Skip to content

Commit

Permalink
Ajuste nas funções de conexões
Browse files Browse the repository at this point in the history
  • Loading branch information
rtenorioh committed Nov 29, 2024
1 parent 59461e0 commit 433d778
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 32 deletions.
23 changes: 18 additions & 5 deletions backend/src/controllers/WhatsAppController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { Request, Response } from "express";
import AppError from "../errors/AppError";
import { getIO } from "../libs/socket";
import { initWbot, removeWbot, shutdownWbot } from "../libs/wbot";
import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession";

import Whatsapp from "../models/Whatsapp";
import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession";
import CreateWhatsAppService from "../services/WhatsappService/CreateWhatsAppService";
import DeleteWhatsAppService from "../services/WhatsappService/DeleteWhatsAppService";
import ListWhatsAppsService from "../services/WhatsappService/ListWhatsAppsService";
Expand Down Expand Up @@ -157,17 +156,31 @@ export const shutdown = async (
): Promise<Response> => {
const { whatsappId } = req.params;

if (!whatsappId) {
return res.status(400).json({ message: "WhatsApp ID is required." });
}

try {
console.log(`Iniciando shutdown para WhatsApp ID: ${whatsappId}`);

await shutdownWbot(whatsappId);
console.log(
`Shutdown realizado com sucesso para WhatsApp ID: ${whatsappId}`
);

const io = getIO();
io.emit("whatsapp", {
action: "update",
whatsappId
});
return res
.status(200)
.json({ message: "WhatsApp session shutdown successfully." });
console.log("Evento emitido com sucesso via WebSocket.");

return res.status(200).json({
message: "WhatsApp session shutdown successfully."
});
} catch (error) {
console.error("Erro ao desligar o WhatsApp:", error);

return res.status(500).json({
message: "Failed to shutdown WhatsApp session.",
error: (error as Error).message
Expand Down
27 changes: 19 additions & 8 deletions backend/src/controllers/WhatsAppSessionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,25 @@ const update = async (req: Request, res: Response): Promise<Response> => {
};

const remove = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params;
const whatsapp = await ShowWhatsAppService(whatsappId);

const wbot = getWbot(whatsapp.id);

wbot.logout();

return res.status(200).json({ message: "Session disconnected." });
try {
console.log("Recebendo solicitação de desconexão...");
const { whatsappId } = req.params;
const whatsapp = await ShowWhatsAppService(whatsappId);

console.log("Obtendo instância do WhatsApp...");
const wbot = getWbot(whatsapp.id);

console.log("Executando logout...");
if (wbot && typeof wbot.logout === "function") {
await wbot.logout();
}

console.log("Logout concluído. Respondendo ao cliente...");
return res.status(200).json({ message: "Session disconnected." });
} catch (error) {
console.error("Erro ao desconectar:", error);
return res.status(500).json({ error: "Failed to disconnect session." });
}
};

export default { store, remove, update };
59 changes: 42 additions & 17 deletions backend/src/libs/wbot.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import fs from "fs/promises";
import { Configuration, CreateImageRequestSizeEnum, OpenAIApi } from "openai";
import path from "path";
import qrCode from "qrcode-terminal";
import { Client, LocalAuth, MessageMedia } from "whatsapp-web.js";
import AppError from "../errors/AppError";
Expand All @@ -20,17 +22,14 @@ interface CreateImageRequest {
}

async function findIntegrationValue(key: string): Promise<string | null> {
// Encontre a instância de integração com base na chave fornecida
const integration = await Integration.findOne({
where: { key }
});

// Se a instância for encontrada, retorne o valor
if (integration) {
return integration.value;
}

// Caso contrário, retorne null
return null as string | null;
}

Expand All @@ -50,13 +49,12 @@ let openai: OpenAIApi;
openai = new OpenAIApi(configuration);
})();

// gera resposta em texto
const getDavinciResponse = async (clientText: string): Promise<string> => {
const options = {
model: "text-davinci-003", // Modelo GPT a ser usado
prompt: clientText, // Texto enviado pelo usuário
temperature: 1, // Nível de variação das respostas geradas, 1 é o máximo
max_tokens: 4000 // Quantidade de tokens (palavras) a serem retornadas pelo bot, 4000 é o máximo
model: "text-davinci-003",
prompt: clientText,
temperature: 1,
max_tokens: 4000
};

try {
Expand All @@ -71,15 +69,14 @@ const getDavinciResponse = async (clientText: string): Promise<string> => {
}
};

// gera a url da imagem
const getDalleResponse = async (
clientText: string
): Promise<string | undefined> => {
const options: CreateImageRequest = {
prompt: clientText, // Descrição da imagem
n: 1, // Número de imagens a serem geradas
prompt: clientText,
n: 1,
// eslint-disable-next-line no-underscore-dangle
size: CreateImageRequestSizeEnum._1024x1024 // Tamanho da imagem
size: CreateImageRequestSizeEnum._1024x1024
};

try {
Expand Down Expand Up @@ -238,15 +235,15 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {

wbot.on("message", async msg => {
const msgChatGPT: string = msg.body;
// mensagem de texto

if (msgChatGPT.includes("/gpt ")) {
const index = msgChatGPT.indexOf(" ");
const question = msgChatGPT.substring(index + 1);
getDavinciResponse(question).then((response: string) => {
wbot.sendMessage(msg.from, response);
});
}
// imagem

if (msgChatGPT.includes("/gptM ")) {
const index = msgChatGPT.indexOf(" ");
const imgDescription = msgChatGPT.substring(index + 1);
Expand Down Expand Up @@ -305,11 +302,39 @@ export const restartWbot = async (whatsappId: number): Promise<Session> => {
export const shutdownWbot = async (whatsappId: string): Promise<void> => {
const whatsappIDNumber: number = parseInt(whatsappId, 10);

if (Number.isNaN(whatsappIDNumber)) {
throw new AppError("Invalid WhatsApp ID format.");
}

const sessionIndex = sessions.findIndex(s => s.id === whatsappIDNumber);
if (sessionIndex !== -1) {
if (sessionIndex === -1) {
console.warn(`Sessão com ID ${whatsappIDNumber} não foi encontrada.`);
throw new AppError("WhatsApp session not initialized.");
}

const sessionPath = path.resolve(
__dirname,
`../../.wwebjs_auth/session-bd_${whatsappIDNumber}`
);

try {
console.log(`Desligando sessão para WhatsApp ID: ${whatsappIDNumber}`);
await sessions[sessionIndex].destroy();
console.log(`Sessão com ID ${whatsappIDNumber} desligada com sucesso.`);

console.log(`Removendo arquivos da sessão: ${sessionPath}`);
await fs.rm(sessionPath, { recursive: true, force: true });
console.log(`Arquivos da sessão removidos com sucesso: ${sessionPath}`);

sessions.splice(sessionIndex, 1);
} else {
throw new AppError("WhatsApp session not initialized.");
console.log(
`Sessão com ID ${whatsappIDNumber} removida da lista de sessões.`
);
} catch (error) {
console.error(
`Erro ao desligar ou limpar a sessão com ID ${whatsappIDNumber}:`,
error
);
throw new AppError("Failed to destroy WhatsApp session.");
}
};
2 changes: 1 addition & 1 deletion frontend/src/layout/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ const LoggedInLayout = ({ children, toggleTheme, onThemeConfigUpdate }) => {
noWrap
className={classes.title}
>
{i18n.t("mainDrawer.appBar.message.hi")} {user.name}, {i18n.t("mainDrawer.appBar.message.text")} {companyData.name || "Press Ticket"}
{i18n.t("mainDrawer.appBar.message.hi")}, {user.name}! {i18n.t("mainDrawer.appBar.message.text")} {companyData.name || "Press Ticket"}.
</Typography>

<ThemeSelector toggleTheme={toggleTheme} />
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/translate/languages/pt.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ const messages = {
},
buttons: {
add: "Adicionar WhatsApp",
shutdown: "Excluir",
restart: "Restart",
disconnect: "desconectar",
tryAgain: "Tentar novamente",
Expand Down Expand Up @@ -457,7 +458,7 @@ const messages = {
appBar: {
message: {
hi: "Olá",
text: "seja bem vindo ao Sistema"
text: "Seja bem-vindo ao Sistema"
},
user: {
profile: "Perfil",
Expand Down

0 comments on commit 433d778

Please sign in to comment.