'use strict'; const generateId = require('../../utils/generateId.util'); const { sessionStore } = require('../../core'); const { objectMapper, pick } = require('../../utils/commons.util'); const { createOutboundMessage } = require('../../services/outbound_messages.service'); const waEmitter = require('../../core/emitter'); function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } exports.sendText = async ctx => { const { from, to, msgcontent, content: _content, actionId } = ctx.request.body; const content = _content || msgcontent.body || ''; if (!from || !content) { ctx.assert(from, 400, 'From and message are required'); return; } const wsToSend = sessionStore.getSession(from); // console.log('find wsToSend', wsToSend) if (!wsToSend) { ctx.assert(wsToSend, 400, 'Session not found'); // 404 return; } try { // wsToSend.sendTextMessage(to, content, actionId).then(({ messageId }) => { // const messageId = generateId(); const _data = ctx.request.body; const defaultR = { direction: 'outbound' }; const r1 = pick(_data, ['actionId', 'msgtype', 'externalId']); r1.id = actionId; // id not null // r1.wamid = messageId; r1.msg_status = 'ready'; r1.createTime = Date.now(); const record = objectMapper(_data, { from: 'from', to: 'to' }, false); const byType = _data.msgtype === 'text' ? { text_body: _data.msgcontent.body, text_preview_url: _data.msgcontent.preview_url } : {}; const toUpsert = { ...defaultR, ...r1, ...record, ...byType, message_origin: JSON.stringify(_data) }; await createOutboundMessage({ ...toUpsert }); // return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' }; // }); //wsToSend.sendTextMessage(to, content, actionId); waEmitter.emit('request.' + from + '.send.text', {to, content, externalId: actionId}); return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' }; } catch (error) { console.error('Error sending message:', error); ctx.assert(null, 500, 'Failed to send message'); } };