@resolveio/server-lib 20.7.76 → 20.7.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(r){return function(e){var t=[r,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(o,c)}catch(e){t=[6,e],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,s=r.call(e),i=[];try{for(;(void 0===t||0<t--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,s=t.length;n<s;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},client_s3_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("@aws-sdk/client-s3")),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),path=require("path"),email_history_collection_1=require("../collections/email-history.collection"),log_collection_1=require("../collections/log.collection"),cron_jobs_1=require("../fixtures/cron-jobs"),init_1=require("../fixtures/init"),accounts_1=require("../methods/accounts"),aws_1=require("../methods/aws"),collections_1=require("../methods/collections"),counters_1=require("../methods/counters"),cron_jobs_2=require("../methods/cron-jobs"),flag_updates_1=require("../methods/flag-updates"),flags_1=require("../methods/flags"),logs_1=require("../methods/logs"),monitor_1=require("../methods/monitor"),pdf_1=require("../methods/pdf"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),resolveio_server_app_1=require("../resolveio-server-app"),common_1=require("../util/common"),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.create=function(){var e=new AWS;return e.initialize(),e},AWS.prototype.initialize=function(){},AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(){this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugcallMethodHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this.clientDir="",this.serverConfig=""}return MethodManager.create=function(e,t,r,o){var n=new MethodManager;return n.initialize(e,t,r,o),n},MethodManager.prototype.initialize=function(e,t,r,o){var n=this;this._websocketManager=e,this._monitorManagerFunction=t,this._isWorkersEnabled=r,this._isWorkerInstance=o,this.clientDir=resolveio_server_app_1.ResolveIOServer.getClientDir(),this.serverConfig=resolveio_server_app_1.ResolveIOServer.getServerConfig(),process.env.IS_WORKERS_ENABLED&&"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.log(new Date,"Start Server Fixture"),[4,(0,init_1.loadServerInit)()];case 1:return e.sent(),console.log(new Date,"End Server Fixture"),[2]}})})},5e3),setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,(0,cron_jobs_1.loadServerCronJobs)()];case 1:return e.sent(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),[2]}})})}),this._aws=new AWS,resolveio_server_app_1.ResolveIOServer.getSESMail()?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_HOST,port:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PORT,secure:!1,auth:{user:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_USERNAME,pass:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",n._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",n._debugcallMethodHits),console.log(new Date,"Method Manager","Call Method Hits",n._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",n._debugCallMethodCronJobHits)),n._debugcallMethodHits=0,n._debugCallMethodHits=0,n._debugCallMethodCronJobHits=0,n._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})})},MethodManager.prototype.getMethod=function(e){return this._methods[e]},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(c){for(var l=[],e=1;e<arguments.length;e++)l[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i,a;return __generator(this,function(e){switch(e.label){case 0:return(this._debugCallMethodCronJobHits+=1,this._methods[c])?[3,2]:(console.log("No Method: "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+c)]);case 1:throw e.sent(),new Error("No Method: "+c);case 2:return!(1<l.length||l[0])||this._methods[c].skipValidation?[3,10]:this._methods[c].check?[3,4]:(console.error(new Date,"No Check Function For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 3:throw e.sent(),new Error("No Check Function For Cron Method "+c);case 4:return this._methods[c].check._schema?[3,6]:(console.error(new Date,"No Check Schema For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 5:throw e.sent(),new Error("No Check Schema For Cron Method "+c);case 6:for(t={},a=Object.keys(this._methods[c].check._schema),r=a.filter(function(e){return!e.includes(".")}),o=0;o<l.length;o++)t[r[o]]=l[o];e.label=7;case 7:return e.trys.push([7,8,,10]),this._methods[c].check.validate(t),[3,10];case 8:return n=e.sent(),console.error(new Date,"Error in Cron Method Check ("+c+")",n),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Cron Method "+c+"\n\nData Being Checked\n"+JSON.stringify(t,null,2)+"\n\nErrors\n"+JSON.stringify(n,null,2))];case 9:throw e.sent(),n.message="".concat((new Date).toISOString()," - Error in Cron Method Check (").concat(c,"): ").concat(n.message),n;case 10:s=this._monitorManagerFunction.startMonitorFunction("Cron Method",c,"","",l),e.label=11;case 11:return e.trys.push([11,13,15,17]),[4,(a=this._methods[c].function).call.apply(a,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(l),!1))];case 12:return[2,e.sent()];case 13:return i=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Cron Method "+c+" - (callMethodCron)\n\nData \n"+JSON.stringify(l,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2))];case 14:throw e.sent(),i.message="".concat((new Date).toISOString()," - Error in Cron Method (").concat(c,"): ").concat(i.message),i;case 15:return[4,this._monitorManagerFunction.finishMonitorFunction(s)];case 16:return e.sent(),[7];case 17:return[2]}})})},MethodManager.prototype.callMethod=function(a){for(var c=[],e=1;e<arguments.length;e++)c[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var o,n,t,r,s,i=this;return __generator(this,function(e){switch(e.label){case 0:if(this._debugcallMethodHits+=1,!this._methods[a])throw console.log("No Method: "+a),new Error("No Method: ".concat(a));if((1<c.length||c[0]&&"function"!=typeof c[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)throw console.error(new Date,"No Check Function For Method "+a),new Error("No Check Function For Method: ".concat(a));if(!this._methods[a].check._schema)throw console.error(new Date,"No Check Schema For Method "+a),new Error("No Check Schema For Method: ".concat(a))}return"insertSubscriptionLog"===a||"getDataURIfromURL"===a||"processAirdropDistribution"===a||"incCounter"===a||"supportCreateBillingUser"===a||"countCollectionWithQuery"===a?[3,4]:"https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?[3,1]:(resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([c]))<2e5?JSON.stringify([c],null,2):"Too Big",method:a,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""}}),[3,3]);case 1:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([c]))<2e5?JSON.stringify([c],null,2):"Too Big",method:a,id_user:this.id_user||"",user:this.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 2:e.sent(),e.label=3;case 3:e.label=4;case 4:return(o="function"==typeof c[c.length-1]?c.slice(0,-1):c,resolveio_server_app_1.ResolveIOServer.getMongoManager().getSession()||["insertErrorLog","countWithQuery","sendEmail"].includes(a)||a.startsWith("monitor-")||a.startsWith("log"))?[3,5]:(n=null,[2,resolveio_server_app_1.ResolveIOServer.getMongoManager().oneTimeTransaction(function(){return __awaiter(i,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:n=this._monitorManagerFunction.startMonitorFunction("Method",a,this.user||"","",o),e.label=1;case 1:return e.trys.push([1,3,7,9]),[4,(r=this._methods[a].function).call.apply(r,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(o),!1))];case 2:return r=e.sent(),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](null,r),[2,r];case 3:return t=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(t,null,2))];case 4:return e.sent(),t.message="".concat((new Date).toISOString()," - Error in Method With Session (").concat(a,") - New Session: ").concat(t.message),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](t,null),process.env.IS_WORKER_INSTANCE?[3,6]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(a," - ").concat(JSON.stringify(c,null,2)))];case 5:e.sent(),e.label=6;case 6:throw t;case 7:return[4,this._monitorManagerFunction.finishMonitorFunction(n)];case 8:return e.sent(),[7];case 9:return[2]}})})})]);case 5:t=this._monitorManagerFunction.startMonitorFunction("Method",a,this.user||"","",o),e.label=6;case 6:return e.trys.push([6,8,12,14]),[4,(s=this._methods[a].function).call.apply(s,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(o),!1))];case 7:return s=e.sent(),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](null,s),[2,s];case 8:return r=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(r,null,2))];case 9:return e.sent(),r.message="".concat((new Date).toISOString()," - Error in Method (").concat(a,") - Existing Session: ").concat(r.message),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](r,null),process.env.IS_WORKER_INSTANCE?[3,11]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(a," - ").concat(JSON.stringify(c,null,2)))];case 10:e.sent(),e.label=11;case 11:throw r;case 12:return[4,this._monitorManagerFunction.finishMonitorFunction(t)];case 13:return e.sent(),[7];case 14:return[2]}})})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var r,o=this;return __generator(this,function(e){switch(e.label){case 0:return(r=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),[4,this.tryProcessEmail()]):[3,2];case 1:return e.sent(),[3,3];case 2:"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),e.label=3;case 3:return[2]}})})}).on("error",function(t){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.error("Email history changestream error",t),[4,r.close()];case 1:return e.sent(),[2]}})})}).on("close",function(){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return[4,this.tryProcessEmail()];case 2:return e.sent(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,u,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,9]),t=function(){var o,t,r,n,s,i,a,c,l;return __generator(this,function(e){switch(e.label){case 0:return s=u.emailQueue.values().next().value,u.emailQueue.delete(s),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:s,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(o=e.sent()))return[2,"continue"];if(!(o.attachments&&0<o.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),c=void 0,t=__values(o.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(n=r.value).path&&n.path.startsWith("http")?[4,fetch(n.path)]:[3,7];case 5:if((s=e.sent()).ok)return[4,s.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:i=e.sent(),i=Buffer.from(i),i.length<=20971520&&(n.content=i,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return i=e.sent(),c={error:i},[3,11];case 10:try{r&&!r.done&&(l=t.return)&&l.call(t)}finally{if(c)throw c.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof a?a:u.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(a={replyTo:o.reply_to||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_REPLY_TO||void 0,from:o.send_from||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_FROM,to:o.email,subject:(resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)||resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+o.subject,text:"string"==typeof o.text?o.text:"",html:"string"==typeof o.html?o.html:"",attachments:o.attachments||[]}).attachments&&0<a.attachments.length&&(a.attachments=a.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),u._mailer.sendMail(a,function(r){return __awaiter(h,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(e.trys.push([0,7,,9]),r)?(console.error("Failed to send email:",r),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof r?r:this.safeStringify(r),completedAt:new Date}})]):[3,2];case 1:return e.sent(),[3,6];case 2:return"dev@resolveio.com"!==o.email?[3,4]:[4,email_history_collection_1.EmailHistories.deleteOne({_id:o._id})];case 3:return e.sent(),[3,6];case 4:return[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})];case 5:e.sent(),e.label=6;case 6:return[3,9];case 7:return t=e.sent(),console.error("Error in sendMail callback:",t),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})];case 8:return e.sent(),[3,9];case 9:return[2]}})})}),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 15:return e.sent(),[2]}})},u=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,9];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,9];case 6:return(this.isEmailProcessing=!1,0<this.emailQueue.size)?[4,this.tryProcessEmail()]:[3,8];case 7:e.sent(),e.label=8;case 8:return[7];case 9:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(o,n,s,i,a,c,l,u){return void 0===u&&(u=!1),__awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:if(!(o=!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)&&!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||o.match(/\@resolveio\.com/)?o:"dev@resolveio.com"))return[3,7];if("http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&!u)return[3,5];a=a||[],a=(a=Array.isArray(a)?a:[a]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:o,subject:n||"",text:s||"",html:i||"",attachments:a||[],send_from:c||"",reply_to:l||"",status:"pending",error:""},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,email_history_collection_1.EmailHistories.insertOne(t)];case 2:return[2,e.sent()];case 3:throw r=e.sent(),console.error("Failed to queue email:",r),r.message="Failed to queue email: ".concat(r.message),r;case 4:return[3,6];case 5:return console.log("Send email",o,n,s,i,a,c),[2,!0];case 6:return[3,8];case 7:return[2,!0];case 8:return[2]}})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}throw new Error("Error in readFile: File Not Found")},MethodManager.prototype.readImage=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}throw new Error("Error in readImage: File Not Found")},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(r){return function(e){var t=[r,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(o,c)}catch(e){t=[6,e],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,s=r.call(e),i=[];try{for(;(void 0===t||0<t--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,s=t.length;n<s;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},client_s3_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("@aws-sdk/client-s3")),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),path=require("path"),email_history_collection_1=require("../collections/email-history.collection"),log_collection_1=require("../collections/log.collection"),cron_jobs_1=require("../fixtures/cron-jobs"),init_1=require("../fixtures/init"),accounts_1=require("../methods/accounts"),aws_1=require("../methods/aws"),collections_1=require("../methods/collections"),counters_1=require("../methods/counters"),cron_jobs_2=require("../methods/cron-jobs"),flag_updates_1=require("../methods/flag-updates"),flags_1=require("../methods/flags"),logs_1=require("../methods/logs"),monitor_1=require("../methods/monitor"),pdf_1=require("../methods/pdf"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),resolveio_server_app_1=require("../resolveio-server-app"),common_1=require("../util/common"),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.create=function(){var e=new AWS;return e.initialize(),e},AWS.prototype.initialize=function(){},AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(){this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugcallMethodHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this.clientDir="",this.serverConfig=""}return MethodManager.create=function(e,t,r,o){var n=new MethodManager;return n.initialize(e,t,r,o),n},MethodManager.prototype.initialize=function(e,t,r,o){var n=this;this._websocketManager=e,this._monitorManagerFunction=t,this._isWorkersEnabled=r,this._isWorkerInstance=o,this.clientDir=resolveio_server_app_1.ResolveIOServer.getClientDir(),this.serverConfig=resolveio_server_app_1.ResolveIOServer.getServerConfig(),process.env.IS_WORKERS_ENABLED&&"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.log(new Date,"Start Server Fixture"),[4,(0,init_1.loadServerInit)()];case 1:return e.sent(),console.log(new Date,"End Server Fixture"),[2]}})})},5e3),setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,(0,cron_jobs_1.loadServerCronJobs)()];case 1:return e.sent(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),[2]}})})}),this._aws=new AWS,resolveio_server_app_1.ResolveIOServer.getSESMail()?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_HOST,port:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PORT,secure:!1,auth:{user:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_USERNAME,pass:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",n._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",n._debugcallMethodHits),console.log(new Date,"Method Manager","Call Method Hits",n._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",n._debugCallMethodCronJobHits)),n._debugcallMethodHits=0,n._debugCallMethodHits=0,n._debugCallMethodCronJobHits=0,n._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})})},MethodManager.prototype.getMethod=function(e){return this._methods[e]},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(c){for(var l=[],e=1;e<arguments.length;e++)l[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i,a;return __generator(this,function(e){switch(e.label){case 0:return(this._debugCallMethodCronJobHits+=1,this._methods[c])?[3,2]:(console.log("No Method: "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+c)]);case 1:throw e.sent(),new Error("No Method: "+c);case 2:return!(1<l.length||l[0])||this._methods[c].skipValidation?[3,10]:this._methods[c].check?[3,4]:(console.error(new Date,"No Check Function For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 3:throw e.sent(),new Error("No Check Function For Cron Method "+c);case 4:return this._methods[c].check._schema?[3,6]:(console.error(new Date,"No Check Schema For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 5:throw e.sent(),new Error("No Check Schema For Cron Method "+c);case 6:for(t={},a=Object.keys(this._methods[c].check._schema),r=a.filter(function(e){return!e.includes(".")}),o=0;o<l.length;o++)t[r[o]]=l[o];e.label=7;case 7:return e.trys.push([7,8,,10]),this._methods[c].check.validate(t),[3,10];case 8:return n=e.sent(),console.error(new Date,"Error in Cron Method Check ("+c+")",n),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Cron Method "+c+"\n\nData Being Checked\n"+JSON.stringify(t,null,2)+"\n\nErrors\n"+JSON.stringify(n,null,2))];case 9:throw e.sent(),n.message="".concat((new Date).toISOString()," - Error in Cron Method Check (").concat(c,"): ").concat(n.message),n;case 10:s=this._monitorManagerFunction.startMonitorFunction("Cron Method",c,"","",l),e.label=11;case 11:return e.trys.push([11,13,15,17]),[4,(a=this._methods[c].function).call.apply(a,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(l),!1))];case 12:return[2,e.sent()];case 13:return i=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Cron Method "+c+" - (callMethodCron)\n\nData \n"+JSON.stringify(l,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2))];case 14:throw e.sent(),i.message="".concat((new Date).toISOString()," - Error in Cron Method (").concat(c,"): ").concat(i.message),i;case 15:return[4,this._monitorManagerFunction.finishMonitorFunction(s)];case 16:return e.sent(),[7];case 17:return[2]}})})},MethodManager.prototype.callMethod=function(a){for(var c=[],e=1;e<arguments.length;e++)c[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var o,n,t,r,s,i=this;return __generator(this,function(e){switch(e.label){case 0:if(this._debugcallMethodHits+=1,!this._methods[a])throw console.log("No Method: "+a),new Error("No Method: ".concat(a));if((1<c.length||c[0]&&"function"!=typeof c[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)throw console.error(new Date,"No Check Function For Method "+a),new Error("No Check Function For Method: ".concat(a));if(!this._methods[a].check._schema)throw console.error(new Date,"No Check Schema For Method "+a),new Error("No Check Schema For Method: ".concat(a))}return"insertSubscriptionLog"===a||"getDataURIfromURL"===a||"processAirdropDistribution"===a||"incCounter"===a||"supportCreateBillingUser"===a||"countCollectionWithQuery"===a?[3,4]:"https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?[3,1]:(resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([c]))<1e6?JSON.stringify([c],null,2):"Too Big",method:a,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""}}),[3,3]);case 1:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([c]))<1e6?JSON.stringify([c],null,2):"Too Big",method:a,id_user:this.id_user||"",user:this.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 2:e.sent(),e.label=3;case 3:e.label=4;case 4:return(o="function"==typeof c[c.length-1]?c.slice(0,-1):c,resolveio_server_app_1.ResolveIOServer.getMongoManager().getSession()||["insertErrorLog","countWithQuery","sendEmail"].includes(a)||a.startsWith("monitor-")||a.startsWith("log"))?[3,5]:(n=null,[2,resolveio_server_app_1.ResolveIOServer.getMongoManager().oneTimeTransaction(function(){return __awaiter(i,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:n=this._monitorManagerFunction.startMonitorFunction("Method",a,this.user||"","",o),e.label=1;case 1:return e.trys.push([1,3,7,9]),[4,(r=this._methods[a].function).call.apply(r,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(o),!1))];case 2:return r=e.sent(),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](null,r),[2,r];case 3:return t=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(t,null,2))];case 4:return e.sent(),t.message="".concat((new Date).toISOString()," - Error in Method With Session (").concat(a,") - New Session: ").concat(t.message),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](t,null),process.env.IS_WORKER_INSTANCE?[3,6]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(a," - ").concat(JSON.stringify(c,null,2)))];case 5:e.sent(),e.label=6;case 6:throw t;case 7:return[4,this._monitorManagerFunction.finishMonitorFunction(n)];case 8:return e.sent(),[7];case 9:return[2]}})})})]);case 5:t=this._monitorManagerFunction.startMonitorFunction("Method",a,this.user||"","",o),e.label=6;case 6:return e.trys.push([6,8,12,14]),[4,(s=this._methods[a].function).call.apply(s,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(o),!1))];case 7:return s=e.sent(),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](null,s),[2,s];case 8:return r=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(r,null,2))];case 9:return e.sent(),r.message="".concat((new Date).toISOString()," - Error in Method (").concat(a,") - Existing Session: ").concat(r.message),c[c.length-1]&&"function"==typeof c[c.length-1]&&c[c.length-1](r,null),process.env.IS_WORKER_INSTANCE?[3,11]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(a," - ").concat(JSON.stringify(c,null,2)))];case 10:e.sent(),e.label=11;case 11:throw r;case 12:return[4,this._monitorManagerFunction.finishMonitorFunction(t)];case 13:return e.sent(),[7];case 14:return[2]}})})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var r,o=this;return __generator(this,function(e){switch(e.label){case 0:return(r=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),[4,this.tryProcessEmail()]):[3,2];case 1:return e.sent(),[3,3];case 2:"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),e.label=3;case 3:return[2]}})})}).on("error",function(t){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.error("Email history changestream error",t),[4,r.close()];case 1:return e.sent(),[2]}})})}).on("close",function(){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return[4,this.tryProcessEmail()];case 2:return e.sent(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,u,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,9]),t=function(){var o,t,r,n,s,i,a,c,l;return __generator(this,function(e){switch(e.label){case 0:return s=u.emailQueue.values().next().value,u.emailQueue.delete(s),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:s,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(o=e.sent()))return[2,"continue"];if(!(o.attachments&&0<o.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),c=void 0,t=__values(o.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(n=r.value).path&&n.path.startsWith("http")?[4,fetch(n.path)]:[3,7];case 5:if((s=e.sent()).ok)return[4,s.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:i=e.sent(),i=Buffer.from(i),i.length<=20971520&&(n.content=i,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return i=e.sent(),c={error:i},[3,11];case 10:try{r&&!r.done&&(l=t.return)&&l.call(t)}finally{if(c)throw c.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof a?a:u.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(a={replyTo:o.reply_to||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_REPLY_TO||void 0,from:o.send_from||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_FROM,to:o.email,subject:(resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)||resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+o.subject,text:"string"==typeof o.text?o.text:"",html:"string"==typeof o.html?o.html:"",attachments:o.attachments||[]}).attachments&&0<a.attachments.length&&(a.attachments=a.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),u._mailer.sendMail(a,function(r){return __awaiter(h,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(e.trys.push([0,7,,9]),r)?(console.error("Failed to send email:",r),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof r?r:this.safeStringify(r),completedAt:new Date}})]):[3,2];case 1:return e.sent(),[3,6];case 2:return"dev@resolveio.com"!==o.email?[3,4]:[4,email_history_collection_1.EmailHistories.deleteOne({_id:o._id})];case 3:return e.sent(),[3,6];case 4:return[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})];case 5:e.sent(),e.label=6;case 6:return[3,9];case 7:return t=e.sent(),console.error("Error in sendMail callback:",t),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})];case 8:return e.sent(),[3,9];case 9:return[2]}})})}),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 15:return e.sent(),[2]}})},u=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,9];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,9];case 6:return(this.isEmailProcessing=!1,0<this.emailQueue.size)?[4,this.tryProcessEmail()]:[3,8];case 7:e.sent(),e.label=8;case 8:return[7];case 9:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(o,n,s,i,a,c,l,u){return void 0===u&&(u=!1),__awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:if(!(o=!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)&&!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||o.match(/\@resolveio\.com/)?o:"dev@resolveio.com"))return[3,7];if("http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&!u)return[3,5];a=a||[],a=(a=Array.isArray(a)?a:[a]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:o,subject:n||"",text:s||"",html:i||"",attachments:a||[],send_from:c||"",reply_to:l||"",status:"pending",error:""},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,email_history_collection_1.EmailHistories.insertOne(t)];case 2:return[2,e.sent()];case 3:throw r=e.sent(),console.error("Failed to queue email:",r),r.message="Failed to queue email: ".concat(r.message),r;case 4:return[3,6];case 5:return console.log("Send email",o,n,s,i,a,c),[2,!0];case 6:return[3,8];case 7:return[2,!0];case 8:return[2]}})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}throw new Error("Error in readFile: File Not Found")},MethodManager.prototype.readImage=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}throw new Error("Error in readImage: File Not Found")},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["client_s3_1","require","fs","nodemailer","sesTransport","path","email_history_collection_1","log_collection_1","cron_jobs_1","init_1","accounts_1","aws_1","collections_1","counters_1","cron_jobs_2","flag_updates_1","flags_1","logs_1","monitor_1","pdf_1","report_builder_1","support_1","resolveio_server_app_1","common_1","AWS","this","_s3","_s3USEast1","prototype","create","aws","initialize","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugcallMethodHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","clientDir","serverConfig","websocketManager","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","methodManager","_this","_websocketManager","_monitorManagerFunction","ResolveIOServer","getClientDir","getServerConfig","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","__awaiter","console","log","Date","loadServerInit","_a","sent","setImmediate","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","getSESMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getMainServer","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMethod","method","methods","Object","assign","callMethodCron","methodData","_i","arguments","length","sendEmail","_b","Error","skipValidation","check","error","_schema","valObj","valKeys","keys","rootKeys","filter","a","includes","i","validate","err_1","JSON","stringify","message","concat","toISOString","monitor","startMonitorFunction","function","call","apply","__spreadArray","id_user","id_ws","__read","err_2","finishMonitorFunction","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","instance_index","functionMethodData","slice","getMongoManager","getSession","startsWith","monitor_2","oneTimeTransaction","res","err_4","err_3","changeStream","EmailHistories","watchCollection","on","change","operationType","fullDocument","status","add","toString","tryProcessEmail","updatedEmail","has","delete","err","close","loadPendingEmails","find","sort","pendingEmails","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","$set","processingAt","emailHistory","_e","attachments","e_2","_c","att","fetch","response","ok","arrayBuffer","buffer","Buffer","from","content","err_6","updateOne","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","sendMail","deleteOne","error_1","Promise","resolve","err_5","obj","getCircularReplacer","e","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","err_7","getAWS","readFile","fileName","existsSync","join","__dirname","readFileSync","readImage"],"mappings":"ihFAAAA,a,gGAAAC,QAAA,oBAAA,GACAC,GAAAD,QAAA,IAAA,EACAE,WAAAF,QAAA,YAAA,EACAG,aAAAH,QAAA,0BAAA,EACAI,KAAAJ,QAAA,MAAA,EACAK,2BAAAL,QAAA,yCAAA,EACAM,iBAAAN,QAAA,+BAAA,EACAO,YAAAP,QAAA,uBAAA,EACAQ,OAAAR,QAAA,kBAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,MAAAV,QAAA,gBAAA,EACAW,cAAAX,QAAA,wBAAA,EACAY,WAAAZ,QAAA,qBAAA,EACAa,YAAAb,QAAA,sBAAA,EACAc,eAAAd,QAAA,yBAAA,EACAe,QAAAf,QAAA,kBAAA,EACAgB,OAAAhB,QAAA,iBAAA,EACAiB,UAAAjB,QAAA,oBAAA,EACAkB,MAAAlB,QAAA,gBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EAGAqB,uBAAArB,QAAA,yBAAA,EACAsB,SAAAtB,QAAA,gBAAA,EAIAuB,IAAA,WAIC,SAAAA,MAHQC,KAAAC,IAAU,K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BAAAC,OAAuBwD,EAAIzD,OAAO,EAC1CyD,C,MAIP,GAAItM,GAAGoR,WAAWjR,KAAKkR,KAAKjQ,uBAAA6C,gBAAgBC,aAAY,EAAK,aAAeiN,CAAS,CAAC,EACrF,IACC,OAAOnR,GAAGuR,aAAapR,KAAKkR,KAAKjQ,uBAAA6C,gBAAgBC,aAAY,EAAK,aAAeiN,CAAS,EAAG,QAAQ,C,CAEtG,MAAO7E,GAEN,MADAA,EAAIzD,QAAU,uBAAAC,OAAuBwD,EAAIzD,OAAO,EAC1CyD,C,CAKT,MAAM,IAAI1E,MAAO,oCAAoC,CACtD,EACDjF,aAAA,EAAC,GArsBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { S3 } from '@aws-sdk/client-s3';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport * as path from 'path';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { Logs } from '../collections/log.collection';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadAWSMethods } from '../methods/aws';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { loadFlagMethods } from '../methods/flags';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { MethodAllModel, MethodModel } from '../models/method.model';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { getBinarySize, objectIdHexString } from '../util/common';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { WebSocketManager } from './websocket.manager';\n\nexport class AWS {\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor() {}\n\n\tpublic create() {\n\t\tconst aws = new AWS();\n\t\taws.initialize();\n\t\treturn aws;\n\t}\n\n\tprivate initialize() {\n\n\t}\n\n\tpublic s3(): S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1(): S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugcallMethodHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tpublic clientDir = '';\n\tpublic serverConfig = '';\n\n\tconstructor() {}\n\n\tstatic create(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tconst methodManager = new MethodManager();\n\t\tmethodManager.initialize(websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance);\n\t\treturn methodManager;\n\t}\n\n\tprivate initialize(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._websocketManager = websocketManager;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\t\t\n\t\tthis.clientDir = ResolveIOServer.getClientDir();\n\t\tthis.serverConfig = ResolveIOServer.getServerConfig();\n\n\t\t// Fixtures\n\t\tif (!process.env.IS_WORKERS_ENABLED || process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tawait loadServerInit();\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetImmediate(async () => {\n\t\t\t// Methods\n\t\t\tawait loadServerCronJobs();\n\n\t\t\tloadAccountMethods(this);\n\t\t\tloadAWSMethods(this);\n\t\t\tloadCollectionMethods(this);\n\t\t\tloadCounterMethods(this);\n\t\t\tloadLogMethods(this);\n\t\t\tloadPDFMethods(this);\n\t\t\tloadCronJobMethods(this);\n\t\t\tloadFlagMethods(this);\n\t\t\tloadFlagUpdatesMethods(this);\n\t\t\tloadReportBuilderMethods(this);\n\t\t\tloadSupportMethods(this);\n\t\t\tloadMonitorMethods(this);\n\t\t});\n\t\t\n\t\tthis._aws = new AWS();\n\t\t\n\t\tif (ResolveIOServer.getSESMail()) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: ResolveIOServer.getServerConfig()['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: ResolveIOServer.getServerConfig()['MAIL_USERNAME'],\n\t\t\t\t\tpass: ResolveIOServer.getServerConfig()['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (ResolveIOServer.getMainServer().getSubscriptionManager() && ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugcallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugcallMethodHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.setupEmailWatcher();\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic getMethod(method: string): MethodAllModel {\n\t\treturn this._methods[method];\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic async callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\tthrow new Error('No Method: ' + method);\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Function For Cron Method ' + method);\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Schema For Cron Method ' + method);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error(new Date(), 'Error in Cron Method Check (' + method + ')', err);\n\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Match Error On Cron Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method Check (${method}): ${err.message}`;\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\ttry {\n\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData);\n\t\t\treturn res;\n\t\t}\n\t\tcatch (err) {\n\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Cron Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\n\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method (${method}): ${err.message}`;\n\t\t\t\n\t\t\tthrow err;\n\t\t}\n\t\tfinally {\n\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic async callMethod(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugcallMethodHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\tthrow new Error(`No Method: ${method}`);\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\tthrow new Error(`No Check Function For Method: ${method}`);\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\tthrow new Error(`No Check Schema For Method: ${method}`);\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\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '', \n\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\tmethod: method,\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\tmessageId: 0,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\n\t\tconst session = ResolveIOServer.getMongoManager().getSession();\n\n\t\tif (!session && \n\t\t\t![\n\t\t\t\t'insertErrorLog', // CIRCULAR LOOP - DO NOT REMOVE\n\t\t\t\t'countWithQuery', // MONGO SESSIONS/TRANSACTIONS DONT WORTH WITH COUNTS\n\t\t\t\t'sendEmail' // ALWAYS SEND SO ALWAYS HAVE RECORD - DONT ROLL BACK - BYPASS SESSION\n\t\t\t].includes(method) &&\n\t\t\t!method.startsWith('monitor-') &&\n\t\t\t!method.startsWith('log')\n\t\t) {\n\t\t\tlet monitor = null;\n\t\t\t\n\t\t\treturn ResolveIOServer.getMongoManager().oneTimeTransaction(async () => {\n\t\t\t\tmonitor = this._monitorManagerFunction.startMonitorFunction('Method', method, this['user'] || '', '', functionMethodData);\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['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\terr.message = `${new Date().toISOString()} - Error in Method With Session (${method}) - New Session: ${err.message}`;\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, this['user'] || '', '', functionMethodData);\n\t\t\t\n\t\t\ttry {\n\t\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t}\n\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['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\terr.message = `${new Date().toISOString()} - Error in Method (${method}) - Existing Session: ${err.message}`;\n\t\t\t\t\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t}\n\n\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', async err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tawait changeStream.close();\n\t\t})\n\t\t.on('close', async () => {\n\t\t\tawait this.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tawait this.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || ResolveIOServer.getServerConfig().MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tthis._mailer.sendMail(mailOptions, async err => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\tawait EmailHistories.deleteOne({ _id: emailHistory._id });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t} \n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\t// eslint-disable-next-line no-restricted-syntax\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic async sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\t// Modify sendTo in development environments\n\t\tif (\n\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t) {\n\t\t\tsendTo = 'dev@resolveio.com';\n\t\t}\n\n\t\tif (sendTo) {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\tlocal_override\n\t\t\t) {\n\t\t\t\tif (!attachments) {\n\t\t\t\t\tattachments = [];\n\t\t\t\t}\n\n\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\tattachments = [attachments];\n\t\t\t\t}\n\n\t\t\t\t// Process attachments before saving\n\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t}\n\t\t\t\t\treturn newAtt;\n\t\t\t\t});\n\n\t\t\t\t// Queue the email in MongoDB\n\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\temail: sendTo,\n\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\ttext: text || '',\n\t\t\t\t\thtml: html || '',\n\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\terror: ''\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\tlet history = await EmailHistories.insertOne(emailHistory);\n\t\t\t\t\treturn history;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\terr.message = `Failed to queue email: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log(\n\t\t\t\t\t'Send email',\n\t\t\t\t\tsendTo,\n\t\t\t\t\tsubject,\n\t\t\t\t\ttext,\n\t\t\t\t\thtml,\n\t\t\t\t\tattachments,\n\t\t\t\t\tsend_from\n\t\t\t\t);\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'utf-8');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readFile: File Not Found');\n\t}\n\n\tpublic readImage(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'base64');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readImage: File Not Found');\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["client_s3_1","require","fs","nodemailer","sesTransport","path","email_history_collection_1","log_collection_1","cron_jobs_1","init_1","accounts_1","aws_1","collections_1","counters_1","cron_jobs_2","flag_updates_1","flags_1","logs_1","monitor_1","pdf_1","report_builder_1","support_1","resolveio_server_app_1","common_1","AWS","this","_s3","_s3USEast1","prototype","create","aws","initialize","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugcallMethodHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","clientDir","serverConfig","websocketManager","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","methodManager","_this","_websocketManager","_monitorManagerFunction","ResolveIOServer","getClientDir","getServerConfig","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","__awaiter","console","log","Date","loadServerInit","_a","sent","setImmediate","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","getSESMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getMainServer","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMethod","method","methods","Object","assign","callMethodCron","methodData","_i","arguments","length","sendEmail","_b","Error","skipValidation","check","error","_schema","valObj","valKeys","keys","rootKeys","filter","a","includes","i","validate","err_1","JSON","stringify","message","concat","toISOString","monitor","startMonitorFunction","function","call","apply","__spreadArray","id_user","id_ws","__read","err_2","finishMonitorFunction","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","instance_index","functionMethodData","slice","getMongoManager","getSession","startsWith","monitor_2","oneTimeTransaction","res","err_4","err_3","changeStream","EmailHistories","watchCollection","on","change","operationType","fullDocument","status","add","toString","tryProcessEmail","updatedEmail","has","delete","err","close","loadPendingEmails","find","sort","pendingEmails","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","$set","processingAt","emailHistory","_e","attachments","e_2","_c","att","fetch","response","ok","arrayBuffer","buffer","Buffer","from","content","err_6","updateOne","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","sendMail","deleteOne","error_1","Promise","resolve","err_5","obj","getCircularReplacer","e","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","err_7","getAWS","readFile","fileName","existsSync","join","__dirname","readFileSync","readImage"],"mappings":"ihFAAAA,a,gGAAAC,QAAA,oBAAA,GACAC,GAAAD,QAAA,IAAA,EACAE,WAAAF,QAAA,YAAA,EACAG,aAAAH,QAAA,0BAAA,EACAI,KAAAJ,QAAA,MAAA,EACAK,2BAAAL,QAAA,yCAAA,EACAM,iBAAAN,QAAA,+BAAA,EACAO,YAAAP,QAAA,uBAAA,EACAQ,OAAAR,QAAA,kBAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,MAAAV,QAAA,gBAAA,EACAW,cAAAX,QAAA,wBAAA,EACAY,WAAAZ,QAAA,qBAAA,EACAa,YAAAb,QAAA,sBAAA,EACAc,eAAAd,QAAA,yBAAA,EACAe,QAAAf,QAAA,kBAAA,EACAgB,OAAAhB,QAAA,iBAAA,EACAiB,UAAAjB,QAAA,oBAAA,EACAkB,MAAAlB,QAAA,gBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EAGAqB,uBAAArB,QAAA,yBAAA,EACAsB,SAAAtB,QAAA,gBAAA,EAIAuB,IAAA,WAIC,SAAAA,MAHQC,KAAAC,IAAU,KACVD,KAAAE,WAAiB,IAEV,CAkDhB,OAhDQH,IAAAI,UAAAC,OAAP,WACC,IAAMC,EAAM,IAAIN,IAEhB,OADAM,EAAIC,WAAU,EACPD,CACR,EAEQN,IAAAI,UAAAG,WAAR,aAIOP,IAAAI,UAAAI,GAAP,WAcC,OAbIP,KAAKC,MAITD,KA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BAAgBC,aAAY,EAAK,aAAeiN,CAAS,EAAG,QAAQ,C,CAEtG,MAAO7E,GAEN,MADAA,EAAIzD,QAAU,uBAAAC,OAAuBwD,EAAIzD,OAAO,EAC1CyD,C,CAKT,MAAM,IAAI1E,MAAO,oCAAoC,CACtD,EACDjF,aAAA,EAAC,GArsBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { S3 } from '@aws-sdk/client-s3';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport * as path from 'path';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { Logs } from '../collections/log.collection';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadAWSMethods } from '../methods/aws';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { loadFlagMethods } from '../methods/flags';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { MethodAllModel, MethodModel } from '../models/method.model';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { getBinarySize, objectIdHexString } from '../util/common';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { WebSocketManager } from './websocket.manager';\n\nexport class AWS {\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor() {}\n\n\tpublic create() {\n\t\tconst aws = new AWS();\n\t\taws.initialize();\n\t\treturn aws;\n\t}\n\n\tprivate initialize() {\n\n\t}\n\n\tpublic s3(): S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1(): S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugcallMethodHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tpublic clientDir = '';\n\tpublic serverConfig = '';\n\n\tconstructor() {}\n\n\tstatic create(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tconst methodManager = new MethodManager();\n\t\tmethodManager.initialize(websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance);\n\t\treturn methodManager;\n\t}\n\n\tprivate initialize(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._websocketManager = websocketManager;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\t\t\n\t\tthis.clientDir = ResolveIOServer.getClientDir();\n\t\tthis.serverConfig = ResolveIOServer.getServerConfig();\n\n\t\t// Fixtures\n\t\tif (!process.env.IS_WORKERS_ENABLED || process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tawait loadServerInit();\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetImmediate(async () => {\n\t\t\t// Methods\n\t\t\tawait loadServerCronJobs();\n\n\t\t\tloadAccountMethods(this);\n\t\t\tloadAWSMethods(this);\n\t\t\tloadCollectionMethods(this);\n\t\t\tloadCounterMethods(this);\n\t\t\tloadLogMethods(this);\n\t\t\tloadPDFMethods(this);\n\t\t\tloadCronJobMethods(this);\n\t\t\tloadFlagMethods(this);\n\t\t\tloadFlagUpdatesMethods(this);\n\t\t\tloadReportBuilderMethods(this);\n\t\t\tloadSupportMethods(this);\n\t\t\tloadMonitorMethods(this);\n\t\t});\n\t\t\n\t\tthis._aws = new AWS();\n\t\t\n\t\tif (ResolveIOServer.getSESMail()) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: ResolveIOServer.getServerConfig()['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: ResolveIOServer.getServerConfig()['MAIL_USERNAME'],\n\t\t\t\t\tpass: ResolveIOServer.getServerConfig()['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (ResolveIOServer.getMainServer().getSubscriptionManager() && ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugcallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugcallMethodHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.setupEmailWatcher();\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic getMethod(method: string): MethodAllModel {\n\t\treturn this._methods[method];\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic async callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\tthrow new Error('No Method: ' + method);\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Function For Cron Method ' + method);\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Schema For Cron Method ' + method);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error(new Date(), 'Error in Cron Method Check (' + method + ')', err);\n\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Match Error On Cron Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method Check (${method}): ${err.message}`;\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\ttry {\n\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData);\n\t\t\treturn res;\n\t\t}\n\t\tcatch (err) {\n\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Cron Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\n\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method (${method}): ${err.message}`;\n\t\t\t\n\t\t\tthrow err;\n\t\t}\n\t\tfinally {\n\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic async callMethod(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugcallMethodHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\tthrow new Error(`No Method: ${method}`);\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\tthrow new Error(`No Check Function For Method: ${method}`);\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\tthrow new Error(`No Check Schema For Method: ${method}`);\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\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '', \n\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\tmethod: method,\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\tmessageId: 0,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\n\t\tconst session = ResolveIOServer.getMongoManager().getSession();\n\n\t\tif (!session && \n\t\t\t![\n\t\t\t\t'insertErrorLog', // CIRCULAR LOOP - DO NOT REMOVE\n\t\t\t\t'countWithQuery', // MONGO SESSIONS/TRANSACTIONS DONT WORTH WITH COUNTS\n\t\t\t\t'sendEmail' // ALWAYS SEND SO ALWAYS HAVE RECORD - DONT ROLL BACK - BYPASS SESSION\n\t\t\t].includes(method) &&\n\t\t\t!method.startsWith('monitor-') &&\n\t\t\t!method.startsWith('log')\n\t\t) {\n\t\t\tlet monitor = null;\n\t\t\t\n\t\t\treturn ResolveIOServer.getMongoManager().oneTimeTransaction(async () => {\n\t\t\t\tmonitor = this._monitorManagerFunction.startMonitorFunction('Method', method, this['user'] || '', '', functionMethodData);\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['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\terr.message = `${new Date().toISOString()} - Error in Method With Session (${method}) - New Session: ${err.message}`;\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, this['user'] || '', '', functionMethodData);\n\t\t\t\n\t\t\ttry {\n\t\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t}\n\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['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\terr.message = `${new Date().toISOString()} - Error in Method (${method}) - Existing Session: ${err.message}`;\n\t\t\t\t\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t}\n\n\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', async err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tawait changeStream.close();\n\t\t})\n\t\t.on('close', async () => {\n\t\t\tawait this.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tawait this.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || ResolveIOServer.getServerConfig().MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tthis._mailer.sendMail(mailOptions, async err => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\tawait EmailHistories.deleteOne({ _id: emailHistory._id });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t} \n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\t// eslint-disable-next-line no-restricted-syntax\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic async sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\t// Modify sendTo in development environments\n\t\tif (\n\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t) {\n\t\t\tsendTo = 'dev@resolveio.com';\n\t\t}\n\n\t\tif (sendTo) {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\tlocal_override\n\t\t\t) {\n\t\t\t\tif (!attachments) {\n\t\t\t\t\tattachments = [];\n\t\t\t\t}\n\n\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\tattachments = [attachments];\n\t\t\t\t}\n\n\t\t\t\t// Process attachments before saving\n\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t}\n\t\t\t\t\treturn newAtt;\n\t\t\t\t});\n\n\t\t\t\t// Queue the email in MongoDB\n\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\temail: sendTo,\n\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\ttext: text || '',\n\t\t\t\t\thtml: html || '',\n\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\terror: ''\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\tlet history = await EmailHistories.insertOne(emailHistory);\n\t\t\t\t\treturn history;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\terr.message = `Failed to queue email: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log(\n\t\t\t\t\t'Send email',\n\t\t\t\t\tsendTo,\n\t\t\t\t\tsubject,\n\t\t\t\t\ttext,\n\t\t\t\t\thtml,\n\t\t\t\t\tattachments,\n\t\t\t\t\tsend_from\n\t\t\t\t);\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'utf-8');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readFile: File Not Found');\n\t}\n\n\tpublic readImage(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'base64');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readImage: File Not Found');\n\t}\n}"]}