first commit
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
DATABASE_CONNECTION_ATLAS = mongodb+srv://horacio:frx8us2w@reservar.a2cgd.mongodb.net/reservar
|
||||
DATABASE_CONNECTION_LOCAL = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
|
||||
DEFAULT_ADMIN_PORT = 3005
|
||||
DEFAULT_BOT_START_PORT = 3010
|
||||
CONTAINER_API_URL = http://localhost
|
||||
@@ -0,0 +1,7 @@
|
||||
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
DATABASE_CONNECTION_ATLAS = mongodb+srv://horacio:frx8us2w@reservar.a2cgd.mongodb.net/reservar
|
||||
DATABASE_CONNECTION_LOCAL = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
|
||||
DEFAULT_ADMIN_PORT = 3005
|
||||
DEFAULT_BOT_START_PORT = 3010
|
||||
CONTAINER_API_URL = http://localhost
|
||||
@@ -0,0 +1,7 @@
|
||||
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
DATABASE_CONNECTION_ATLAS = mongodb+srv://horacio:frx8us2w@reservar.a2cgd.mongodb.net/reservar
|
||||
DATABASE_CONNECTION_LOCAL = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
|
||||
DEFAULT_ADMIN_PORT = 3005
|
||||
DEFAULT_BOT_START_PORT = 3010
|
||||
CONTAINER_API_URL = http://localhost
|
||||
@@ -0,0 +1,26 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,28 @@
|
||||
# Usamos Node.js con Alpine para menor tamaño
|
||||
FROM node:22-alpine
|
||||
|
||||
# Configurar entorno global
|
||||
ENV NODEJS_ORG_MIRROR=https://nodejs.org/dist \
|
||||
NODE_ENV=production
|
||||
|
||||
# Instalar TypeScript y limpiar cache
|
||||
RUN npm install -g typescript && npm cache clean --force
|
||||
|
||||
# Crear carpetas de trabajo separadas para server y client
|
||||
WORKDIR /app
|
||||
|
||||
ARG DOCKER_GID=1001 # Valor por defecto
|
||||
RUN addgroup -g ${DOCKER_GID} docker && \
|
||||
addgroup node docker
|
||||
|
||||
WORKDIR /app/bot-admin-api
|
||||
COPY package*.json ./
|
||||
RUN npm install --omit=dev=false
|
||||
COPY . ./
|
||||
RUN npm run build
|
||||
|
||||
# Configurar puertos expuestos
|
||||
EXPOSE 3005
|
||||
|
||||
# Comando de inicio que lanza tanto el server como el client
|
||||
CMD [ "sh", "-c", "npm --prefix /app/bot-admin-api start" ]
|
||||
@@ -0,0 +1,18 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const dotenv_1 = __importDefault(require("dotenv"));
|
||||
const containers_1 = __importDefault(require("./routes/containers"));
|
||||
dotenv_1.default.config();
|
||||
const app = (0, express_1.default)();
|
||||
const PORT = process.env.DEFAULT_ADMIN_PORT || 3000;
|
||||
app.use(express_1.default.json());
|
||||
// Rutas
|
||||
app.use("/containers", containers_1.default);
|
||||
// Iniciar el servidor
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running on http://localhost:${PORT}`);
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SERVER_STATE = exports.BOT_STATE = void 0;
|
||||
const express_1 = require("express");
|
||||
const dockerService_1 = require("../services/dockerService");
|
||||
const axios_1 = __importDefault(require("axios"));
|
||||
var BOT_STATE;
|
||||
(function (BOT_STATE) {
|
||||
BOT_STATE["EXISTS"] = "exists";
|
||||
BOT_STATE["NOT_EXISTS"] = "not_exists";
|
||||
})(BOT_STATE = exports.BOT_STATE || (exports.BOT_STATE = {}));
|
||||
var SERVER_STATE;
|
||||
(function (SERVER_STATE) {
|
||||
SERVER_STATE["RUNNING"] = "running";
|
||||
SERVER_STATE["NOT_WORKING"] = "not_working";
|
||||
})(SERVER_STATE = exports.SERVER_STATE || (exports.SERVER_STATE = {}));
|
||||
const router = (0, express_1.Router)();
|
||||
const getContainerApiUrl = (port) => {
|
||||
const baseUrl = process.env.CONTAINER_API_URL ? process.env.CONTAINER_API_URL : "http://localhost";
|
||||
const url = `${baseUrl}:${port}/`;
|
||||
return url;
|
||||
};
|
||||
// Obtener todos los contenedores
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const containers = await (0, dockerService_1.listContainers)();
|
||||
res.json(containers);
|
||||
}
|
||||
catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
// Iniciar un contenedor por ID
|
||||
router.post("/:id/start", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
|
||||
await (0, dockerService_1.startContainer)(containerInfo.Id);
|
||||
res.json({ message: `El bot ${containerInfo.Id} ha sido iniciado` });
|
||||
}
|
||||
catch (error) {
|
||||
if (error.message.indexOf("already started") >= 0) {
|
||||
res.json({ message: `El bot se encontraba iniciado anteriormente.` });
|
||||
return;
|
||||
}
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
// Obtener el QR de conexion para el bot de una organization.
|
||||
router.get("/:id/qr", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
|
||||
const url = getContainerApiUrl(containerInfo.Ports[0].PublicPort.toString()); // "http://localhost:" + containerInfo.Ports[0].PublicPort + "/";
|
||||
const response = await axios_1.default.get(url, { responseType: "arraybuffer" });
|
||||
res.setHeader("Content-type", "image/png");
|
||||
res.send(response.data);
|
||||
}
|
||||
catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
// Detener un contenedor por ID
|
||||
router.post("/:id/stop", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
|
||||
await (0, dockerService_1.stopContainer)(containerInfo.Id);
|
||||
res.json({ message: `El bot de la organizacion ${organizationId} ha sido detenido` });
|
||||
}
|
||||
catch (error) {
|
||||
console.log(error.message);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
// Eliminar un contenedor por ID
|
||||
router.delete("/:id", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
|
||||
await (0, dockerService_1.removeContainer)(containerInfo.Id);
|
||||
res.json({ message: `El bot de la organizacion ${organizationId} removed` });
|
||||
}
|
||||
catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
// Crear un nuevo contenedor
|
||||
router.post("/create", async (req, res) => {
|
||||
try {
|
||||
const { organizationId } = req.body;
|
||||
const port = await (0, dockerService_1.getAvailablePort)();
|
||||
if (!port) {
|
||||
res.status(400).json({ error: "Port is required" });
|
||||
return;
|
||||
}
|
||||
if (await (0, dockerService_1.existsContainer)(organizationId)) {
|
||||
res.json({ message: `Ya existe un bot de whatsapp creado para esta organizacion` });
|
||||
return;
|
||||
}
|
||||
const containerName = `${organizationId}_bot_${port}`;
|
||||
const imageName = "txbot";
|
||||
const containerId = await (0, dockerService_1.createContainer)(port, containerName, imageName);
|
||||
console.log(`Se ha creado un nuevo bot en el contenedor ${containerId} para la organizacion ${organizationId}`);
|
||||
res.json({ message: `El bot ha sido creado con exito`, port, organizationId });
|
||||
}
|
||||
catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
// Consultar el estado de un contenedor par auna organizationId
|
||||
router.post("/:id/status", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const info = await (0, dockerService_1.getContainerByOrganization)(organizationId);
|
||||
res.json({ state: BOT_STATE.EXISTS, status: info.Status, serverState: SERVER_STATE.RUNNING });
|
||||
}
|
||||
catch (error) {
|
||||
res.status(500).json({ error: error.message, code: 404 });
|
||||
}
|
||||
});
|
||||
router.post("/:id/send", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const data = req.body;
|
||||
const info = await (0, dockerService_1.getContainerByOrganization)(organizationId);
|
||||
const url = getContainerApiUrl(info.Ports[0].PublicPort.toString());
|
||||
const result = await axios_1.default.post(url + "v1/messages", data);
|
||||
if (result.status !== 200) {
|
||||
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
|
||||
}
|
||||
res.json({ message: `Mensaje enviado` });
|
||||
}
|
||||
catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
router.post("/:id/session", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const data = req.body;
|
||||
const info = await (0, dockerService_1.getContainerByOrganization)(organizationId);
|
||||
const url = getContainerApiUrl(info.Ports[0].PublicPort.toString());
|
||||
const result = await axios_1.default.post(url + "v1/session", data);
|
||||
if (result.status !== 200) {
|
||||
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
|
||||
}
|
||||
const resultData = result.data;
|
||||
res.json({ message: `${resultData}` });
|
||||
}
|
||||
catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
exports.default = router;
|
||||
@@ -0,0 +1,127 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getContainerByOrganization = exports.removeContainer = exports.createContainer = exports.stopContainer = exports.startContainer = exports.getAvailablePort = exports.getOrganizationBotPort = exports.existsContainer = exports.listContainers = void 0;
|
||||
const dockerode_1 = __importDefault(require("dockerode"));
|
||||
const docker = new dockerode_1.default();
|
||||
/**
|
||||
* Listar todos los contenedores.
|
||||
*/
|
||||
const listContainers = async () => {
|
||||
return docker.listContainers({ all: true });
|
||||
};
|
||||
exports.listContainers = listContainers;
|
||||
const existsContainer = async (organizationId) => {
|
||||
const contenedores = await (0, exports.listContainers)();
|
||||
const contenedoresNombres = Array.from(contenedores, (item) => item.Names[0].split("_bot")[0].substring(1));
|
||||
if (contenedoresNombres.includes(organizationId)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
exports.existsContainer = existsContainer;
|
||||
const getOrganizationBotPort = async (organizationId) => {
|
||||
const contenedores = await (0, exports.listContainers)();
|
||||
for (const contenedor of contenedores) {
|
||||
if (contenedor.Names.includes(organizationId)) {
|
||||
const port = contenedor.Ports[0].PublicPort;
|
||||
return port;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
exports.getOrganizationBotPort = getOrganizationBotPort;
|
||||
const getAvailablePort = async () => {
|
||||
const contenedores = await (0, exports.listContainers)();
|
||||
let defaultPort = process.env.DEFAULT_BOT_START_PORT ? parseInt(process.env.DEFAULT_BOT_START_PORT) : -1;
|
||||
if (contenedores.length == 0) {
|
||||
return defaultPort;
|
||||
}
|
||||
contenedores.sort((a, b) => b.Created - a.Created);
|
||||
//Obtengo el contenedor mas reciente.
|
||||
const lastContainerCreated = contenedores.shift();
|
||||
if (!lastContainerCreated) {
|
||||
return defaultPort;
|
||||
}
|
||||
const lastPort = lastContainerCreated.Ports;
|
||||
if (!lastPort) {
|
||||
return defaultPort;
|
||||
}
|
||||
if (lastPort.length == 0) {
|
||||
return defaultPort;
|
||||
}
|
||||
return lastPort[0].PublicPort + 1;
|
||||
};
|
||||
exports.getAvailablePort = getAvailablePort;
|
||||
/**
|
||||
* Iniciar un contenedor por ID.
|
||||
*/
|
||||
const startContainer = async (containerId) => {
|
||||
const container = docker.getContainer(containerId);
|
||||
await container.start();
|
||||
};
|
||||
exports.startContainer = startContainer;
|
||||
/**
|
||||
* Detener un contenedor por ID.
|
||||
*/
|
||||
const stopContainer = async (containerId) => {
|
||||
const container = docker.getContainer(containerId);
|
||||
await container.stop();
|
||||
};
|
||||
exports.stopContainer = stopContainer;
|
||||
const createContainer = async (port, name, image) => {
|
||||
try {
|
||||
// Crear un contenedor con las configuraciones especificadas
|
||||
const container = await docker.createContainer({
|
||||
Image: image,
|
||||
name,
|
||||
Env: [`PORT=${port}`],
|
||||
ExposedPorts: {
|
||||
[`${port}/tcp`]: {}, // Define el puerto expuesto
|
||||
},
|
||||
HostConfig: {
|
||||
PortBindings: {
|
||||
[`${port}/tcp`]: [{ HostPort: `${port}` }], // Mapea el puerto entre el host y el contenedor
|
||||
},
|
||||
},
|
||||
});
|
||||
// Iniciar el contenedor creado
|
||||
await container.start();
|
||||
// Devolver el ID del contenedor como resultado
|
||||
return container.id;
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Error al crear el contenedor: ${error.message}`);
|
||||
}
|
||||
};
|
||||
exports.createContainer = createContainer;
|
||||
const removeContainer = async (containerId) => {
|
||||
try {
|
||||
// Obtiene el contenedor por su ID
|
||||
const container = docker.getContainer(containerId);
|
||||
// Verifica si el contenedor existe antes de intentar eliminarlo
|
||||
const containerInfo = await container.inspect();
|
||||
if (containerInfo.State.Running) {
|
||||
// Si el contenedor está corriendo, debe detenerse primero
|
||||
await container.stop();
|
||||
}
|
||||
// Elimina el contenedor
|
||||
await container.remove();
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Error al eliminar el contenedor: ${error.message}`);
|
||||
}
|
||||
};
|
||||
exports.removeContainer = removeContainer;
|
||||
const getContainerByOrganization = async (organizationId) => {
|
||||
const contenedores = await (0, exports.listContainers)();
|
||||
for (const contenedor of contenedores) {
|
||||
if (contenedor.Names.some((item) => item.includes(organizationId))) {
|
||||
return contenedor;
|
||||
}
|
||||
}
|
||||
throw new Error("Container not found");
|
||||
};
|
||||
exports.getContainerByOrganization = getContainerByOrganization;
|
||||
@@ -0,0 +1,17 @@
|
||||
version: "3.8"
|
||||
|
||||
services:
|
||||
bot-admin-api:
|
||||
image: bot-admin-api
|
||||
container_name: bot-admin-api
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
ports:
|
||||
- 3005:3005
|
||||
networks:
|
||||
- tx-net
|
||||
|
||||
networks:
|
||||
tx-net:
|
||||
driver: bridge
|
||||
Generated
+2587
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "bot-admin-api",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev": "ts-node-dev src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node build/index.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"description": "",
|
||||
"dependencies": {
|
||||
"axios": "^1.8.2",
|
||||
"cors": "^2.8.5",
|
||||
"dockerode": "^4.0.3",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.21.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/axios": "^0.9.36",
|
||||
"@types/dockerode": "^3.3.34",
|
||||
"@types/dotenv": "^6.1.1",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/node": "^22.10.5",
|
||||
"ts-node-dev": "^2.0.0",
|
||||
"typescript": "5.0.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import express from "express";
|
||||
import dotenv from "dotenv";
|
||||
import containerRoutes from "./routes/containers";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const app = express()
|
||||
|
||||
const PORT = process.env.DEFAULT_ADMIN_PORT || 3000;
|
||||
app.use(express.json());
|
||||
|
||||
// Rutas
|
||||
app.use("/containers", containerRoutes);
|
||||
|
||||
// Iniciar el servidor
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running on http://localhost:${PORT}`);
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { Router } from "express";
|
||||
import {
|
||||
createContainer,
|
||||
listContainers,
|
||||
removeContainer,
|
||||
startContainer,
|
||||
stopContainer,
|
||||
getAvailablePort,
|
||||
existsContainer,
|
||||
getContainerByOrganization,
|
||||
} from "../services/dockerService";
|
||||
import axios from "axios";
|
||||
|
||||
export enum BOT_STATE {
|
||||
"EXISTS" = "exists",
|
||||
"NOT_EXISTS" = "not_exists",
|
||||
}
|
||||
|
||||
export enum SERVER_STATE {
|
||||
"RUNNING" = "running",
|
||||
"NOT_WORKING" = "not_working",
|
||||
}
|
||||
|
||||
const router = Router();
|
||||
|
||||
const getContainerApiUrl = (name: string, port: string): string => {
|
||||
const isProduction = process.env.NODE_ENV === "production";
|
||||
const baseUrl = isProduction ? name : "localhost";
|
||||
const url = `http:/${baseUrl}:${port}/`;
|
||||
return url;
|
||||
};
|
||||
|
||||
// Obtener todos los contenedores
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const containers = await listContainers();
|
||||
res.json(containers);
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Iniciar un contenedor por ID
|
||||
router.post("/:id/start", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await getContainerByOrganization(organizationId);
|
||||
await startContainer(containerInfo.Id);
|
||||
res.json({ message: `El bot ${containerInfo.Id} ha sido iniciado` });
|
||||
} catch (error: any) {
|
||||
if (error.message.indexOf("already started") >= 0) {
|
||||
res.json({ message: `El bot se encontraba iniciado anteriormente.` });
|
||||
return;
|
||||
}
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Obtener el QR de conexion para el bot de una organization.
|
||||
router.get("/:id/qr", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await getContainerByOrganization(organizationId);
|
||||
const containerName = containerInfo.Names[0].toString();
|
||||
const containerPort = containerInfo.Ports[0].PublicPort.toString();
|
||||
const url = getContainerApiUrl(containerName, containerPort);
|
||||
const response = await axios.get(url, { responseType: "arraybuffer" });
|
||||
res.setHeader("Content-type", "image/png");
|
||||
res.send(response.data);
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Detener un contenedor por ID
|
||||
router.post("/:id/stop", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await getContainerByOrganization(organizationId);
|
||||
await stopContainer(containerInfo.Id);
|
||||
res.json({ message: `El bot de la organizacion ${organizationId} ha sido detenido` });
|
||||
} catch (error: any) {
|
||||
console.log(error.message);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Eliminar un contenedor por ID
|
||||
router.delete("/:id", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const containerInfo = await getContainerByOrganization(organizationId);
|
||||
await removeContainer(containerInfo.Id);
|
||||
res.json({ message: `El bot de la organizacion ${organizationId} removed` });
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Crear un nuevo contenedor
|
||||
router.post("/create", async (req, res) => {
|
||||
try {
|
||||
const { organizationId } = req.body;
|
||||
const port = await getAvailablePort();
|
||||
|
||||
if (!port) {
|
||||
res.status(400).json({ error: "Port is required" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (await existsContainer(organizationId)) {
|
||||
res.json({ message: `Ya existe un bot de whatsapp creado para esta organizacion` });
|
||||
return;
|
||||
}
|
||||
|
||||
const containerName = `${organizationId}_bot_${port}`;
|
||||
const imageName = "txbot";
|
||||
|
||||
const containerId = await createContainer(port, containerName, imageName);
|
||||
console.log(
|
||||
`Se ha creado un nuevo bot en el contenedor ${containerId} para la organizacion ${organizationId}`
|
||||
);
|
||||
res.json({ message: `El bot ha sido creado con exito`, port, organizationId });
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Consultar el estado de un contenedor par auna organizationId
|
||||
router.post("/:id/status", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const info = await getContainerByOrganization(organizationId);
|
||||
res.json({
|
||||
state: BOT_STATE.EXISTS,
|
||||
status: info.Status,
|
||||
serverState: SERVER_STATE.RUNNING,
|
||||
});
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: error.message, code: 404 });
|
||||
}
|
||||
});
|
||||
|
||||
export interface MessageData {
|
||||
number: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
router.post("/:id/send", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const data = req.body as MessageData;
|
||||
const info = await getContainerByOrganization(organizationId);
|
||||
const containerName = info.Names[0].toString();
|
||||
const containerPort = info.Ports[0].PublicPort.toString();
|
||||
const url = getContainerApiUrl(containerName, containerPort);
|
||||
const result = await axios.post(url + "v1/messages", data);
|
||||
|
||||
if (result.status !== 200) {
|
||||
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
|
||||
}
|
||||
|
||||
res.json({ message: `Mensaje enviado` });
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/:id/session", async (req, res) => {
|
||||
try {
|
||||
const organizationId = req.params.id;
|
||||
const data = req.body as MessageData;
|
||||
const info = await getContainerByOrganization(organizationId);
|
||||
|
||||
const containerName = info.Names[0].toString();
|
||||
const containerPort = info.Ports[0].PublicPort.toString();
|
||||
const url = getContainerApiUrl(containerName, containerPort);
|
||||
|
||||
const result = await axios.post(url + "v1/session", data);
|
||||
|
||||
if (result.status !== 200) {
|
||||
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
|
||||
}
|
||||
|
||||
const resultData = result.data;
|
||||
|
||||
res.json({ message: `${resultData}` });
|
||||
} catch (error: any) {
|
||||
console.log(error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,152 @@
|
||||
import Docker from "dockerode";
|
||||
|
||||
const docker = new Docker();
|
||||
|
||||
/**
|
||||
* Listar todos los contenedores.
|
||||
*/
|
||||
export const listContainers = async () => {
|
||||
return docker.listContainers({ all: true, filters: { ancestor: ["txbot:latest"] } });
|
||||
};
|
||||
|
||||
export const existsContainer = async (organizationId: string): Promise<boolean> => {
|
||||
const contenedores = await listContainers();
|
||||
const contenedoresNombres = Array.from(contenedores, (item) =>
|
||||
item.Names[0].split("_bot")[0].substring(1)
|
||||
);
|
||||
|
||||
if (contenedoresNombres.includes(organizationId)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
export const getOrganizationBotPort = async (organizationId: string): Promise<number> => {
|
||||
const contenedores = await listContainers();
|
||||
|
||||
for (const contenedor of contenedores) {
|
||||
if (contenedor.Names.includes(organizationId)) {
|
||||
const port = contenedor.Ports[0].PublicPort;
|
||||
return port;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
|
||||
export const getAvailablePort = async (): Promise<number> => {
|
||||
const contenedores = await listContainers();
|
||||
|
||||
let defaultPort = process.env.DEFAULT_BOT_START_PORT
|
||||
? parseInt(process.env.DEFAULT_BOT_START_PORT)
|
||||
: -1;
|
||||
|
||||
if (contenedores.length == 0) {
|
||||
return defaultPort;
|
||||
}
|
||||
|
||||
contenedores.sort((a, b) => b.Created - a.Created);
|
||||
|
||||
//Obtengo el contenedor mas reciente.
|
||||
const lastContainerCreated = contenedores.shift();
|
||||
|
||||
if (!lastContainerCreated) {
|
||||
return defaultPort;
|
||||
}
|
||||
|
||||
const lastPort = lastContainerCreated.Ports;
|
||||
|
||||
if (!lastPort) {
|
||||
return defaultPort;
|
||||
}
|
||||
|
||||
if (lastPort.length == 0) {
|
||||
return defaultPort;
|
||||
}
|
||||
|
||||
return lastPort[0].PublicPort + 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Iniciar un contenedor por ID.
|
||||
*/
|
||||
export const startContainer = async (containerId: string) => {
|
||||
const container = docker.getContainer(containerId);
|
||||
await container.start();
|
||||
};
|
||||
|
||||
/**
|
||||
* Detener un contenedor por ID.
|
||||
*/
|
||||
export const stopContainer = async (containerId: string) => {
|
||||
const container = docker.getContainer(containerId);
|
||||
await container.stop();
|
||||
};
|
||||
|
||||
export const createContainer = async (
|
||||
port: number,
|
||||
name: string,
|
||||
image: string
|
||||
): Promise<string> => {
|
||||
try {
|
||||
// Crear un contenedor con las configuraciones especificadas
|
||||
const container = await docker.createContainer({
|
||||
Image: image,
|
||||
name,
|
||||
Env: [`PORT=${port}`],
|
||||
ExposedPorts: {
|
||||
[`${port}/tcp`]: {}, // Define el puerto expuesto
|
||||
},
|
||||
HostConfig: {
|
||||
PortBindings: {
|
||||
[`${port}/tcp`]: [{ HostPort: `${port}` }], // Mapea el puerto entre el host y el contenedor
|
||||
},
|
||||
},
|
||||
NetworkingConfig: {
|
||||
EndpointsConfig: {
|
||||
"bot-admin-api_tx-net": {}, // importante: debe coincidir con el nombre exacto de la red
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Iniciar el contenedor creado
|
||||
await container.start();
|
||||
|
||||
// Devolver el ID del contenedor como resultado
|
||||
return container.id;
|
||||
} catch (error: any) {
|
||||
throw new Error(`Error al crear el contenedor: ${error.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
export const removeContainer = async (containerId: string): Promise<void> => {
|
||||
try {
|
||||
// Obtiene el contenedor por su ID
|
||||
const container = docker.getContainer(containerId);
|
||||
|
||||
// Verifica si el contenedor existe antes de intentar eliminarlo
|
||||
const containerInfo = await container.inspect();
|
||||
if (containerInfo.State.Running) {
|
||||
// Si el contenedor está corriendo, debe detenerse primero
|
||||
await container.stop();
|
||||
}
|
||||
|
||||
// Elimina el contenedor
|
||||
await container.remove();
|
||||
} catch (error: any) {
|
||||
throw new Error(`Error al eliminar el contenedor: ${error.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
export const getContainerByOrganization = async (
|
||||
organizationId: string
|
||||
): Promise<Docker.ContainerInfo> => {
|
||||
const contenedores = await listContainers();
|
||||
|
||||
for (const contenedor of contenedores) {
|
||||
if (contenedor.Names.some((item) => item.includes(organizationId))) {
|
||||
return contenedor;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Container not found");
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
/* Language and Environment */
|
||||
"target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
"experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||
"emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
//"rootDir": "./src", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
"baseUrl": ".", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
|
||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
|
||||
"resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
"outDir": "./build", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
//"noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
//"noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user