File size: 4,439 Bytes
4888678 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
const Message = require('../models/Message');
const Conversation = require('../models/Conversation');
const { generateAIResponse } = require('../services/aiService');
const Joi = require('joi');
// Validation schema
const sendMessageSchema = Joi.object({
conversationId: Joi.string().required(),
content: Joi.string().min(1).max(10000).required()
});
// Send message
exports.sendMessage = async (req, res) => {
try {
// Validate input
const { error } = sendMessageSchema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
const { conversationId, content } = req.body;
const userId = req.userId;
// Verify conversation belongs to user
const conversation = await Conversation.findOne({
_id: conversationId,
userId
});
if (!conversation) {
return res.status(404).json({ error: 'Conversation not found' });
}
// Create user message
const userMessage = new Message({
conversationId,
sender: 'user',
content
});
await userMessage.save();
// Update conversation
conversation.messageCount += 1;
conversation.lastMessageAt = new Date();
// Update title if it's the first message
if (conversation.messageCount === 1) {
conversation.title = content.substring(0, 50) + (content.length > 50 ? '...' : '');
}
await conversation.save();
// Generate AI response
const aiResponse = await generateAIResponse(content, conversationId);
const assistantMessage = new Message({
conversationId,
sender: 'assistant',
content: aiResponse.content,
metadata: aiResponse.metadata
});
await assistantMessage.save();
// Update conversation message count
conversation.messageCount += 1;
conversation.lastMessageAt = new Date();
await conversation.save();
// Emit to socket if available
const io = req.app.get('socketio');
if (io) {
io.to(`user_${userId}`).emit('newMessage', {
userMessage,
assistantMessage
});
}
res.json({
userMessage,
assistantMessage
});
} catch (error) {
console.error('Send message error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
// Get messages for a conversation
exports.getMessages = async (req, res) => {
try {
const { conversationId } = req.params;
const { page = 1, limit = 50 } = req.query;
const userId = req.userId;
// Verify conversation belongs to user
const conversation = await Conversation.findOne({
_id: conversationId,
userId
});
if (!conversation) {
return res.status(404).json({ error: 'Conversation not found' });
}
// Get messages with pagination
const messages = await Message.find({ conversationId })
.sort({ createdAt: 1 })
.limit(limit * 1)
.skip((page - 1) * limit);
const total = await Message.countDocuments({ conversationId });
res.json({
messages,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total,
pages: Math.ceil(total / limit)
}
});
} catch (error) {
console.error('Get messages error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
// Delete message
exports.deleteMessage = async (req, res) => {
try {
const { messageId } = req.params;
const userId = req.userId;
// Find message and verify ownership
const message = await Message.findById(messageId).populate({
path: 'conversationId',
select: 'userId'
});
if (!message) {
return res.status(404).json({ error: 'Message not found' });
}
if (message.conversationId.userId.toString() !== userId) {
return res.status(403).json({ error: 'Unauthorized' });
}
await Message.findByIdAndDelete(messageId);
// Update conversation message count
await Conversation.findByIdAndUpdate(message.conversationId._id, {
$inc: { messageCount: -1 }
});
res.json({ message: 'Message deleted successfully' });
} catch (error) {
console.error('Delete message error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}; |