@resolveio/server-lib 20.4.50 → 20.4.51
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,i){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var i,s,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(o,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)s.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;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.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),flag_updates_1=require("../methods/flag-updates"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,r,o,n,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this.serverConfig=t,this.clientDir=r,this._monitorManagerFunction=o,this._isWorkersEnabled=n,this._isWorkerInstance=i,"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(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(t),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<r.length||r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<r.length;a++)i[s[a]]=r[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,u,d=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),l=(0,mongo_manager_1.objectIdHexString)(),d=new Promise(function(t,r){var o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});o.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?r:t)(e.data),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),r(e),o.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:r,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(u=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),d=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(r),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(u),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(u),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),d}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(o,n,i,s,a){for(var c,e,l,u,t=this,d=[],r=5;r<arguments.length;r++)d[r-5]=arguments[r];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,d,h={messageId:s,hasError:!0,data:"Internal Error"}),void(o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),h={messageId:s,hasError:!0,data:"Internal Error"},o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}),void this.sendWS(n,i,a,d,h);for(var h,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),f=0;f<d.length;f++)_[g[f]]=d[f];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,d,h={messageId:s,hasError:!0,data:"Internal Error"}),void(o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}))}}this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a&&"incorrectUser"!==a&&"reloadWS"!==a&&"reconnectWS"!==a&&"disconnectWS"!==a?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",d),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==r.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=r.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,d,t),o?[4,log_method_latency_collection_1.LogMethodLatencies.findById(o)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:o},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:d,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(u=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",d),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],__read(d),!1)).then(function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(u),t={messageId:s,hasError:!1,data:r},this.sendWS(n,i,a,d,t),o)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(o)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:o},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(u),t.sendWS(n,i,a,d,{messageId:s,hasError:!0,data:e}),o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),h={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,d,h),o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<r.length||r[0]&&"function"!=typeof r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r]))<2e5?JSON.stringify([r],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof r[r.length-1]?r.slice(0,-1):r,l=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,r){var o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});o.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?r:t)(e.data),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),r(e),o.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(c),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),r[r.length-1]&&"function"==typeof r[r.length-1]&&l.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,r,o,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(t=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){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){o.setupEmailWatcher()}),[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,i,s;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){i={error:e}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,s=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,7]),t=function(){var t,n,i;return __generator(this,function(e){switch(e.label){case 0:return t=r.emailQueue.values().next().value,r.emailQueue.delete(t),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:t,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:return(n=e.sent())?((i={replyTo:n.reply_to||r.serverConfig.MAIL_REPLY_TO||void 0,from:n.send_from||r.serverConfig.MAIL_FROM,to:n.email,subject:(r.serverConfig.ROOT_URL.match(/https:\/\/dev\./)||r.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+n.subject,text:"string"==typeof n.text?n.text:"",html:"string"==typeof n.html?n.html:"",attachments:n.attachments||[]}).attachments&&0<i.attachments.length&&(i.attachments=i.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})),[4,new Promise(function(r,o){try{s._mailer.sendMail(i,function(t,e){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){return t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}}),o(t)):("dev@resolveio.com"===n.email?email_history_collection_1.EmailHistories.deleteOne({_id:n._id}):email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"completed",completedAt:new Date}}),r()),[2]})})})}catch(e){console.error("Failed to send email:",e),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof e?e:s.safeStringify(e),completedAt:new Date}}),o(e)}})]):[2,"continue"];case 2:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 3:return e.sent(),[2]}})},r=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,7];case 5:return o=e.sent(),console.error("Error processing email queue:",o),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7: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(n,i,s,a,c,l,u,d){var e=this;return void 0===d&&(d=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(n=!this.serverConfig.ROOT_URL.match(/https:\/\/dev\./)&&!this.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||n.match(/\@resolveio\.com/)?n:"dev@resolveio.com")?"http://localhost:4200"!==this.serverConfig.ROOT_URL||d?(c=c||[],c=(c=Array.isArray(c)?c:[c]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:n,subject:i||"",text:s||"",html:a||"",attachments:c||[],send_from:l||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),o(e)})):(console.log("Send email",n,i,s,a,c,l),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?o(e):r(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?o(e):r(t)})})},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,i){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var i,s,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(o,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)s.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;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.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),flag_updates_1=require("../methods/flag-updates"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,r,o,n,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this.serverConfig=t,this.clientDir=r,this._monitorManagerFunction=o,this._isWorkersEnabled=n,this._isWorkerInstance=i,"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(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(t),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<r.length||r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<r.length;a++)i[s[a]]=r[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,u,d=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),l=(0,mongo_manager_1.objectIdHexString)(),d=new Promise(function(t,r){var o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});o.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?r:t)(e.data),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),r(e),o.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:r,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(u=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),d=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(r),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(u),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(u),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),d}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(o,n,i,s,a){for(var c,e,l,u,t=this,d=[],r=5;r<arguments.length;r++)d[r-5]=arguments[r];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,d,h={messageId:s,hasError:!0,data:"Internal Error"}),void(o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),h={messageId:s,hasError:!0,data:"Internal Error"},o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}),void this.sendWS(n,i,a,d,h);for(var h,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),f=0;f<d.length;f++)_[g[f]]=d[f];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,d,h={messageId:s,hasError:!0,data:"Internal Error"}),void(o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}))}}this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a&&"incorrectUser"!==a&&"reloadWS"!==a&&"reconnectWS"!==a&&"disconnectWS"!==a?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",d),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==r.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=r.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,d,t),o?[4,log_method_latency_collection_1.LogMethodLatencies.findById(o)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:o},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:d,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(u=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",d),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],__read(d),!1)).then(function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(u),t={messageId:s,hasError:!1,data:r},this.sendWS(n,i,a,d,t),o)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(o)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:o},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(u),t.sendWS(n,i,a,d,{messageId:s,hasError:!0,data:e}),o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),h={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,d,h),o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<r.length||r[0]&&"function"!=typeof r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r]))<2e5?JSON.stringify([r],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof r[r.length-1]?r.slice(0,-1):r,l=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,r){var o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});o.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?r:t)(e.data),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),r(e),o.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(c),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),r[r.length-1]&&"function"==typeof r[r.length-1]&&l.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,r,o,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(t=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){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){o.setupEmailWatcher()}),[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,i,s;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){i={error:e}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,i=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,7]),t=function(){var t,o,n;return __generator(this,function(e){switch(e.label){case 0:return t=r.emailQueue.values().next().value,r.emailQueue.delete(t),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:t,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:return(o=e.sent())?((n={replyTo:o.reply_to||r.serverConfig.MAIL_REPLY_TO||void 0,from:o.send_from||r.serverConfig.MAIL_FROM,to:o.email,subject:(r.serverConfig.ROOT_URL.match(/https:\/\/dev\./)||r.serverConfig.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<n.attachments.length&&(n.attachments=n.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})),[4,new Promise(function(r,e){try{i._mailer.sendMail(n,function(t,e){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){return t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===o.email?email_history_collection_1.EmailHistories.deleteOne({_id:o._id}):email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}}),r(),[2]})})})}catch(e){console.error("Failed to send email:",e),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof e?e:i.safeStringify(e),completedAt:new Date}}),r()}})]):[2,"continue"];case 2:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 3:return e.sent(),[2]}})},r=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,7];case 5:return o=e.sent(),console.error("Error processing email queue:",o),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7: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(n,i,s,a,c,l,u,d){var e=this;return void 0===d&&(d=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(n=!this.serverConfig.ROOT_URL.match(/https:\/\/dev\./)&&!this.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||n.match(/\@resolveio\.com/)?n:"dev@resolveio.com")?"http://localhost:4200"!==this.serverConfig.ROOT_URL||d?(c=c||[],c=(c=Array.isArray(c)?c:[c]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:n,subject:i||"",text:s||"",html:a||"",attachments:c||[],send_from:l||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),o(e)})):(console.log("Send email",n,i,s,a,c,l),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?o(e):r(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?o(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
|
|
2
2
|
//# sourceMappingURL=method.manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","flag_updates_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","console","log","Date","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMainServer","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","monitor_2","taskId_1","monitor_3","promise","startMonitorFunction","objectIdHexString","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","data","close","WorkerTaskRequests","create","_id","params","status","id_user","id_ws","_a","function","call","apply","__spreadArray","__read","then","res","methodErrs","callMethod","id_methodLatency","ws","messageDate","messageId","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","Logs","insertOne","type","collection","id_document","payload","getBinarySize","route","monitor_6","taskId_2","monitor_7","functionMethodData","slice","send","EmailHistories","add","toString","tryProcessEmail","updatedEmail","has","delete","loadPendingEmails","find","sort","pendingEmails","_b","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","processingAt","emailHistory","mailOptions","replyTo","reply_to","undefined","from","send_from","MAIL_FROM","to","subject","match","text","html","attachments","map","att","newAtt","__assign","content","Buffer","encoding","_bsontype","sub_type","buffer","sendMail","info","safeStringify","completedAt","err_1","obj","getCircularReplacer","e","concat","message","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","history","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"ihFACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,SAAAd,QAAA,gBAAA,EACAe,iBAAAf,QAAA,+BAAA,EAEAgB,gCAAAhB,QAAA,8CAAA,EACAiB,OAAAjB,QAAA,iBAAA,EACAkB,iBAAAlB,QAAA,2BAAA,EACAmB,UAAAnB,QAAA,oBAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,2BAAArB,QAAA,yCAAA,EACAsB,gBAAAtB,QAAA,iBAAA,EAEAuB,YAAAvB,QAAA,oBAAA,EACAwB,iCAAAxB,QAAA,+CAAA,EACAyB,kCAA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,EAAAzB,KACC,OAAO,IAAI+G,QAAQ,SAACC,EAASC,GACxBxI,GAAGwR,WAAWzR,KAAK0R,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEvR,GAAGsR,SAASvR,KAAK0R,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACxF,EAAK1B,GACzE0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,EAGGrK,GAAGwR,WAAWzR,KAAK0R,KAAKzO,EAAKJ,UAAY,aAAe2O,CAAS,CAAC,GACrEvR,GAAGsR,SAASvR,KAAK0R,KAAKzO,EAAKJ,UAAY,aAAe2O,CAAS,EAAG,SAAU,SAACxF,EAAK1B,GAC7E0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACD5H,aAAA,EAAC,GAr9BYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { EmailHistoryModel } from '../models/email-history.model';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3(): S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1(): S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._websocketManager = this._mainServer.getWebSocketManager();\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\t// Fixtures\n\t\tif (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(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tloadServerInit(serverConfig);\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\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadFlagUpdatesMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\n\n\t\tif (mainServer.sesMail) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tthis.setupEmailWatcher();\n\t\t}\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', change => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', error => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', async change => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\t\tif (latency) {\n\t\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', error => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\terr => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution' && method !== 'incCounter' && method !== 'supportCreateBillingUser' && method !== 'countCollectionWithQuery') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\t\tlet promise = null;\n\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', error => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t},\n\t\t\t\tmethodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\t\t\t});\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'client-response',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload:\n\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t: 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\tuser: ws['user'] || '',\n\t\t\t\tmessageId: data.messageId,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\t// MethodResponses.create({\n\t\t// \t_id: objectIdHexString(),\n\t\t// \t__v: 0,\n\t\t// \tid_user: ws['id_user'] || '',\n\t\t// \tmessage_id: data.messageId,\n\t\t// \tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t// \tmethod: method,\n\t\t// \tdate: messageDate\n\t\t// });\n\t}\n\n\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\tthis.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', err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tchangeStream.close();\n\t\t})\n\t\t.on('close', () => {\n\t\t\tthis.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\tthis.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// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (this.serverConfig['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || this.serverConfig.MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tthis.serverConfig['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\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis._mailer.sendMail(mailOptions, async (err, info) => {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\t\tEmailHistories.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: 'failed',\n\t\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\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\treject(err);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\t\tEmailHistories.deleteOne({ _id: emailHistory._id });\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\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date()\n\t\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\t\tresolve();\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 send email:', err);\n\t\t\t\t\t\tEmailHistories.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\treject(err);\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\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\tthis.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 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\treturn new Promise(async (resolve, reject) => {\n\t\t\t// Modify sendTo in development environments\n\t\t\tif (\n\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t\t) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\t\n\t\t\tif (sendTo) {\n\t\t\t\tif (\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\t\tlocal_override\n\t\t\t\t) {\n\t\t\t\t\tif (!attachments) {\n\t\t\t\t\t\tattachments = [];\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\t\tattachments = [attachments];\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// Process attachments before saving\n\t\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\n\t\t\t\t\t// Queue the email in MongoDB\n\t\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate: new Date(),\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\temail: sendTo,\n\t\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\t\ttext: text || '',\n\t\t\t\t\t\thtml: html || '',\n\t\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t\terror: ''\n\t\t\t\t\t};\n\t\n\t\t\t\t\tEmailHistories.insertOne(emailHistory).then(\n\t\t\t\t\t\t(history) => resolve(history),\n\t\t\t\t\t\t(err) => {\n\t\t\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'Send email',\n\t\t\t\t\t\tsendTo,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\thtml,\n\t\t\t\t\t\tattachments,\n\t\t\t\t\t\tsend_from\n\t\t\t\t\t);\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","flag_updates_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","console","log","Date","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMainServer","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","monitor_2","taskId_1","monitor_3","promise","startMonitorFunction","objectIdHexString","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","data","close","WorkerTaskRequests","create","_id","params","status","id_user","id_ws","_a","function","call","apply","__spreadArray","__read","then","res","methodErrs","callMethod","id_methodLatency","ws","messageDate","messageId","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","Logs","insertOne","type","collection","id_document","payload","getBinarySize","route","monitor_6","taskId_2","monitor_7","functionMethodData","slice","send","EmailHistories","add","toString","tryProcessEmail","updatedEmail","has","delete","loadPendingEmails","find","sort","pendingEmails","_b","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","processingAt","emailHistory","mailOptions","replyTo","reply_to","undefined","from","send_from","MAIL_FROM","to","subject","match","text","html","attachments","map","att","newAtt","__assign","content","Buffer","encoding","_bsontype","sub_type","buffer","sendMail","info","safeStringify","completedAt","err_1","obj","getCircularReplacer","e","concat","message","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","history","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"ihFACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,SAAAd,QAAA,gBAAA,EACAe,iBAAAf,QAAA,+BAAA,EAEAgB,gCAAAhB,QAAA,8CAAA,EACAiB,OAAAjB,QAAA,iBAAA,EACAkB,iBAAAlB,QAA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G,QAAS,SAACxF,EAAK1B,GAC5E0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEO5H,cAAAd,UAAAgQ,UAAP,SAAiBJ,GAAjB,IAAAvO,EAAAzB,KACC,OAAO,IAAI+G,QAAQ,SAACC,EAASC,GACxBxI,GAAGwR,WAAWzR,KAAK0R,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEvR,GAAGsR,SAASvR,KAAK0R,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACxF,EAAK1B,GACzE0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,EAGGrK,GAAGwR,WAAWzR,KAAK0R,KAAKzO,EAAKJ,UAAY,aAAe2O,CAAS,CAAC,GACrEvR,GAAGsR,SAASvR,KAAK0R,KAAKzO,EAAKJ,UAAY,aAAe2O,CAAS,EAAG,SAAU,SAACxF,EAAK1B,GAC7E0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACD5H,aAAA,EAAC,GAr9BYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { EmailHistoryModel } from '../models/email-history.model';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3(): S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1(): S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._websocketManager = this._mainServer.getWebSocketManager();\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\t// Fixtures\n\t\tif (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(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tloadServerInit(serverConfig);\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\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadFlagUpdatesMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\n\n\t\tif (mainServer.sesMail) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tthis.setupEmailWatcher();\n\t\t}\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', change => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', error => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', async change => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\t\tif (latency) {\n\t\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', error => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\terr => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution' && method !== 'incCounter' && method !== 'supportCreateBillingUser' && method !== 'countCollectionWithQuery') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\t\tlet promise = null;\n\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', error => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t},\n\t\t\t\tmethodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\t\t\t});\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'client-response',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload:\n\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t: 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\tuser: ws['user'] || '',\n\t\t\t\tmessageId: data.messageId,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\t// MethodResponses.create({\n\t\t// \t_id: objectIdHexString(),\n\t\t// \t__v: 0,\n\t\t// \tid_user: ws['id_user'] || '',\n\t\t// \tmessage_id: data.messageId,\n\t\t// \tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t// \tmethod: method,\n\t\t// \tdate: messageDate\n\t\t// });\n\t}\n\n\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\tthis.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', err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tchangeStream.close();\n\t\t})\n\t\t.on('close', () => {\n\t\t\tthis.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\tthis.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// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (this.serverConfig['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || this.serverConfig.MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tthis.serverConfig['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\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis._mailer.sendMail(mailOptions, async (err, info) => {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\t\tEmailHistories.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: 'failed',\n\t\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\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\tresolve();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\t\tEmailHistories.deleteOne({ _id: emailHistory._id });\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\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date()\n\t\t\t\t\t\t\t\t\t\t\t},\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\n\t\t\t\t\t\t\t\tresolve();\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 send email:', err);\n\t\t\t\t\t\tEmailHistories.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\tresolve();\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\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\tthis.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 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\treturn new Promise(async (resolve, reject) => {\n\t\t\t// Modify sendTo in development environments\n\t\t\tif (\n\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t\t) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\t\n\t\t\tif (sendTo) {\n\t\t\t\tif (\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\t\tlocal_override\n\t\t\t\t) {\n\t\t\t\t\tif (!attachments) {\n\t\t\t\t\t\tattachments = [];\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\t\tattachments = [attachments];\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// Process attachments before saving\n\t\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\n\t\t\t\t\t// Queue the email in MongoDB\n\t\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate: new Date(),\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\temail: sendTo,\n\t\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\t\ttext: text || '',\n\t\t\t\t\t\thtml: html || '',\n\t\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t\terror: ''\n\t\t\t\t\t};\n\t\n\t\t\t\t\tEmailHistories.insertOne(emailHistory).then(\n\t\t\t\t\t\t(history) => resolve(history),\n\t\t\t\t\t\t(err) => {\n\t\t\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'Send email',\n\t\t\t\t\t\tsendTo,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\thtml,\n\t\t\t\t\t\tattachments,\n\t\t\t\t\t\tsend_from\n\t\t\t\t\t);\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
|