Spaces:
Sleeping
Sleeping
| 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 }; | |