Files
2026-01-27 14:51:41 -05:00

116 lines
3.5 KiB
PHP

<?php
/**
* API interna para empujar eventos SSE
* Este endpoint es llamado por el webhook para notificar eventos
* Fecha: 27 de enero de 2026
*/
require_once '../config/config.php';
header('Content-Type: application/json; charset=utf-8');
// Solo permitir llamadas internas
$allowedIPs = ['127.0.0.1', '::1', 'localhost'];
$clientIP = $_SERVER['REMOTE_ADDR'] ?? '';
// En producción, verificar IP o usar token secreto
$secretToken = $_SERVER['HTTP_X_PUSH_TOKEN'] ?? $_POST['push_token'] ?? '';
$validToken = getenv('PUSH_TOKEN') ?: 'internal_push_secret_2026';
if (!in_array($clientIP, $allowedIPs) && $secretToken !== $validToken) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No autorizado']);
exit;
}
try {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$eventType = $input['event_type'] ?? 'message';
$eventData = $input['data'] ?? [];
$targetUserId = $input['target_user_id'] ?? 'all'; // ID del operador, no del cliente
// Si no se especifica usuario objetivo, broadcast a todos
$targets = [];
if ($targetUserId === 'all') {
// Broadcast: usar archivo global para todos los clientes conectados
$targets = ['global'];
// Opcional: También enviar a usuarios con token conocidos
// (buscar archivos events_token_*.json en uploads)
$uploadsDir = __DIR__ . '/../uploads/';
if (is_dir($uploadsDir)) {
$tokenFiles = glob($uploadsDir . 'events_token_*.json');
foreach ($tokenFiles as $file) {
$basename = basename($file, '.json');
$userId = str_replace('events_', '', $basename);
if ($userId && $userId !== 'global') {
$targets[] = $userId;
}
}
}
} else {
$targets = [$targetUserId];
}
// Escribir evento en archivos temporales para cada usuario objetivo
$eventId = uniqid('evt_', true);
$event = [
'id' => $eventId,
'type' => $eventType,
'data' => $eventData,
'timestamp' => time()
];
$written = 0;
foreach ($targets as $target) {
$eventsFile = __DIR__ . "/../uploads/events_{$target}.json";
// Asegurar que el directorio existe
$dir = dirname($eventsFile);
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
// Leer eventos existentes
$existingEvents = [];
if (file_exists($eventsFile)) {
$content = @file_get_contents($eventsFile);
if ($content) {
$existingEvents = json_decode($content, true) ?: [];
}
}
// Agregar nuevo evento
$existingEvents[] = $event;
// Mantener solo últimos 50 eventos
if (count($existingEvents) > 50) {
$existingEvents = array_slice($existingEvents, -50);
}
// Guardar
if (@file_put_contents($eventsFile, json_encode($existingEvents))) {
$written++;
}
}
echo json_encode([
'success' => true,
'event_id' => $eventId,
'targets_notified' => $written
]);
} catch (Exception $e) {
error_log("push_event.php error: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}