File size: 6,342 Bytes
057576a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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();
};