File size: 2,017 Bytes
0a8fe79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('./auth');

function setupSocket(io, db) {
  io.use((socket, next) => {
    try {
      const token = socket.handshake.auth.token;
      if (!token) {
        return next(new Error('Authentication required'));
      }
      const decoded = jwt.verify(token, JWT_SECRET);
      socket.userId = decoded.id;
      next();
    } catch (err) {
      next(new Error('Invalid token'));
    }
  });

  io.on('connection', (socket) => {
    const userId = socket.userId;

    // Join personal room for notifications
    socket.join(`user:${userId}`);

    socket.on('join-channel', (channelId) => {
      socket.join(`channel:${channelId}`);
    });

    socket.on('leave-channel', (channelId) => {
      socket.leave(`channel:${channelId}`);
    });

    socket.on('join-dm', (conversationId) => {
      socket.join(`dm:${conversationId}`);
    });

    socket.on('leave-dm', (conversationId) => {
      socket.leave(`dm:${conversationId}`);
    });

    socket.on('typing', ({ channelId }) => {
      try {
        const user = db.prepare('SELECT username FROM users WHERE id = ?').get(userId);
        if (user) {
          socket.to(`channel:${channelId}`).emit('user-typing', {
            userId,
            username: user.username,
            channelId
          });
        }
      } catch (err) {
        console.error('Typing event error:', err);
      }
    });

    socket.on('dm-typing', ({ conversationId }) => {
      try {
        const user = db.prepare('SELECT username FROM users WHERE id = ?').get(userId);
        if (user) {
          socket.to(`dm:${conversationId}`).emit('user-dm-typing', {
            userId,
            username: user.username,
            conversationId
          });
        }
      } catch (err) {
        console.error('DM typing event error:', err);
      }
    });

    socket.on('disconnect', () => {
      // Cleanup handled automatically by Socket.io
    });
  });
}

module.exports = { setupSocket };