Primer commit del sistema separado falta mejorar mucho
This commit is contained in:
41
discord/api/recipients/create.php
Executable file
41
discord/api/recipients/create.php
Executable file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
header('Content-Type: application/json');
|
||||
require_once __DIR__ . '/../../../shared/utils/helpers.php';
|
||||
require_once __DIR__ . '/../../../shared/auth/jwt.php';
|
||||
require_once __DIR__ . '/../../../shared/database/connection.php';
|
||||
|
||||
// Verificar autenticación
|
||||
$userData = JWTAuth::authenticate();
|
||||
if (!$userData) {
|
||||
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
|
||||
}
|
||||
|
||||
// Verificar permiso
|
||||
if (!hasPermission('manage_recipients', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para crear destinatarios de Discord.'], 403);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$nombre = trim($input['nombre'] ?? '');
|
||||
$discord_id = trim($input['discord_id'] ?? '');
|
||||
$tipo = trim($input['tipo'] ?? 'canal');
|
||||
|
||||
if (empty($nombre) || empty($discord_id)) {
|
||||
jsonResponse(['success' => false, 'error' => 'Faltan datos'], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO destinatarios_discord (nombre, discord_id, tipo, activo)
|
||||
VALUES (?, ?, ?, 1)
|
||||
");
|
||||
$stmt->execute([$nombre, $discord_id, $tipo]);
|
||||
|
||||
jsonResponse(['success' => true]);
|
||||
} catch (PDOException $e) {
|
||||
if ($e->getCode() == 23000) {
|
||||
jsonResponse(['success' => false, 'error' => 'Este ID de Discord ya está registrado'], 409);
|
||||
}
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
33
discord/api/recipients/delete.php
Executable file
33
discord/api/recipients/delete.php
Executable file
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
header('Content-Type: application/json');
|
||||
require_once __DIR__ . '/../../../shared/utils/helpers.php';
|
||||
require_once __DIR__ . '/../../../shared/auth/jwt.php';
|
||||
require_once __DIR__ . '/../../../shared/database/connection.php';
|
||||
|
||||
// Verificar autenticación
|
||||
$userData = JWTAuth::authenticate();
|
||||
if (!$userData) {
|
||||
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
|
||||
}
|
||||
|
||||
// Verificar permiso
|
||||
if (!hasPermission('manage_recipients', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para eliminar destinatarios de Discord.'], 403);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$id = $input['id'] ?? null;
|
||||
|
||||
if (!$id) {
|
||||
jsonResponse(['success' => false, 'error' => 'ID requerido'], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
$stmt = $db->prepare("DELETE FROM destinatarios_discord WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
jsonResponse(['success' => true]);
|
||||
} catch (PDOException $e) {
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
85
discord/api/recipients/edit.php
Executable file
85
discord/api/recipients/edit.php
Executable file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Editar Destinatario Discord
|
||||
*/
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Habilitar errores para debug (quitar en producción estricta)
|
||||
ini_set('display_errors', 0);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
require_once __DIR__ . '/../../../shared/utils/helpers.php';
|
||||
require_once __DIR__ . '/../../../shared/auth/jwt.php';
|
||||
require_once __DIR__ . '/../../../shared/database/connection.php';
|
||||
|
||||
// Verificar autenticación
|
||||
$userData = JWTAuth::authenticate();
|
||||
if (!$userData) {
|
||||
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
|
||||
}
|
||||
|
||||
// Verificar permiso
|
||||
if (!hasPermission('manage_recipients', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para editar destinatarios de Discord.'], 403);
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$id = $input['id'] ?? null;
|
||||
$nombre = trim($input['nombre'] ?? '');
|
||||
$discord_id = trim($input['discord_id'] ?? '');
|
||||
$tipo = trim($input['tipo'] ?? '');
|
||||
|
||||
// Validaciones
|
||||
if (empty($id) || !is_numeric($id)) {
|
||||
jsonResponse(['success' => false, 'error' => 'ID de destinatario inválido'], 400);
|
||||
}
|
||||
if (empty($nombre) || empty($discord_id) || empty($tipo)) {
|
||||
jsonResponse(['success' => false, 'error' => 'Faltan datos requeridos (nombre, ID de Discord, tipo)'], 400);
|
||||
}
|
||||
if (!in_array($tipo, ['canal', 'usuario', 'grupo'])) { // Permitir 'grupo' aunque no esté en UI aún
|
||||
jsonResponse(['success' => false, 'error' => 'Tipo de destinatario inválido'], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
|
||||
// 1. Verificar si el destinatario existe y si el usuario tiene permisos
|
||||
$stmt = $db->prepare("SELECT usuario_id FROM destinatarios_discord WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
$recipient = $stmt->fetch();
|
||||
|
||||
if (!$recipient) {
|
||||
jsonResponse(['success' => false, 'error' => 'Destinatario no encontrado'], 404);
|
||||
}
|
||||
|
||||
// Opcional: Si se implementara la propiedad del destinatario, se verificaría aquí
|
||||
// if ($userData->rol !== 'Admin' && $recipient['usuario_id'] != $userData->userId) {
|
||||
// jsonResponse(['success' => false, 'error' => 'No tiene permisos para editar este destinatario'], 403);
|
||||
// }
|
||||
|
||||
// 2. Verificar duplicidad de discord_id (excluyendo el propio destinatario)
|
||||
$stmt = $db->prepare("SELECT id FROM destinatarios_discord WHERE discord_id = ? AND id != ?");
|
||||
$stmt->execute([$discord_id, $id]);
|
||||
if ($stmt->fetch()) {
|
||||
jsonResponse(['success' => false, 'error' => 'Ya existe un destinatario con este ID de Discord'], 409);
|
||||
}
|
||||
|
||||
// 3. Actualizar el destinatario
|
||||
$stmt = $db->prepare("
|
||||
UPDATE destinatarios_discord
|
||||
SET nombre = ?, discord_id = ?, tipo = ?
|
||||
WHERE id = ?
|
||||
");
|
||||
$stmt->execute([$nombre, $discord_id, $tipo, $id]);
|
||||
|
||||
logToFile('discord/recipients.log', "Destinatario editado: ID={$id}, Nombre={$nombre}, Usuario={$userData->username}");
|
||||
jsonResponse(['success' => true, 'message' => 'Destinatario actualizado correctamente']);
|
||||
|
||||
} catch (Exception $e) {
|
||||
logToFile('discord/errors.log', "Error editando destinatario: " . $e->getMessage(), 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor.'], 500);
|
||||
}
|
||||
125
discord/api/recipients/kick.php
Executable file
125
discord/api/recipients/kick.php
Executable file
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Expulsar/Remover Destinatario Discord
|
||||
* Expulsa a un usuario de un guild o remueve el bot de un canal/grupo (según el tipo)
|
||||
*/
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Habilitar errores para debug (quitar en producción estricta)
|
||||
ini_set('display_errors', 0);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
require_once __DIR__ . '/../../../shared/utils/helpers.php';
|
||||
require_once __DIR__ . '/../../../shared/auth/jwt.php';
|
||||
require_once __DIR__ . '/../../../shared/database/connection.php';
|
||||
|
||||
// Verificar autenticación
|
||||
$userData = JWTAuth::authenticate();
|
||||
if (!$userData) {
|
||||
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
|
||||
}
|
||||
|
||||
// Verificar permiso
|
||||
if (!hasPermission('manage_recipients', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para expulsar destinatarios de Discord.'], 403);
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$recipientDbId = $input['id'] ?? null; // ID de nuestra base de datos
|
||||
|
||||
if (empty($recipientDbId) || !is_numeric($recipientDbId)) {
|
||||
jsonResponse(['success' => false, 'error' => 'ID de destinatario inválido o no proporcionado'], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
$botToken = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
|
||||
$guildId = $_ENV['DISCORD_GUILD_ID'] ?? getenv('DISCORD_GUILD_ID');
|
||||
|
||||
if (!$botToken) {
|
||||
throw new Exception("Token de bot de Discord no configurado.");
|
||||
}
|
||||
if (!$guildId) {
|
||||
throw new Exception("ID de Guild de Discord no configurado.");
|
||||
}
|
||||
|
||||
// 1. Obtener detalles del destinatario de nuestra DB
|
||||
$stmt = $db->prepare("SELECT discord_id, tipo FROM destinatarios_discord WHERE id = ?");
|
||||
$stmt->execute([$recipientDbId]);
|
||||
$recipient = $stmt->fetch();
|
||||
|
||||
if (!$recipient) {
|
||||
jsonResponse(['success' => false, 'error' => 'Destinatario no encontrado en la base de datos local.'], 404);
|
||||
}
|
||||
|
||||
$discordId = $recipient['discord_id'];
|
||||
$tipo = $recipient['tipo'];
|
||||
|
||||
$actionSuccess = false;
|
||||
$actionMessage = '';
|
||||
|
||||
// Lógica para expulsar/remover según el tipo
|
||||
switch ($tipo) {
|
||||
case 'usuario':
|
||||
// Expulsar usuario de un guild (servidor)
|
||||
// Endpoint: DELETE /guilds/{guild.id}/members/{user.id}
|
||||
$url = "https://discord.com/api/v10/guilds/{$guildId}/members/{$discordId}";
|
||||
$ch = curl_init($url);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bot ' . $botToken,
|
||||
'Content-Type: application/json'
|
||||
]);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($curlError) {
|
||||
throw new Exception("Error cURL al intentar expulsar al usuario de Discord: " . $curlError);
|
||||
}
|
||||
if ($httpCode === 204) { // 204 No Content es éxito para DELETE
|
||||
$actionSuccess = true;
|
||||
$actionMessage = "Usuario {$discordId} expulsado del guild {$guildId} en Discord.";
|
||||
} else {
|
||||
$responseJson = json_decode($response, true);
|
||||
$actionMessage = "Error de Discord al expulsar usuario ({$httpCode}): " . ($responseJson['message'] ?? 'Desconocido');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'canal':
|
||||
case 'grupo':
|
||||
// Para canales/grupos, "expulsar" podría significar que el bot abandone el canal/grupo
|
||||
// Esto es más complejo y no hay un endpoint directo "abandonar canal" para un bot en v10 sin conocer el webhook.
|
||||
// Para simplificar, por ahora solo marcaremos como removido en nuestra DB.
|
||||
// Una implementación real necesitaría una lógica para que el bot salga del canal/thread.
|
||||
$actionSuccess = true; // Por ahora, se asume éxito en la acción "local"
|
||||
$actionMessage = "No hay una API directa para que el bot 'expulse' de un canal/grupo Discord. Eliminado de la base de datos local.";
|
||||
break;
|
||||
|
||||
default:
|
||||
jsonResponse(['success' => false, 'error' => 'Tipo de destinatario no soportado para expulsión.'], 400);
|
||||
break;
|
||||
}
|
||||
|
||||
if ($actionSuccess) {
|
||||
// Eliminar el destinatario de nuestra base de datos
|
||||
$deleteStmt = $db->prepare("DELETE FROM destinatarios_discord WHERE id = ?");
|
||||
$deleteStmt->execute([$recipientDbId]);
|
||||
|
||||
logToFile('discord/recipients.log', "Destinatario '{$recipient['discord_id']}' ({$tipo}) expulsado/eliminado de Discord y de la DB local por Usuario: {$userData->username}.");
|
||||
jsonResponse(['success' => true, 'message' => 'Destinatario expulsado/eliminado correctamente.', 'discord_action' => $actionMessage]);
|
||||
} else {
|
||||
logToFile('discord/errors.log', "Fallo al expulsar/eliminar destinatario '{$recipient['discord_id']}' ({$tipo}): {$actionMessage}", 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => 'Fallo al realizar la acción en Discord: ' . $actionMessage], 500);
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
logToFile('discord/errors.log', "Error general en la API de expulsión de destinatarios: " . $e->getMessage(), 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor: ' . $e->getMessage()], 500);
|
||||
}
|
||||
Reference in New Issue
Block a user