90 lines
2.4 KiB
JavaScript
90 lines
2.4 KiB
JavaScript
const WebSocket = require('ws');
|
|
const { logger } = require('../config/logs');
|
|
|
|
class WebSocketManager {
|
|
constructor(server) {
|
|
this.wss = new WebSocket.Server({ server });
|
|
this.connections = new Map(); // Pour stocker les connexions utilisateur
|
|
this.init();
|
|
}
|
|
|
|
init() {
|
|
this.wss.on('connection', (ws, req) => {
|
|
|
|
ws.on('message', (message) => {
|
|
try {
|
|
const data = JSON.parse(message);
|
|
this.handleMessage(ws, data);
|
|
} catch (error) {
|
|
logger.error('Error handling WebSocket message:', error);
|
|
}
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
this.handleDisconnect(ws);
|
|
});
|
|
});
|
|
}
|
|
|
|
handleMessage(ws, data) {
|
|
switch (data.type) {
|
|
case 'join':
|
|
this.handleJoin(ws, data);
|
|
break;
|
|
case 'leave':
|
|
this.handleLeave(ws, data);
|
|
break;
|
|
default:
|
|
logger.warn('Unknown message type:', data.type);
|
|
}
|
|
}
|
|
|
|
handleJoin(ws, data) {
|
|
const { userId, fileId } = data;
|
|
this.connections.set(ws, { userId, fileId });
|
|
this.broadcastFileStatus(fileId);
|
|
}
|
|
|
|
handleLeave(ws, data) {
|
|
const { fileId } = data;
|
|
this.connections.delete(ws);
|
|
this.broadcastFileStatus(fileId);
|
|
}
|
|
|
|
handleDisconnect(ws) {
|
|
const connection = this.connections.get(ws);
|
|
if (connection) {
|
|
this.broadcastFileStatus(connection.fileId);
|
|
this.connections.delete(ws);
|
|
}
|
|
}
|
|
|
|
broadcastFileStatus(fileId) {
|
|
const activeUsers = Array.from(this.connections.values())
|
|
.filter(conn => conn.fileId === fileId)
|
|
.map(conn => conn.userId);
|
|
|
|
const message = JSON.stringify({
|
|
type: 'fileStatus',
|
|
fileId,
|
|
activeUsers
|
|
});
|
|
|
|
this.wss.clients.forEach(client => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(message);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Méthode pour envoyer une mise à jour à tous les clients
|
|
broadcast(data) {
|
|
this.wss.clients.forEach(client => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(JSON.stringify(data));
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = WebSocketManager; |