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

65 lines
2.2 KiB
JavaScript

const { sessionService } = 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 } = require('../../utils/commons.util');
const waInstance = {
wa: null,
};
exports.newConnect = async ctx => {
try {
const { phone } = ctx.query;
const findSession = getConnection({ sesson_id: phone, status: 'open' });
if (findSession) {
return findSession;
}
const whatsApp1 = await createWhatsApp(phone);
const qr = await whatsApp1.start();
waInstance.wa = whatsApp1;
ctx.assert(whatsApp1, 503, 'No available connections');
const { sessionId } = sessionService.createSession(phone, whatsApp1);
return { qr, phone, sessionId };
} catch (error) {
console.error('create connection error', error);
ctx.assert(null, 500, 'Failed to create connection or generate QR code.');
}
};
exports.testSend = async ctx => {
const { to, content } = ctx.request.body;
waInstance.wa.sendTextMessage(to, content);
return { waInstance, ret: 'Message sent successfully' };
};
exports.getAll = async () => {
const sessions = sessionService.sessions;
return Array.from(sessions);
};
/**
* @deprecated
*/
exports.getIn = async () => {
// Wait for at least one connection to be established (or handle the case where no connections are available)
// await new Promise(resolve => {
// const checkConnections = () => {
// if (websocketManager.getConnections().length > 0) {
// resolve();
// } else {
// setTimeout(checkConnections, 100); // Check again after 100ms
// }
// };
// checkConnections();
// });
// const availableWs = websocketManager.getAvailableConnection();
// if (!availableWs) {
// // ctx.status = 503;
// // ctx.body = { message: 'No available connections' };
// ctx.assert(availableWs, 503, 'No available connections');
// return;
// }
// // return availableWs;
// const { sessionId, url } = websocketService.createSession(availableWs);
// return { sessionId, url, message: 'Connection established' }; // availableWs
};