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/call.controller.js

68 lines
2.4 KiB
JavaScript

const { websocketService, websocketManager } = require('../../core'); // Import from core/index.js
const generateId = require('../../utils/generateId.util');
// const { createConnection, getConnection } = require('../../core/whatsapp/connection');
// const { getAvailableConnection } = require('../../core/whatsapp/sessionStore');
exports.newConnect = async ctx => {
// try {
// const socketId = generateId();
// const { qr } = await createConnection(socketId); // Await the Promise here
// return { socketId, qr, message: 'Connection initiated. QR code provided.' }; // Return the QR code
// } catch (error) {
// console.error('create connection error', error);
// ctx.assert(null, 500, 'Failed to create connection or generate QR code.');
// }
};
exports.getIn = async ctx => {
// 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
};
exports.sendMsg = ctx => {
const { sessionId, message } = ctx.request.body;
if (!sessionId || !message) {
// ctx.status = 400;
// ctx.body = { message: 'Session ID and message are required' };
ctx.assert(sessionId, 400, 'Session ID and message are required');
return;
}
const wsToSend = websocketService.getSession(sessionId);
if (!wsToSend) {
// ctx.status = 404;
// ctx.body = { message: 'Session not found' };
ctx.assert(wsToSend, 400, 'Session not found');
return;
}
try {
wsToSend.send(message);
ctx.body = { message: 'Message sent' };
} catch (error) {
console.error('Error sending message:', error);
ctx.status = 500;
ctx.body = { message: 'Failed to send message' };
}
};