Files
crm.clientright.ru/crm_extensions/file_storage/api/nextcloud_webhook_redis.php

103 lines
2.8 KiB
PHP
Raw Normal View History

<?php
/**
* Nextcloud Webhook Redis Pub/Sub
*
* Получает события от Nextcloud и публикует в Redis канал
*/
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
// Логирование
$logFile = '/var/log/crm_nextcloud_webhook.log';
function logWebhook($message) {
global $logFile;
$timestamp = date('Y-m-d H:i:s');
@file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND | LOCK_EX);
}
// Проверяем метод запроса
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
// Получаем данные webhook
$input = file_get_contents('php://input');
$data = json_decode($input, true);
logWebhook("Webhook received: " . $input);
if (!$data) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
// Проверяем обязательные поля
if (!isset($data['action']) || !isset($data['file_path'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing required fields']);
exit;
}
$action = $data['action'];
$filePath = $data['file_path'];
$projectId = $data['project_id'] ?? null;
logWebhook("Processing action: $action, path: $filePath, project: $projectId");
// Создаем событие
$event = [
'type' => $action,
'data' => [
'module' => 'Project',
'recordId' => $projectId ?: '123',
'documentId' => '456',
'fileName' => basename($filePath)
],
'timestamp' => time()
];
// Публикуем в Redis
try {
$redis = new Redis();
if (!$redis->connect('127.0.0.1', 6379)) {
throw new Exception('Failed to connect to Redis');
}
// Аутентификация (в старых версиях Redis extension auth() может не возвращать результат)
try {
$redis->auth('CRM_Redis_Pass_2025_Secure!');
} catch (RedisException $e) {
throw new Exception('Redis authentication failed: ' . $e->getMessage());
}
// Публикуем в канал
$channel = 'crm:file:events';
$subscribers = $redis->publish($channel, json_encode($event));
logWebhook("Event published to Redis: " . json_encode($event) . " (subscribers: $subscribers)");
$redis->close();
http_response_code(200);
echo json_encode([
'status' => 'success',
'message' => 'Event published to Redis',
'subscribers' => $subscribers
]);
} catch (Exception $e) {
logWebhook("ERROR: Redis publish failed: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'status' => 'error',
'message' => $e->getMessage()
]);
}
?>