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.
Global-sales/wai-server/api/channels/channel.controller.js

74 lines
2.8 KiB
JavaScript

const { sessionStore } = require('../../core'); // Import from core/index.js
const { createWhatsApp } = require('../../core/baileys'); // Import from core/index.js
const { getConnection } = require('../../services/connections.service');
const { objectMapper, isEmpty } = require('../../utils/commons.util');
const { domain, name: domainName } = require('../../config').server;
exports.newConnect = async ctx => {
try {
const { phone } = ctx.query;
const findSession = await getConnection({ sesson_id: phone, status: ['open', 'connecting'] }); // connect_domain: domain
// // todo: 只有一条
if (!isEmpty(findSession)) {
const { sesson_id: sessionId, status, ...connection } = findSession[0];
// if (['open', 'connecting'].includes(status)) {
// const sock = sessionStore.getSession(sessionId);
// if (!isEmpty(sock)) {
// return sock;
// }
// }
// return { qr: '', phone, sessionId, ...connection }; // 返回已登录
}
const whatsApp1 = await createWhatsApp(phone);
const existsSession = sessionStore.getSession(phone);
let qr;
// if (isEmpty(existsSession)) {
qr = await whatsApp1.start();
const { sessionId } = sessionStore.createSession(phone, whatsApp1);
// }
ctx.assert(whatsApp1, 503, 'No available connections');
return { qr, phone, sessionId: phone, domainName };
} catch (error) {
console.error('create connection error', error);
ctx.assert(null, 500, 'Failed to create connection or generate QR code.');
}
};
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 = whatApp.instance;
// console.log('find wsToSend', wsToSend)
if (!wsToSend) {
ctx.assert(wsToSend, 400, 'Session not found'); // 404
return;
}
try {
const fromWebId = generateId();
console.info(`fromWebId: ${fromWebId};`);
wsToSend.sendTextMessage(to, content, fromWebId).then(({ messageId, externalId }) => {
console.info(`messageId: ${messageId}; externalId: ${externalId}`);
}).catch(ex => {
console.error('Error channel sending message:', error);
});
// const sockMsg = await wsToSend.sendTextMessage(to, content, actionId);
return 'channel sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
} catch (error) {
console.error('Error sending message:', error);
ctx.assert(null, 500, 'Failed to send message');
}
};
exports.getAll = async () => {
const findConnection = await getConnection({});
return findConnection;
};
exports.getSessions = async ctx => {
return Array.from(sessionStore.sessions);
};