You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
147 lines
6.1 KiB
JavaScript
147 lines
6.1 KiB
JavaScript
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 = { pending: 'createTime', sent: 'sendTime', delivered: 'deliverTime', read: 'readTime' };
|
|
const statusMapped = { pending: 'accepted', sent: 'sent', delivered: 'delivered', read: 'read' }
|
|
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' }, 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);
|
|
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 => {
|
|
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 },
|
|
);
|
|
// todo: 通知前端: 重新扫码
|
|
} catch (error) {
|
|
logger.error({ connectionData, error }, 'error add connection');
|
|
}
|
|
});
|
|
// });
|
|
};
|
|
|
|
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 m = await getOutboundMessage({ id: messageData.id });
|
|
const bixFields = pick(m, ['actionId', 'externalId', 'message_origin']);
|
|
logger.info('message evt NOT pending \n', m, bixFields);
|
|
|
|
const webhookBody = webhookBodyBuilder({ ...messageData, ...bixFields, savedMsg: m }, eventName);
|
|
const { waiMessage } = webhookBody;
|
|
|
|
const timeFields = pick(waiMessage, [...Object.values(timeField), 'createTime', 'updateTime']);
|
|
// timeFields.msgtime = m?.msgtime || now;
|
|
// timeFields.createTime = messageData?.createTime || m?.createTime || now;
|
|
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: 'froms', to: 'tos', status: 'msg_status', type: 'msgtype' }, false);
|
|
const contentFields = waiMessage.type === 'text' ? { text_body: waiMessage.text.body } : {};
|
|
await upsertOutboundMessage(m.sn || null, { ...timeFields, ...upsertFields, ...pusher, ...contentFields, ...record, message_origin: bixFields?.message_origin || JSON.stringify(messageData) });
|
|
// 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 };
|