Compare commits

..

5 Commits

159
server.js
View File

@@ -161,16 +161,10 @@ app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public')); app.use(express.static('public'));
app.use(session({ app.use(session({
secret: process.env.SESSION_SECRET || 'educat-secret-key-2025', secret: process.env.SESSION_SECRET || 'educat-secret-key',
resave: true, resave: false,
saveUninitialized: true, saveUninitialized: false,
rolling: true, cookie: { secure: false, maxAge: 24 * 60 * 60 * 1000 } // 24 hours
cookie: {
secure: false,
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days instead of 1 day
httpOnly: true
},
name: 'educat.session.id' // Custom session name
})); }));
app.use(flash()); app.use(flash());
@@ -783,24 +777,23 @@ app.get('/dashboard', requireAuth, async (req, res) => {
// Chat route // Chat route
app.get('/chat', requireAuth, async (req, res) => { app.get('/chat', requireAuth, async (req, res) => {
try { try {
// Initialize chat session ID if it doesn't exist // Load user chat history
if (!req.session.chatSessionId) { let chatHistory = [];
req.session.chatSessionId = `educat-${req.session.userId}-${Date.now()}`; try {
} chatHistory = await loadChatHistory(req.session.userId);
} catch (error) {
// Initialize chat history in session if it doesn't exist console.error('Error loading chat history:', error);
if (!req.session.chatHistory) { chatHistory = [];
req.session.chatHistory = [];
} }
res.render('chat', { res.render('chat', {
title: 'Chat with EduCat AI', title: 'AI Chat - EduCat',
chatHistory: req.session.chatHistory chatHistory: chatHistory
}); });
} catch (error) { } catch (error) {
console.error('Chat route error:', error); console.error('Chat route error:', error);
res.render('chat', { res.render('chat', {
title: 'Chat with EduCat AI', title: 'AI Chat - EduCat',
chatHistory: [] chatHistory: []
}); });
} }
@@ -1108,54 +1101,41 @@ app.post('/api/chat', requireAuth, async (req, res) => {
}); });
} }
// Initialize chat history in session if it doesn't exist // Load existing chat history from storage
if (!req.session.chatHistory) { let existingHistory = [];
req.session.chatHistory = []; try {
existingHistory = await loadChatHistory(req.session.userId);
} catch (error) {
console.log('No existing chat history found, starting fresh');
} }
// Initialize or get persistent chat session ID for this user // Prepare history for API call (last 10 conversations)
if (!req.session.chatSessionId) { const recentHistory = existingHistory.slice(-10).map(conv => [
req.session.chatSessionId = `${req.session.userId}-${Date.now()}`; { role: 'human', content: conv.human },
} { role: 'ai', content: conv.ai }
]).flat();
// Prepare the request payload for Flowise with sessionId and chatId
const flowisePayload = { // Call Flowise API for chat
question: message, const response = await axios.post(`${FLOWISE_API_URL}/${FLOWISE_CHATFLOW_ID}`, {
history: req.session.chatHistory, question: message.trim(),
sessionId: req.session.chatSessionId history: recentHistory
}; });
// Add chatId if we have one from previous conversations const botResponse = response.data.text || response.data.answer || 'Sorry, I could not process your request.';
if (req.session.chatId) {
flowisePayload.chatId = req.session.chatId; // Save the conversation to history
} const conversation = {
human: message.trim(),
// Call Flowise API for chat with session history and sessionId ai: botResponse,
const response = await axios.post(`${FLOWISE_API_URL}/${FLOWISE_CHATFLOW_ID}`, flowisePayload);
const aiResponse = response.data.text || response.data.answer || 'No response received';
// Save the chatId from Flowise response for future requests
if (response.data.chatId) {
req.session.chatId = response.data.chatId;
}
// Add the conversation to session history
req.session.chatHistory.push({
human: message,
ai: aiResponse,
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}); };
// Save session existingHistory.push(conversation);
req.session.save((err) => { await saveChatHistory(req.session.userId, existingHistory);
if (err) {
console.error('Error saving session:', err);
}
});
res.json({ res.json({
success: true, success: true,
response: aiResponse response: botResponse
}); });
} catch (error) { } catch (error) {
console.error('Chat error:', error); console.error('Chat error:', error);
@@ -1167,47 +1147,13 @@ app.post('/api/chat', requireAuth, async (req, res) => {
} }
}); });
// Get chat history endpoint // Delete chat history endpoint
app.get('/api/chat/history', requireAuth, (req, res) => { app.delete('/api/chat/history', requireAuth, async (req, res) => {
try { try {
const chatHistory = req.session.chatHistory || []; await clearChatHistory(req.session.userId);
res.json({ res.json({
success: true, success: true,
chatHistory: chatHistory message: 'Chat history cleared successfully'
});
} catch (error) {
console.error('Error getting chat history:', error);
res.json({
success: false,
error: 'Failed to get chat history',
details: error.message
});
}
});
// Delete chat history endpoint
app.delete('/api/chat/history', requireAuth, (req, res) => {
try {
req.session.chatHistory = [];
// Reset the session ID to start a fresh conversation
req.session.chatSessionId = `${req.session.userId}-${Date.now()}`;
// Clear the Flowise chatId
delete req.session.chatId;
req.session.save((err) => {
if (err) {
console.error('Error clearing chat session:', err);
return res.json({
success: false,
error: 'Failed to clear chat history'
});
}
res.json({
success: true,
message: 'Chat history cleared'
});
}); });
} catch (error) { } catch (error) {
console.error('Error clearing chat history:', error); console.error('Error clearing chat history:', error);
@@ -2859,11 +2805,9 @@ async function ensureChatHistoryDirectory() {
// Save chat history to persistent storage // Save chat history to persistent storage
async function saveChatHistory(userId, chatHistory) { async function saveChatHistory(userId, chatHistory) {
try { try {
console.log(`Saving chat history for user ${userId}, ${chatHistory.length} messages`);
await ensureChatHistoryDirectory(); await ensureChatHistoryDirectory();
const historyPath = path.join(CHAT_HISTORY_DIR, `chat-${userId}.json`); const historyPath = path.join(CHAT_HISTORY_DIR, `chat-${userId}.json`);
await fs.writeJSON(historyPath, chatHistory, { spaces: 2 }); await fs.writeJSON(historyPath, chatHistory, { spaces: 2 });
console.log(`Chat history saved successfully to ${historyPath}`);
} catch (error) { } catch (error) {
console.error('Error saving chat history:', error); console.error('Error saving chat history:', error);
throw error; throw error;
@@ -2873,16 +2817,12 @@ async function saveChatHistory(userId, chatHistory) {
// Load chat history from persistent storage // Load chat history from persistent storage
async function loadChatHistory(userId) { async function loadChatHistory(userId) {
try { try {
console.log(`Loading chat history for user ${userId}`);
await ensureChatHistoryDirectory(); await ensureChatHistoryDirectory();
const historyPath = path.join(CHAT_HISTORY_DIR, `chat-${userId}.json`); const historyPath = path.join(CHAT_HISTORY_DIR, `chat-${userId}.json`);
if (await fs.pathExists(historyPath)) { if (await fs.pathExists(historyPath)) {
const history = await fs.readJSON(historyPath); return await fs.readJSON(historyPath);
console.log(`Loaded ${history.length} chat messages for user ${userId}`);
return history;
} else { } else {
console.log(`No chat history file found for user ${userId}`);
return []; return [];
} }
} catch (error) { } catch (error) {
@@ -2916,7 +2856,6 @@ async function initializeDataDirectories() {
// Call initialization // Call initialization
initializeDataDirectories().catch(console.error); initializeDataDirectories().catch(console.error);
initializeDataDirectories().catch(console.error);