98 lines
3.0 KiB
PHP
98 lines
3.0 KiB
PHP
<?php
|
|
// aiassist/save_message.php
|
|
// Сохранение сообщений в историю чата
|
|
|
|
header('Content-Type: application/json');
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: POST, OPTIONS');
|
|
header('Access-Control-Allow-Headers: Content-Type');
|
|
|
|
// Обработка preflight запросов
|
|
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
|
http_response_code(200);
|
|
exit();
|
|
}
|
|
|
|
try {
|
|
// Получение данных из POST запроса
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input) {
|
|
throw new Exception('Invalid JSON input');
|
|
}
|
|
|
|
$message = $input['message'] ?? '';
|
|
$type = $input['type'] ?? 'assistant'; // 'user' или 'assistant'
|
|
$context = $input['context'] ?? [];
|
|
$timestamp = $input['timestamp'] ?? date('c');
|
|
|
|
if (empty($message)) {
|
|
throw new Exception('Message is empty');
|
|
}
|
|
|
|
// Создаем уникальный ключ для истории на основе контекста
|
|
$historyKey = md5(json_encode([
|
|
'module' => $context['currentModule'] ?? '',
|
|
'record' => $context['projectId'] ?? '',
|
|
'user' => $context['userId'] ?? ''
|
|
]));
|
|
|
|
// Путь к файлу истории
|
|
$historyFile = __DIR__ . '/logs/chat_history_' . $historyKey . '.json';
|
|
|
|
// Создаем папку logs если её нет
|
|
$logsDir = __DIR__ . '/logs';
|
|
if (!is_dir($logsDir)) {
|
|
mkdir($logsDir, 0755, true);
|
|
}
|
|
|
|
$history = ['messages' => []];
|
|
|
|
// Загружаем существующую историю
|
|
if (file_exists($historyFile)) {
|
|
$historyData = file_get_contents($historyFile);
|
|
$decodedHistory = json_decode($historyData, true);
|
|
|
|
if ($decodedHistory && isset($decodedHistory['messages'])) {
|
|
$history = $decodedHistory;
|
|
}
|
|
}
|
|
|
|
// Добавляем новое сообщение
|
|
$newMessage = [
|
|
'message' => $message,
|
|
'type' => $type,
|
|
'timestamp' => $timestamp,
|
|
'context' => $context
|
|
];
|
|
|
|
$history['messages'][] = $newMessage;
|
|
|
|
// Ограничиваем историю последними 50 сообщениями
|
|
if (count($history['messages']) > 50) {
|
|
$history['messages'] = array_slice($history['messages'], -50);
|
|
}
|
|
|
|
// Сохраняем обновленную историю
|
|
$result = file_put_contents($historyFile, json_encode($history, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
|
|
|
if ($result === false) {
|
|
throw new Exception('Failed to save message to history');
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Message saved to history',
|
|
'historyKey' => $historyKey,
|
|
'totalMessages' => count($history['messages'])
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => $e->getMessage()
|
|
]);
|
|
}
|
|
?>
|