Skip to content

Commit

Permalink
Novos comandos em conexões
Browse files Browse the repository at this point in the history
  • Loading branch information
rtenorioh committed Nov 20, 2024
1 parent dcb3fae commit fcb6f24
Show file tree
Hide file tree
Showing 5 changed files with 195 additions and 3 deletions.
75 changes: 74 additions & 1 deletion backend/src/controllers/WhatsAppController.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Request, Response } from "express";
import AppError from "../errors/AppError";
import { getIO } from "../libs/socket";
import { removeWbot } from "../libs/wbot";
import { initWbot, removeWbot, shutdownWbot } from "../libs/wbot";
import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession";

import Whatsapp from "../models/Whatsapp";
import CreateWhatsAppService from "../services/WhatsappService/CreateWhatsAppService";
import DeleteWhatsAppService from "../services/WhatsappService/DeleteWhatsAppService";
import ListWhatsAppsService from "../services/WhatsappService/ListWhatsAppsService";
import RestartWhatsAppService from "../services/WhatsappService/RestartWhatsAppService";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppService";

Expand Down Expand Up @@ -124,3 +126,74 @@ export const remove = async (

return res.status(200).json({ message: "Whatsapp deleted." });
};

export const restart = async (
req: Request,
res: Response
): Promise<Response> => {
const { whatsappId } = req.params;

try {
await RestartWhatsAppService(whatsappId);
const io = getIO();
io.emit("whatsapp", {
action: "update",
whatsappId
});
return res
.status(200)
.json({ message: "WhatsApp session restarted successfully." });
} catch (error) {
return res.status(500).json({
message: "Failed to restart WhatsApp session.",
error: (error as Error).message
});
}
};

export const shutdown = async (
req: Request,
res: Response
): Promise<Response> => {
const { whatsappId } = req.params;

try {
await shutdownWbot(whatsappId);
const io = getIO();
io.emit("whatsapp", {
action: "update",
whatsappId
});
return res
.status(200)
.json({ message: "WhatsApp session shutdown successfully." });
} catch (error) {
return res.status(500).json({
message: "Failed to shutdown WhatsApp session.",
error: (error as Error).message
});
}
};

export const start = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params;
const whatsapp = await Whatsapp.findByPk(whatsappId);
if (!whatsapp) throw Error("no se encontro el whatsapp");

try {
await initWbot(whatsapp);
const io = getIO();
io.emit("whatsapp", {
action: "update",
whatsappId
});
return res
.status(200)
.json({ message: "WhatsApp session started successfully." });
} catch (error) {
return res.status(500).json({
message: "Failed to start WhatsApp session.",
error: (error as Error).message
});
}
};
28 changes: 28 additions & 0 deletions backend/src/libs/wbot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,3 +285,31 @@ export const removeWbot = (whatsappId: number): void => {
logger.error(err);
}
};

export const restartWbot = async (whatsappId: number): Promise<Session> => {
const sessionIndex = sessions.findIndex(s => s.id === whatsappId);
if (sessionIndex !== -1) {
const whatsapp = await Whatsapp.findByPk(whatsappId);
if (!whatsapp) {
throw new AppError("WhatsApp not found.");
}
sessions[sessionIndex].destroy();
sessions.splice(sessionIndex, 1);

const newSession = await initWbot(whatsapp);
return newSession;
}
throw new AppError("WhatsApp session not initialized.");
};

export const shutdownWbot = async (whatsappId: string): Promise<void> => {
const whatsappIDNumber: number = parseInt(whatsappId, 10);

const sessionIndex = sessions.findIndex(s => s.id === whatsappIDNumber);
if (sessionIndex !== -1) {
await sessions[sessionIndex].destroy();
sessions.splice(sessionIndex, 1);
} else {
throw new AppError("WhatsApp session not initialized.");
}
};
15 changes: 13 additions & 2 deletions backend/src/routes/whatsappRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import express from "express";
import isAuth from "../middleware/isAuth";

import * as WhatsAppController from "../controllers/WhatsAppController";
import isAuth from "../middleware/isAuth";

const whatsappRoutes = express.Router();

Expand All @@ -19,4 +18,16 @@ whatsappRoutes.delete(
WhatsAppController.remove
);

whatsappRoutes.post(
"/whatsapp/:whatsappId/restart",
isAuth,
WhatsAppController.restart
);

whatsappRoutes.post(
"/whatsapp/:whatsappId/shutdown",
isAuth,
WhatsAppController.shutdown
);

export default whatsappRoutes;
23 changes: 23 additions & 0 deletions backend/src/services/WhatsappService/RestartWhatsAppService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// src/services/WhatsappService/RestartWhatsAppService.ts
import { getWbot, restartWbot } from "../../libs/wbot";
import { logger } from "../../utils/logger";

const RestartWhatsAppService = async (whatsappId: string): Promise<void> => {
const whatsappIDNumber: number = parseInt(whatsappId, 10);

try {
const wbot = getWbot(whatsappIDNumber);
if (!wbot) {
throw new Error("No active session found for this ID.");
}

await restartWbot(whatsappIDNumber);
logger.info(`WhatsApp session for ID ${whatsappId} has been restarted.`);
} catch (error) {
logger.error(
`Failed to restart WhatsApp session: ${(error as Error).message}`
);
}
};

export default RestartWhatsAppService;
57 changes: 57 additions & 0 deletions frontend/src/pages/Connections/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,56 @@ const Connections = () => {
setConfirmModalInfo(confirmationModalInitialState);
};

const handleRestartSession = async (whatsAppId) => {
try {
await api.post(`/whatsapp/${whatsAppId}/restart`);
toast.success(i18n.t("connections.toasts.sessionRestarted"));
} catch (err) {
toastError(err);
}
};

const handleStartSession = async (whatsAppId) => {
try {
await api.post(`/whatsapp/${whatsAppId}/start`);
toast.success(i18n.t("connections.toasts.sessionStarted"));
} catch (err) {
toastError(err);
}
};

const handleShutdownSession = async (whatsAppId) => {
try {
await api.post(`/whatsapp/${whatsAppId}/shutdown`);
toast.success(i18n.t("connections.toasts.sessionShutdown"));
} catch (err) {
toastError(err);
}
};

const renderActionButtons = whatsApp => {
return (
<>
{whatsApp.status === "DISCONNECTED" && (
<Button
size="small"
variant="outlined"
color="primary"
onClick={() => handleStartSession(whatsApp?.id)}
>
{i18n.t("connections.buttons.start")}
</Button>
)}
{whatsApp.status === "qrcode" && (
<Button
size="small"
variant="outlined"
color="secondary"
onClick={() => handleShutdownSession(whatsApp?.id)}
>
{i18n.t("connections.buttons.shutdown")}
</Button>
)}
{whatsApp.status === "qrcode" && (
<Button
size="small"
Expand Down Expand Up @@ -274,6 +321,16 @@ const Connections = () => {
{i18n.t("connections.buttons.connecting")}
</Button>
)}
{whatsApp.status && (
<Button
size="small"
variant="outlined"
color="primary"
onClick={() => handleRestartSession(whatsApp?.id)}
>
{i18n.t("connections.buttons.restart")}
</Button>
)}
</>
);
};
Expand Down

0 comments on commit fcb6f24

Please sign in to comment.