@resolveio/server-lib 20.7.6 → 20.7.8
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.
- package/client-server-app.js +1 -1
- package/client-server-app.js.map +1 -1
- package/collections/app-status.collection.js +1 -1
- package/collections/app-status.collection.js.map +1 -1
- package/collections/counter.collection.js +1 -1
- package/collections/counter.collection.js.map +1 -1
- package/collections/cron-job-history.collection.js +1 -1
- package/collections/cron-job-history.collection.js.map +1 -1
- package/collections/cron-job.collection.js +1 -1
- package/collections/cron-job.collection.js.map +1 -1
- package/collections/email-history.collection.js +1 -1
- package/collections/email-history.collection.js.map +1 -1
- package/collections/email-verified.collection.js +1 -1
- package/collections/email-verified.collection.js.map +1 -1
- package/collections/file.collection.js +1 -1
- package/collections/file.collection.js.map +1 -1
- package/collections/flag-update.collection.js +1 -1
- package/collections/flag-update.collection.js.map +1 -1
- package/collections/flag.collection.js +1 -1
- package/collections/flag.collection.js.map +1 -1
- package/collections/log-method-latency.collection.js +1 -1
- package/collections/log-method-latency.collection.js.map +1 -1
- package/collections/log-subscription.collection.js +1 -1
- package/collections/log-subscription.collection.js.map +1 -1
- package/collections/log.collection.js +1 -1
- package/collections/log.collection.js.map +1 -1
- package/collections/logged-in-users.collection.js +1 -1
- package/collections/logged-in-users.collection.js.map +1 -1
- package/collections/method-response.collection.js +1 -1
- package/collections/method-response.collection.js.map +1 -1
- package/collections/monitor-cpu.collection.js +1 -1
- package/collections/monitor-cpu.collection.js.map +1 -1
- package/collections/monitor-function.collection.js +1 -1
- package/collections/monitor-function.collection.js.map +1 -1
- package/collections/monitor-memory.collection.js +1 -1
- package/collections/monitor-memory.collection.js.map +1 -1
- package/collections/monitor-mongo.collection.js +1 -1
- package/collections/monitor-mongo.collection.js.map +1 -1
- package/collections/notification.collection.js +1 -1
- package/collections/notification.collection.js.map +1 -1
- package/collections/report-builder-dashboard-builder.collection.js +1 -1
- package/collections/report-builder-dashboard-builder.collection.js.map +1 -1
- package/collections/report-builder-library.collection.js +1 -1
- package/collections/report-builder-library.collection.js.map +1 -1
- package/collections/report-builder-report.collection.js +1 -1
- package/collections/report-builder-report.collection.js.map +1 -1
- package/collections/user-group.collection.js +1 -1
- package/collections/user-group.collection.js.map +1 -1
- package/collections/user-guide.collection.js +1 -1
- package/collections/user-guide.collection.js.map +1 -1
- package/collections/user.collection.js +1 -1
- package/collections/user.collection.js.map +1 -1
- package/fixtures/cron-jobs.js +1 -1
- package/fixtures/cron-jobs.js.map +1 -1
- package/fixtures/init.js +1 -1
- package/fixtures/init.js.map +1 -1
- package/http/auth.d.ts +2 -1
- package/http/auth.js +1 -1
- package/http/auth.js.map +1 -1
- package/http/home.js +1 -1
- package/http/home.js.map +1 -1
- package/managers/cron.manager.d.ts +3 -1
- package/managers/cron.manager.js +1 -1
- package/managers/cron.manager.js.map +1 -1
- package/managers/local-log.manager.d.ts +3 -1
- package/managers/local-log.manager.js +1 -1
- package/managers/local-log.manager.js.map +1 -1
- package/managers/method.manager.d.ts +12 -7
- package/managers/method.manager.js +1 -1
- package/managers/method.manager.js.map +1 -1
- package/managers/mongo.manager.d.ts +17 -12
- package/managers/mongo.manager.js +1 -1
- package/managers/mongo.manager.js.map +1 -1
- package/managers/monitor.manager.d.ts +15 -7
- package/managers/monitor.manager.js +1 -1
- package/managers/monitor.manager.js.map +1 -1
- package/managers/subscription.manager.d.ts +5 -3
- package/managers/subscription.manager.js +1 -1
- package/managers/subscription.manager.js.map +1 -1
- package/managers/websocket.manager.d.ts +3 -1
- package/managers/websocket.manager.js +1 -1
- package/managers/websocket.manager.js.map +1 -1
- package/methods/accounts.js +1 -1
- package/methods/accounts.js.map +1 -1
- package/methods/aws.js +1 -1
- package/methods/aws.js.map +1 -1
- package/methods/collections.js +1 -1
- package/methods/collections.js.map +1 -1
- package/methods/counters.js +1 -1
- package/methods/counters.js.map +1 -1
- package/methods/cron-jobs.js +1 -1
- package/methods/cron-jobs.js.map +1 -1
- package/methods/logs.js +1 -1
- package/methods/logs.js.map +1 -1
- package/methods/monitor.js +1 -1
- package/methods/monitor.js.map +1 -1
- package/methods/pdf.js +1 -1
- package/methods/pdf.js.map +1 -1
- package/methods/report-builder.js +1 -1
- package/methods/report-builder.js.map +1 -1
- package/methods/support.js +1 -1
- package/methods/support.js.map +1 -1
- package/models/method.model.d.ts +6 -1
- package/package.json +5 -4
- package/publications/logs.js +1 -1
- package/publications/logs.js.map +1 -1
- package/resolveio-server-app.d.ts +14 -10
- package/resolveio-server-app.js +1 -1
- package/resolveio-server-app.js.map +1 -1
- package/server-app.d.ts +5 -4
- package/server-app.js +1 -1
- package/server-app.js.map +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,i){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var i,s,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;l=c&&t[c=0]?0:l;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return l.label++,{value:t[1],done:!1};case 5:l.label++,s=t[1],t=[0];continue;case 7:t=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){l=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))l.label=t[1];else if(6===t[0]&&l.label<a[1])l.label=a[1],a=t;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(t)}}t=n.call(o,l)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)s.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),client_s3_1=require("@aws-sdk/client-s3"),flag_updates_1=require("../methods/flag-updates"),resolveio_server_app_1=require("../resolveio-server-app"),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,r){var o=this;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="",this._websocketManager=resolveio_server_app_1.ResolveIOServer.getMainServer().getWebSocketManager(),this._monitorManagerFunction=e,this._isWorkersEnabled=t,this._isWorkerInstance=r,this.clientDir=resolveio_server_app_1.ResolveIOServer.getClientDir(),this.serverConfig=resolveio_server_app_1.ResolveIOServer.getServerConfig(),"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS,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",o._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",o._debugcallMethodHits),console.log(new Date,"Method Manager","Call Method Hits",o._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",o._debugCallMethodCronJobHits)),o._debugcallMethodHits=0,o._debugCallMethodHits=0,o._debugCallMethodCronJobHits=0,o._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}return MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,r=this,o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var l=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o);return(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(o),!1)).then(function(e){return r._monitorManagerFunction.finishMonitorFunction(l),e},function(e){throw r._monitorManagerFunction.finishMonitorFunction(l),r.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(t){for(var e,r=this,o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];if(this._debugcallMethodHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?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([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""}));var i,s,a="function"==typeof o[o.length-1]?o.slice(0,-1):o,l=null;return l=resolveio_server_app_1.ResolveIOServer.getMongoManager().getSession()?(i=this._monitorManagerFunction.startMonitorFunction("Method",t,this.user||"","",a),(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(a),!1)).then(function(e){return r._monitorManagerFunction.finishMonitorFunction(i),e},function(e){throw r._monitorManagerFunction.finishMonitorFunction(i),r.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethod)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})):(s=this._monitorManagerFunction.startMonitorFunction("Method",t,this.user||"","",a),resolveio_server_app_1.ResolveIOServer.getMongoManager().oneTimeTransaction(function(){var e;return(e=r._methods[t].function).call.apply(e,__spreadArray([Object.assign({},r,MethodManager.prototype)],__read(a),!1))}).then(function(e){return r._monitorManagerFunction.finishMonitorFunction(s),e}).catch(function(e){throw r._monitorManagerFunction.finishMonitorFunction(s),r.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethod)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),o[o.length-1]&&"function"==typeof o[o.length-1]&&l.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,r,o,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:"",client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""}))},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(t=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){o.setupEmailWatcher()}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,i,s;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){i={error:e}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,_,r,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,7]),t=function(){var o,t,r,n,i,s,a,l,c,u;return __generator(this,function(e){switch(e.label){case 0:return i=_.emailQueue.values().next().value,_.emailQueue.delete(i),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:i,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((i=e.sent()).ok)return[4,i.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:s=e.sent(),s=Buffer.from(s),s.length<=20971520&&(n.content=s,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return s=e.sent(),c={error:s},[3,11];case 10:try{r&&!r.done&&(u=t.return)&&u.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:_.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(l={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<l.attachments.length&&(l.attachments=l.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),[4,new Promise(function(r){h._mailer.sendMail(l,function(t,e){return __awaiter(h,void 0,void 0,function(){return __generator(this,function(e){try{t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===o.email?email_history_collection_1.EmailHistories.deleteOne({_id:o._id}):email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})}catch(e){console.error("Error in sendMail callback:",e),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof e?e:this.safeStringify(e),completedAt:new Date}})}finally{r()}return[2]})})})})];case 15:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 16:return e.sent(),[2]}})},_=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,7];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(n,i,s,a,l,c,u,_){var e=this;return void 0===_&&(_=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(n=!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||n.match(/\@resolveio\.com/)?n:"dev@resolveio.com")?"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||_?(l=l||[],l=(l=Array.isArray(l)?l:[l]).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:n,subject:i||"",text:s||"",html:a||"",attachments:l||[],send_from:c||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),o(e)})):(console.log("Send email",n,i,s,a,l,c),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8",function(e,t){e?o(e):r(t)})})},MethodManager.prototype.readImage=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64",function(e,t){e?o(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
|
|
1
|
+
"use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,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(),"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.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())?[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:return[3,9];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:return[3,14];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,e){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){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){if(e)throw e;return t}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8",function(e,t){if(e)throw e;return t})},MethodManager.prototype.readImage=function(e){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){if(e)throw e;return t}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64",function(e,t){if(e)throw e;return t})},MethodManager}());exports.MethodManager=MethodManager;
|
|
2
2
|
//# sourceMappingURL=method.manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","common_1","log_collection_1","report_builder_1","support_1","monitor_1","email_history_collection_1","client_s3_1","flag_updates_1","resolveio_server_app_1","AWS","this","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugcallMethodHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","clientDir","serverConfig","_websocketManager","ResolveIOServer","getMainServer","getWebSocketManager","_monitorManagerFunction","getClientDir","getServerConfig","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","console","log","Date","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","getSESMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","setupEmailWatcher","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","monitor","startMonitorFunction","_a","function","call","apply","__spreadArray","id_user","id_ws","__read","then","res","finishMonitorFunction","methodErrs","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","instance_index","monitor_3","monitor_2","functionMethodData","slice","promise","getMongoManager","getSession","oneTimeTransaction","catch","err","sendWS","ws","messageDate","send","changeStream","EmailHistories","watchCollection","on","change","__awaiter","operationType","fullDocument","status","add","toString","tryProcessEmail","updatedEmail","has","delete","close","loadPendingEmails","sent","find","sort","pendingEmails","_b","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","startsWith","fetch","response","ok","arrayBuffer","Error","concat","buffer","Buffer","from","content","err_2","updateOne","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","Promise","resolve","sendMail","info","deleteOne","err_1","obj","getCircularReplacer","e","message","seen","WeakSet","key","sendTo","local_override","reject","Array","isArray","isBuffer","__v","date","history","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"ihFACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,SAAAd,QAAA,gBAAA,EACAe,iBAAAf,QAAA,+BAAA,EACAgB,iBAAAhB,QAAA,2BAAA,EACAiB,UAAAjB,QAAA,oBAAA,EACAkB,UAAAlB,QAAA,oBAAA,EACAmB,2BAAAnB,QAAA,yCAAA,EAEAoB,YAAApB,QAAA,oBAAA,EAGAqB,eAAArB,QAAA,yBAAA,EAEAsB,uBAAAtB,QAAA,yBAAA,EAEAuB,IAAA,WAIC,SAAAA,MAHQC,KAAAC,IAAU,KACVD,KAAAE,WAAiB,IAIzB,CAwCD,OAtCQH,IAAAI,UAAAC,GAAP,WAcC,OAbIJ,KAAKC,MAITD,KAAKC,IAAM,IAAIL,YAAAS,GAAG,CACjBC,YAAa,CACZC,YAAaC,QAAQC,IAAIC,eACzBC,gBAAiBH,QAAQC,IAAIG,qB,EAE9BC,OAAQL,QAAQC,IAAIK,WACpBC,WAAY,Y,CACZ,GAEMf,KAAKC,GACb,EAEOF,IAAAI,UAAAa,UAAP,WACC,MAA+B,c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AAK,aAAemN,CAAS,EAAG,QAAS,SAACvG,EAAK/B,GAC5F+B,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQ/G,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEOpG,cAAAd,UAAA4P,UAAP,SAAiBJ,GAChB,OAAO,IAAIxB,QAAQ,SAACC,EAASc,GACxBpQ,GAAG8Q,WAAW/Q,KAAKgR,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjE7Q,GAAG4Q,SAAS7Q,KAAKgR,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACvG,EAAK/B,GACzE+B,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQ/G,CAAG,CAEb,CAAC,EAGGvI,GAAG8Q,WAAW/Q,KAAKgR,KAAK/P,uBAAAsC,gBAAgBI,aAAY,EAAK,aAAemN,CAAS,CAAC,GACrF7Q,GAAG4Q,SAAS7Q,KAAKgR,KAAK/P,uBAAAsC,gBAAgBI,aAAY,EAAK,aAAemN,CAAS,EAAG,SAAU,SAACvG,EAAK/B,GAC7F+B,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQ/G,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDpG,aAAA,EAAC,GApuBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { getBinarySize, objectIdHexString } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { ResolveIOServer } from '../resolveio-server-app';\n\nexport class AWS {\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor() {\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(monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._websocketManager = ResolveIOServer.getMainServer().getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\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 === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tloadServerInit();\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadFlagUpdatesMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS();\n\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\tthis.setupEmailWatcher();\n\t\t}\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\tthrow methodErrs;\n\t\t});\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic 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\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution' && method !== 'incCounter' && method !== 'supportCreateBillingUser' && method !== 'countCollectionWithQuery') {\n\t\t\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\tLogs.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\t\tlet promise = null;\n\n\t\tconst session = ResolveIOServer.getMongoManager().getSession();\n\n\t\tif (!session) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, this['user'] || '', '', functionMethodData);\n\n\t\t\tpromise = ResolveIOServer.getMongoManager().oneTimeTransaction(() => {\n\t\t\t\tlet res = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\t\t\t\treturn res;\n\t\t\t})\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t})\n\t\t\t.catch(err => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.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\tthrow err;\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\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t},\n\t\t\t\tmethodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\tthrow methodErrs;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\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: 'client-response',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload:\n\t\t\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t\t\t: 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: data.messageId,\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\tLogs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload:\n\t\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t\t: 'Too Big',\n\t\t\t\t\tmethod: method,\n\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\tmessageId: data.messageId,\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\t// MethodResponses.create({\n\t\t// \t_id: objectIdHexString(),\n\t\t// \t__v: 0,\n\t\t// \tid_user: ws['id_user'] || '',\n\t\t// \tmessage_id: data.messageId,\n\t\t// \tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t// \tmethod: method,\n\t\t// \tdate: messageDate\n\t\t// });\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tchangeStream.close();\n\t\t})\n\t\t.on('close', () => {\n\t\t\tthis.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tthis.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// 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\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tthis._mailer.sendMail(mailOptions, async (err, info) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\t\tEmailHistories.deleteOne({ _id: emailHistory._id });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\t\tEmailHistories.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 error === 'string' ? error : this.safeStringify(error),\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} finally {\n\t\t\t\t\t\t\tresolve(); // Continue processing the queue\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\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// Modify sendTo in development environments\n\t\t\tif (\n\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t\t) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\t\n\t\t\tif (sendTo) {\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\t\tlocal_override\n\t\t\t\t) {\n\t\t\t\t\tif (!attachments) {\n\t\t\t\t\t\tattachments = [];\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\t\tattachments = [attachments];\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// Process attachments before saving\n\t\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\n\t\t\t\t\t// Queue the email in MongoDB\n\t\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\t\ttext: text || '',\n\t\t\t\t\t\thtml: html || '',\n\t\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t\terror: ''\n\t\t\t\t\t};\n\t\n\t\t\t\t\tEmailHistories.insertOne(emailHistory).then(\n\t\t\t\t\t\t(history) => resolve(history),\n\t\t\t\t\t\t(err) => {\n\t\t\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'Send email',\n\t\t\t\t\t\tsendTo,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\thtml,\n\t\t\t\t\t\tattachments,\n\t\t\t\t\t\tsend_from\n\t\t\t\t\t);\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["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","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","sendEmail","_b","Error","skipValidation","check","error","_schema","valObj","valKeys","keys","rootKeys","filter","a","includes","i","validate","err_1","JSON","stringify","message","concat","toISOString","monitor","startMonitorFunction","function","call","apply","__spreadArray","id_user","id_ws","__read","err_2","finishMonitorFunction","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","instance_index","functionMethodData","slice","getMongoManager","getSession","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","startsWith","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","info","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","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,KAAKC,IAAM,IAAI1B,YAAAiC,GAAG,CACjBC,YAAa,C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Q,KAAKkR,KAAKC,UAAY,cAAgBH,CAAS,EAAG,QAAS,SAAC/E,EAAKjB,GAC5E,GAAIiB,EACH,MAAMA,EAGN,OAAOjB,CAET,CAAC,EAGGnL,GAAGoR,WAAWjR,KAAKkR,KAAKjQ,uBAAA6C,gBAAgBC,aAAY,EAAK,aAAeiN,CAAS,CAAC,GACrFnR,GAAGkR,SAAS/Q,KAAKkR,KAAKjQ,uBAAA6C,gBAAgBC,aAAY,EAAK,aAAeiN,CAAS,EAAG,QAAS,SAAC/E,EAAKjB,GAChG,GAAIiB,EACH,MAAMA,EAGN,OAAOjB,CAET,CAAC,CAGJ,EAEOxI,cAAAjB,UAAA6P,UAAP,SAAiBJ,GACZnR,GAAGoR,WAAWjR,KAAKkR,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEnR,GAAGkR,SAAS/Q,KAAKkR,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAC/E,EAAKjB,GAC7E,GAAIiB,EACH,MAAMA,EAGN,OAAOjB,CAET,CAAC,EAGGnL,GAAGoR,WAAWjR,KAAKkR,KAAKjQ,uBAAA6C,gBAAgBC,aAAY,EAAK,aAAeiN,CAAS,CAAC,GACrFnR,GAAGkR,SAAS/Q,KAAKkR,KAAKjQ,uBAAA6C,gBAAgBC,aAAY,EAAK,aAAeiN,CAAS,EAAG,SAAU,SAAC/E,EAAKjB,GACjG,GAAIiB,EACH,MAAMA,EAGN,OAAOjB,CAET,CAAC,CAGJ,EACDxI,aAAA,EAAC,GAzrBYC,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 { 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 === '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\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\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\t// throw 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\t// throw 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, info) => {\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\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\tif (err) {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn res;\n\t\t\t\t}\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\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic readImage(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\tif (err) {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn res;\n\t\t\t\t}\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\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import { AggregateOptions, AggregationCursor, BulkWriteOptions, ChangeStream, ChangeStreamOptions, CommandOperationOptions, CountDocumentsOptions, CreateCollectionOptions, CreateIndexesOptions, CursorStreamOptions, DeleteOptions, FindCursor, FindOneAndDeleteOptions, FindOneAndReplaceOptions, FindOneAndUpdateOptions, FindOptions, IndexDescription, IndexInformationOptions, InsertOneOptions, ListIndexesCursor, ListIndexesOptions, RenameOptions, ReplaceOptions, UpdateOptions
|
|
2
|
+
import { AggregateOptions, AggregationCursor, BulkWriteOptions, BulkWriteResult, ChangeStream, ChangeStreamOptions, Collection, CollectionInfo, CommandOperationOptions, CountDocumentsOptions, CreateCollectionOptions, CreateIndexesOptions, CursorStreamOptions, DeleteOptions, FindCursor, FindOneAndDeleteOptions, FindOneAndReplaceOptions, FindOneAndUpdateOptions, FindOptions, IndexDescription, IndexInformationOptions, InsertOneOptions, ListIndexesCursor, ListIndexesOptions, RenameOptions, ReplaceOptions, UpdateOptions } from 'mongodb';
|
|
3
|
+
import { CollectionDocument, Document } from '../models/collection-document.model';
|
|
3
4
|
import { LookupTables } from '../models/report-builder.model';
|
|
4
5
|
import { UserModel } from '../models/user.model';
|
|
5
|
-
import { CollectionDocument, Document } from '../models/collection-document.model';
|
|
6
6
|
export declare interface MongoManagerFilterParamaterOperators<P> {
|
|
7
7
|
$eq?: P;
|
|
8
8
|
$gt?: P;
|
|
@@ -67,13 +67,14 @@ export declare class MongoManager {
|
|
|
67
67
|
private _isWorkersEnabled;
|
|
68
68
|
private _isWorkerInstance;
|
|
69
69
|
constructor();
|
|
70
|
-
|
|
70
|
+
static create(): Promise<MongoManager>;
|
|
71
|
+
private initialize;
|
|
72
|
+
oneTimeTransaction<T>(fn: () => Promise<T>): Promise<T>;
|
|
71
73
|
getSession(): any;
|
|
72
74
|
private setCacheLimit;
|
|
73
|
-
initServerCollections(): Promise<void>;
|
|
74
75
|
getServerCollections(): (CollectionInfo | Pick<CollectionInfo, "type" | "name">)[];
|
|
75
|
-
registerCollection(collection: MongoManagerCollection<CollectionDocument>): void
|
|
76
|
-
createCollection(collection: MongoManagerCollection<CollectionDocument>): void
|
|
76
|
+
registerCollection(collection: MongoManagerCollection<CollectionDocument>): Promise<void>;
|
|
77
|
+
createCollection(collection: MongoManagerCollection<CollectionDocument>): Promise<void>;
|
|
77
78
|
collections(): MongoManagerCollection<CollectionDocument>[];
|
|
78
79
|
collection(collectionName: string): MongoManagerCollection<CollectionDocument> | MongoManagerUserCollection<CollectionDocument>;
|
|
79
80
|
private delay;
|
|
@@ -94,7 +95,9 @@ export declare class MongoManager {
|
|
|
94
95
|
export declare class MongoManagerModel<T extends CollectionDocument> {
|
|
95
96
|
collection_main: MongoManagerCollection<T> | MongoManagerUserCollection<T>;
|
|
96
97
|
collection_version: MongoManagerCollection<T> | MongoManagerUserCollection<T>;
|
|
97
|
-
constructor(
|
|
98
|
+
constructor();
|
|
99
|
+
static create<T>(options: MongoManagerCollectionOptions): MongoManagerModel<T>;
|
|
100
|
+
private initialize;
|
|
98
101
|
}
|
|
99
102
|
export interface MongoManagerCollectionOptions {
|
|
100
103
|
collectionName: string;
|
|
@@ -122,7 +125,9 @@ export declare class MongoManagerCollection<T extends CollectionDocument> {
|
|
|
122
125
|
collectionOptions: CreateCollectionOptions;
|
|
123
126
|
skipCache: boolean;
|
|
124
127
|
bypassSession: boolean;
|
|
125
|
-
constructor(
|
|
128
|
+
constructor();
|
|
129
|
+
static create(options: MongoManagerCollectionOptions): MongoManagerCollection<CollectionDocument>;
|
|
130
|
+
private initialize;
|
|
126
131
|
private static indexQueue;
|
|
127
132
|
extractIndexNameFromError(errorMessage: any): any;
|
|
128
133
|
aggregate(pipeline: object[], options?: AggregateOptions, skipCache?: boolean, bypassSession?: boolean): Promise<any[]>;
|
|
@@ -166,9 +171,9 @@ export declare class MongoManagerUserCollection<T extends CollectionDocument> ex
|
|
|
166
171
|
error: string;
|
|
167
172
|
}>;
|
|
168
173
|
serializeUser(): (user: any, cb: any) => void;
|
|
169
|
-
deserializeUser(): (username: any, cb: any) =>
|
|
170
|
-
setPassword(user: UserModel, password: string): Promise<
|
|
171
|
-
changePassword(user: any, oldPassword: any, newPassword: any): Promise<
|
|
172
|
-
register(user: any, password: any): Promise<
|
|
174
|
+
deserializeUser(): (username: any, cb: any) => Promise<UserModel>;
|
|
175
|
+
setPassword(user: UserModel, password: string): Promise<number>;
|
|
176
|
+
changePassword(user: any, oldPassword: any, newPassword: any): Promise<number>;
|
|
177
|
+
register(user: any, password: any): Promise<any>;
|
|
173
178
|
resetAttempts(user: UserModel): Promise<number>;
|
|
174
179
|
}
|