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.
126 lines
4.5 KiB
JavaScript
126 lines
4.5 KiB
JavaScript
7 months ago
|
const generateId = require('../../utils/generateId.util');
|
||
7 months ago
|
const { domain, name: domainName } = require('../../config').server;
|
||
7 months ago
|
const whatsappEvents = require('../emitter');
|
||
|
const { callWebhook } = require('../webhook');
|
||
7 months ago
|
const { addConnection, updateConnection, addCurrentConnection, resetConnection } = require('../../services/connections.service');
|
||
7 months ago
|
const { objectMapper } = require('../../utils/commons.util');
|
||
7 months ago
|
const { sessionService } = require('..');
|
||
7 months ago
|
const { getOutboundMessage, upsertOutboundMessage } = require('../../services/outbound_messages.service');
|
||
7 months ago
|
|
||
|
const logger = console;
|
||
|
|
||
7 months ago
|
const connectionEventNames = ['connection:connect', 'connection:open', 'connection:close'];
|
||
7 months ago
|
const messageEventNames = ['message:received', 'message:updated'];
|
||
|
|
||
7 months ago
|
const eventTypeMapped = {
|
||
7 months ago
|
'message:received': 'wai.message.received',
|
||
|
'message:updated': 'wai.message.updated',
|
||
|
};
|
||
7 months ago
|
const timeField = { sent: 'sendTime', delivered: 'deliverTime', read: 'readTime' };
|
||
|
const directionField = { 'message:received': 'inbound', 'message:updated': 'outbound' };
|
||
7 months ago
|
|
||
|
/**
|
||
|
* @returns {Object} webhookBody
|
||
|
*/
|
||
7 months ago
|
const webhookBodyBuilder = (messageData, messageType) => {
|
||
|
const message = {
|
||
|
id: `evt_${generateId().replace(/-/g, '')}`,
|
||
7 months ago
|
type: eventTypeMapped[messageType],
|
||
7 months ago
|
apiVersion: 'v2',
|
||
|
webhooksource: 'wai',
|
||
|
createTime: new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString(), // GMT +8
|
||
7 months ago
|
domainName,
|
||
7 months ago
|
waiMessage: {
|
||
|
...messageData,
|
||
|
...(messageData.updateTime ? { [timeField[messageData.status]]: messageData.updateTime } : {}),
|
||
7 months ago
|
wamid: messageData.id,
|
||
7 months ago
|
direction: directionField[messageType],
|
||
7 months ago
|
// externalId: '-1', // todo:
|
||
7 months ago
|
},
|
||
7 months ago
|
};
|
||
|
return message;
|
||
|
};
|
||
|
|
||
|
const setupConnectionHandler = () => {
|
||
|
// connectionEventNames.forEach(eventName => {
|
||
7 months ago
|
logger.info(`Setting up event ${'connection:connect'}`);
|
||
|
whatsappEvents.on('connection:connect', async connectionData => {
|
||
7 months ago
|
try {
|
||
7 months ago
|
// find Or create
|
||
|
await addCurrentConnection({
|
||
7 months ago
|
...objectMapper(connectionData, { phone: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id', createTimestamp: 'createtime' }, false),
|
||
7 months ago
|
service_type: 'baileys',
|
||
|
status: 'connecting',
|
||
|
});
|
||
|
} catch (error) {
|
||
|
logger.error({ connectionData, error }, 'error add connection');
|
||
|
}
|
||
|
});
|
||
7 months ago
|
logger.info(`Setting up event ${'connection:open'}`);
|
||
|
whatsappEvents.on('connection:open', async connectionData => {
|
||
|
logger.info(`event ${'connection:open'}`, connectionData);
|
||
|
try {
|
||
|
await updateConnection(
|
||
|
{
|
||
7 months ago
|
...objectMapper(connectionData, { whatsAppNo: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id' }),
|
||
7 months ago
|
service_type: 'baileys',
|
||
|
},
|
||
|
{ connect_domain: domain },
|
||
|
);
|
||
|
} catch (error) {
|
||
|
logger.error({ connectionData, error }, 'error add connection');
|
||
|
}
|
||
|
});
|
||
|
logger.info(`Setting up event ${'connection:close'}`);
|
||
|
whatsappEvents.on('connection:close', async connectionData => {
|
||
7 months ago
|
try {
|
||
7 months ago
|
sessionService.removeSession(connectionData.sesson_id);
|
||
7 months ago
|
await updateConnection(
|
||
|
{
|
||
|
...objectMapper(connectionData, { whatsAppNo: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id' }),
|
||
|
service_type: 'baileys',
|
||
|
},
|
||
|
{ connect_domain: domain },
|
||
|
);
|
||
7 months ago
|
// todo: 通知前端: 重新扫码
|
||
7 months ago
|
} 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 => {
|
||
|
try {
|
||
7 months ago
|
const m = await getOutboundMessage({ id: messageData.id });
|
||
|
|
||
|
const webhookBody = webhookBodyBuilder({ ...messageData, actionId: m.actionId, externalId: m.externalId }, eventName);
|
||
|
const { waiMessage } = webhookBody;
|
||
|
|
||
|
const upsert = await upsertOutboundMessage(m.sn, { ...waiMessage, msg_status: waiMessage.status });
|
||
|
// console.log('upsert=========================', upsert);
|
||
|
await callWebhook(webhookBody);
|
||
7 months ago
|
} catch (error) {
|
||
|
logger.error({ messageData, error }, 'error call webhook');
|
||
|
}
|
||
|
});
|
||
|
});
|
||
|
};
|
||
|
|
||
|
function setupWhatsappHandler() {
|
||
|
setupConnectionHandler();
|
||
|
setupMessageHandler();
|
||
|
}
|
||
|
|
||
7 months ago
|
/**
|
||
|
* 登出: 当前服务的所有连接
|
||
|
*/
|
||
|
async function resetCurrentConnection() {
|
||
|
await resetConnection();
|
||
|
}
|
||
|
|
||
|
module.exports = { setupWhatsappHandler, resetCurrentConnection };
|