ysn-rfd's picture
Upload 302 files
057576a verified
const User = require('../models/User');
const Conversation = require('../models/Conversation');
const Message = require('../models/Message');
module.exports = (io, socket) => {
const userId = socket.userId;
console.log(`User ${userId} connected via WebSocket`);
// Join user to their conversation rooms
const joinConversationRooms = async () => {
try {
const conversations = await Conversation.find({
'participants.user': userId
});
conversations.forEach(conversation => {
socket.join(conversation._id.toString());
console.log(`User ${userId} joined room ${conversation._id}`);
});
// Update user status to online
await User.findByIdAndUpdate(userId, {
status: 'online',
lastSeen: new Date()
});
// Notify others that user is online
socket.broadcast.emit('user:status', {
userId,
status: 'online',
lastSeen: new Date()
});
} catch (error) {
console.error('Error joining conversation rooms:', error);
}
};
// Handle new message
const handleMessageSend = async (data) => {
try {
const { conversationId, content, type, attachment, replyTo } = data;
// Validate conversation membership
const conversation = await Conversation.findOne({
_id: conversationId,
'participants.user': userId
});
if (!conversation) {
socket.emit('message:error', { error: 'Not a member of this conversation' });
return;
}
// Create message
const message = new Message({
conversation: conversationId,
sender: userId,
content,
type: type || 'text',
attachment,
replyTo,
status: 'sent'
});
await message.save();
// Populate message with sender info
await message.populate('sender', 'username displayName avatar status');
if (message.replyTo) {
await message.populate('replyTo');
}
// Update conversation last activity
conversation.updatedAt = new Date();
await conversation.save();
// Emit to all users in conversation
io.to(conversationId).emit('message:receive', message);
// Emit conversation update
io.to(conversationId).emit('conversation:updated', {
conversationId,
lastMessage: message,
updatedAt: conversation.updatedAt
});
console.log(`Message sent in conversation ${conversationId} by user ${userId}`);
} catch (error) {
console.error('Error sending message:', error);
socket.emit('message:error', { error: 'Failed to send message' });
}
};
// Handle typing indicators
const handleTypingStart = (data) => {
const { conversationId } = data;
socket.to(conversationId).emit('typing:start', {
userId,
conversationId
});
};
const handleTypingStop = (data) => {
const { conversationId } = data;
socket.to(conversationId).emit('typing:stop', {
userId,
conversationId
});
};
// Handle message read receipts
const handleMessageRead = async (data) => {
try {
const { messageId, conversationId } = data;
const message = await Message.findByIdAndUpdate(
messageId,
{
$addToSet: {
readBy: {
user: userId,
readAt: new Date()
}
}
},
{ new: true }
);
if (!message) {
return;
}
// Update user's last read in conversation
await Conversation.updateOne(
{
_id: conversationId,
'participants.user': userId
},
{
$set: {
'participants.$.lastRead': new Date()
}
}
);
// Notify others in conversation
socket.to(conversationId).emit('message:read', {
messageId,
userId,
readAt: new Date()
});
} catch (error) {
console.error('Error updating read receipt:', error);
}
};
// Handle message reactions
const handleMessageReaction = async (data) => {
try {
const { messageId, emoji } = data;
const message = await Message.findById(messageId);
if (!message) {
return;
}
// Check if user already reacted with this emoji
const existingReactionIndex = message.reactions.findIndex(
reaction => reaction.user.toString() === userId && reaction.emoji === emoji
);
if (existingReactionIndex > -1) {
// Remove reaction
message.reactions.splice(existingReactionIndex, 1);
} else {
// Add reaction
message.reactions.push({
user: userId,
emoji,
createdAt: new Date()
});
}
await message.save();
await message.populate('reactions.user', 'username displayName');
// Broadcast reaction update
io.to(message.conversation.toString()).emit('message:reaction', {
messageId,
reactions: message.reactions
});
} catch (error) {
console.error('Error handling message reaction:', error);
}
};
// Handle disconnect
const handleDisconnect = async () => {
try {
console.log(`User ${userId} disconnected`);
// Update user status to offline
await User.findByIdAndUpdate(userId, {
status: 'offline',
lastSeen: new Date()
});
// Notify others that user is offline
socket.broadcast.emit('user:status', {
userId,
status: 'offline',
lastSeen: new Date()
});
} catch (error) {
console.error('Error handling disconnect:', error);
}
};
// Register event handlers
socket.on('message:send', handleMessageSend);
socket.on('typing:start', handleTypingStart);
socket.on('typing:stop', handleTypingStop);
socket.on('message:read', handleMessageRead);
socket.on('message:react', handleMessageReaction);
socket.on('disconnect', handleDisconnect);
// Initialize socket connection
joinConversationRooms();
};