const generateId = require('../../utils/generateId.util'); const { domain, name: domainName } = require('../../config').server; const whatsappEvents = require('../emitter'); const { callWebhook } = require('../webhook'); const { addConnection, updateConnection, addCurrentConnection, resetConnection } = require('../../services/connections.service'); const { objectMapper, pick } = require('../../utils/commons.util'); const { sessionStore } = require('..'); const { getOutboundMessage, upsertOutboundMessage } = require('../../services/outbound_messages.service'); const logger = require('../../utils/logger.util'); const connectionEventNames = ['connection:connect', 'connection:open', 'connection:close']; const messageEventNames = ['message:received', 'message:updated']; const eventTypeMapped = { 'message:received': 'wai.message.received', 'message:updated': 'wai.message.updated', }; const timeField = { saved: 'createTime', pending: 'createTime', sent: 'sendTime', delivered: 'deliverTime', read: 'readTime', }; const statusMapped = { saved: 'accepted', pending: 'accepted', sent: 'sent', delivered: 'delivered', read: 'read', failed: 'failed' } const directionField = { 'message:received': 'inbound', 'message:updated': 'outbound' }; /** * @returns {Object} webhookBody */ const webhookBodyBuilder = (messageData, messageType) => { const message = { id: `evt_${generateId().replace(/-/g, '')}`, type: eventTypeMapped[messageType], apiVersion: 'v2', webhooksource: 'wai', createTime: new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString(), // GMT +8 domainName, conversationid: messageData?.externalId || '', waiMessage: { ...messageData, ...(messageData.updateTime ? { [timeField[messageData.status]]: messageData.updateTime } : {}), wamid: messageData.id, // direction: directionField[messageType], status: statusMapped?.[messageData.status] || '', // externalId: '-1', // todo: externalId: `-${messageData.externalId || 1}`, // debug: 测试: 是负值 }, }; return message; }; const setupConnectionHandler = () => { // connectionEventNames.forEach(eventName => { logger.info(`Setting up event ${'connection:connect'}`); whatsappEvents.on('connection:connect', async connectionData => { try { // find Or create await addCurrentConnection({ ...objectMapper(connectionData, { phone: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id', createTimestamp: 'createtime', version: 'version' }, false), service_type: 'baileys', status: 'connecting', }); } catch (error) { logger.error({ connectionData, error }, 'error add connection'); } }); logger.info(`Setting up event ${'connection:open'}`); whatsappEvents.on('connection:open', async connectionData => { logger.info(`event ${'connection:open'}`, connectionData); // todo: 更新实例 try { await updateConnection( { ...objectMapper(connectionData, { whatsAppNo: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id' }), service_type: 'baileys', closetime: null, }, { connect_domain: domain, connect_name: domainName }, ); } catch (error) { logger.error({ connectionData, error }, 'error add connection'); } }); logger.info(`Setting up event ${'connection:close'}`); whatsappEvents.on('connection:close', async connectionData => { logger.info(`event ${'connection:close'}`, connectionData); try { sessionStore.removeSession(connectionData.channelId); await updateConnection( { ...objectMapper(connectionData, { whatsAppNo: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id' }), service_type: 'baileys', }, { connect_domain: domain, connect_name: domainName, channel_id: connectionData.channelId }, ); // todo: 通知前端: 重新扫码 } catch (error) { logger.error({ connectionData, error }, 'error add connection'); } }); // }); }; /** * WhatsApp 消息事件 * pending -> saved -> sent(*) -> delivered -> read * saved -> pending -> sent(*) -> delivered -> read */ const setupMessageHandler = () => { messageEventNames.forEach(eventName => { logger.info(`Setting up event ${eventName}`); whatsappEvents.on(eventName, async messageData => { // if (messageData.status === 'pending') { // logger.info('message pending', messageData); // return false; // } try { const now = new Date(new Date().getTime() + 60 * 60 * 1000).toISOString(); const targetUpsert = messageData.externalId ? { actionId: messageData.externalId } : { id: messageData.id }; const savedMsg = await getOutboundMessage(targetUpsert); const bixFields = pick(savedMsg, ['actionId', 'externalId']); logger.info('message evt\n', eventName, messageData, savedMsg); const webhookBody = webhookBodyBuilder({ ...messageData, ...bixFields }, eventName); const { waiMessage } = webhookBody; const timeFields = pick(waiMessage, [...Object.values(timeField), 'createTime', 'updateTime']); const upsertFields = pick(waiMessage, ['direction', 'wamid', 'id', 'status']); upsertFields.evt_id = webhookBody.id; const pusher = { customerProfile_id: waiMessage.customerProfile?.id || '', customerProfile_name: waiMessage.customerProfile?.name || '' }; const record = objectMapper(waiMessage, { from: 'from', to: 'to', status: 'msg_status', type: 'msgtype' }, false); const contentFields = waiMessage.type === 'text' ? { text_body: waiMessage.text.body } : {}; await upsertOutboundMessage({ ...timeFields, ...upsertFields, ...pusher, ...contentFields, ...record, message_origin: savedMsg?.message_origin || JSON.stringify(messageData) }, targetUpsert); // console.log('upsert=========================', upsert); await callWebhook(webhookBody); } catch (error) { logger.error({ messageData, error }, 'error call webhook'); } }); }); }; function setupWhatsappHandler() { setupConnectionHandler(); setupMessageHandler(); } /** * 登出: 当前服务的所有连接 */ async function resetCurrentConnection() { await resetConnection(); } module.exports = { setupWhatsappHandler, resetCurrentConnection };