UNPKG

yekonga-server

Version:
229 lines (187 loc) 8.09 kB
// @ts-nocheck /*global Yekonga, serverLibrary */ const fs = serverLibrary.fs; const path = serverLibrary.path; async function processNotifications() { let list = await Yekonga.Model.Notification.find({ status: "waiting" }, { limit: 100 }, true); if (Array.isArray(list)) { for (var row of list) { processSingleNotification(row) } } else { // console.debug(list); } } async function processSingleNotification(row) { try { var notificationData = Yekonga.Helper.copyJson({...row, from: row.senderName, phone: row.recipient, text:row.content}); var beforeInjectFunction = Yekonga.Cloud.getBeforeAndAfterNotificationCallback('beforeNotification'); if (beforeInjectFunction) { var _input = await beforeInjectFunction(notificationData); if (_input === false) throw new Yekonga.Error.Forbidden(`Action rejected by before notification`); if (_input) notificationData = _input; } const names = []; if(Yekonga.Helper.isNotEmpty(notificationData.name)) { names.push(notificationData.name); } if(!names.length) names.push('You'); const fullName = names.join(' '); var status = "failed"; var response = null; var responseReference = null; if (notificationData.type == "sms") { notificationData.content = Yekonga.Helper.clearSpecialCharacters(notificationData.content); // console.debug("notificationData.sms", notificationData.senderName); var res = await Yekonga.Helper.sendSMS(notificationData); // console.debug(res); if(res.status == 'SUCCESS') { status = "submitted"; } if(res.response) { responseReference = res.messageId; response = res.response; } } else if (notificationData.type == "whatsapp") { var res = await Yekonga.Helper.sendWhatsapp(notificationData); // console.debug(res); if(res.status == 'SUCCESS' || res.status === true) { status = "submitted"; } if(res.response) { responseReference = res.messageId; response = res.response; } } else if (notificationData.type == 'mail') { notificationData.from = notificationData.replyTo; var from = (Yekonga.Config.mail && Yekonga.Config.mail.smtp) ? Yekonga.Config.mail.smtp.from : null; var htmlContent = Yekonga.Helper.textTemplate(notificationData.content, notificationData, /@(?<name>notificationId)/g); var attachments = []; notificationData.attachments = (Array.isArray(notificationData.attachment)) ? notificationData.attachment : (notificationData.attachment? [notificationData.attachment]: []); for (const attach of notificationData.attachments) { if(fs.existsSync(attach)) { // console.debug('existsSync'); var filename = path.basename(attach); var content = fs.readFileSync(attach, { encoding: 'base64' }) attachments.push({ filename: filename, content: content, encoding: 'base64' }); } } var emailOptions = { from: Yekonga.Helper.isNotEmpty(notificationData.from)? notificationData.from: `"${Yekonga.Config.appName}" <${from}>`, // sender address to: `${notificationData.recipient}`, // list of receivers replyTo: notificationData.replyTo, subject: notificationData.title, // Subject line text: notificationData.content, // plain text body html: htmlContent, // html body attachments: attachments, }; var res = await Yekonga.Helper.sendMail(emailOptions, notificationData); if(res && res.response) { status = "submitted"; response = res.response; responseReference = res.messageId; } } if(status == 'failed') { console.debug(`========= ${notificationData.type}`,status); if(response) { console.debug(`========= ${notificationData.type}`,response); console.debug(`========= ${notificationData.type}`,response.requestError); } console.debug(`========= ${notificationData.type}`,notificationData.recipient); if(notificationData.type != 'mail') { console.debug(`========= ${notificationData.type}`,notificationData.content); } } await Yekonga.Model.Notification.update( { status: status, response: response, responseReference: responseReference }, { notificationId: notificationData.notificationId }, null, true ); var afterInjectFunction = Yekonga.Cloud.getBeforeAndAfterNotificationCallback('afterNotification'); if (afterInjectFunction) { await afterInjectFunction({data: notificationData, response}); } } catch (error) { console.error('processSingleNotification', error) } } const time = 1000; Yekonga.cronjobProcess = function() { var timeDelay = 3; try { timeDelay = `${process.pid}`; if(timeDelay.length > 2) { timeDelay = timeDelay.substring((timeDelay.length - 2)); } if(timeDelay.length >= 2) { var multipleOf = parseInt(timeDelay.substring(timeDelay.length - 1)) * 5; timeDelay = parseInt(timeDelay) + multipleOf; } timeDelay = parseInt(`${timeDelay}`); if(timeDelay < 100) { timeDelay = timeDelay * 1000; } else if(timeDelay < 1000) { timeDelay = timeDelay * 100; } } catch (error) { console.debug(error); } // console.debug('timeDelay in millisecond', timeDelay); setTimeout(() => { setInterval(() => { Yekonga.runCronjob(); }, time); }, timeDelay); } Yekonga._registeredCronjobs = {}; Yekonga._runCronjobProcess = async function(name) { if(Yekonga._registeredCronjobs[name].time >= Yekonga._registeredCronjobs[name].delay) { Yekonga._registeredCronjobs[name].time = 0; var status = await Yekonga.Storage.acquireLock(name); if(status) { if(typeof Yekonga._registeredCronjobs[name].callback == 'function'){ await Yekonga._registeredCronjobs[name].callback(); } await Yekonga.Storage.releaseLock(name); } } Yekonga._registeredCronjobs[name].time += 1000; } Yekonga.runCronjob = function() { for (const name in Yekonga._registeredCronjobs) { if (Object.prototype.hasOwnProperty.call(Yekonga._registeredCronjobs), name) { Yekonga._runCronjobProcess(name); } } } Yekonga.registerCronjob = function(name, delay, callback) { var cronjobName = `cronjobs:${name}`; Yekonga._registeredCronjobs[cronjobName] = { name: cronjobName, delay: delay, time: 0, callback: callback, process: false, }; } Yekonga.registerCronjob('processSystemNotifications', 10000, async function() { var status = await Yekonga.Storage.get('cronjobProcessStatus', false); if (!status) { await Yekonga.Storage.set('cronjobProcessStatus', true); if(Yekonga.Cloud.exists('processSystemNotifications')) { await Yekonga.Cloud.run('processSystemNotifications') } else { await processNotifications(); } await Yekonga.Storage.set('cronjobProcessStatus', false); } });