Spaces:
Sleeping
Sleeping
| const { send, broadcast } = require("./utils"); | |
| const rooms = new Map(); // roomCode -> { host: ws, participants: Set<ws> } | |
| function generateRoomCode() { | |
| const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
| let code = ""; | |
| for (let i = 0; i < 6; i++) code += chars[Math.floor(Math.random() * chars.length)]; | |
| return code; | |
| } | |
| function getRoom(roomCode) { | |
| return rooms.get(roomCode); | |
| } | |
| function createRoom(ws) { | |
| removeFromRoom(ws); | |
| let roomCode = generateRoomCode(); | |
| while (rooms.has(roomCode)) roomCode = generateRoomCode(); | |
| const room = { host: ws, participants: new Set([ws]) }; | |
| rooms.set(roomCode, room); | |
| ws._roomCode = roomCode; | |
| return roomCode; | |
| } | |
| function joinRoom(ws, roomCode) { | |
| const room = rooms.get(roomCode); | |
| if (!room) return null; | |
| removeFromRoom(ws); | |
| room.participants.add(ws); | |
| ws._roomCode = roomCode; | |
| return room; | |
| } | |
| function removeFromRoom(ws) { | |
| const roomCode = ws._roomCode; | |
| if (!roomCode) return; | |
| const room = rooms.get(roomCode); | |
| if (!room) return; | |
| room.participants.delete(ws); | |
| ws._roomCode = null; | |
| if (room.participants.size === 0) { | |
| rooms.delete(roomCode); | |
| return; | |
| } | |
| // Reassign host if the host left | |
| if (room.host === ws) { | |
| room.host = room.participants.values().next().value; | |
| send(room.host, { type: "promoted-to-host" }); | |
| } | |
| broadcast(room, { type: "participant-update", count: room.participants.size, members: getParticipantList(room) }); | |
| } | |
| function getParticipantList(room) { | |
| const members = []; | |
| for (const p of room.participants) { | |
| members.push({ url: p._url || null }); | |
| } | |
| return members; | |
| } | |
| module.exports = { rooms, generateRoomCode, createRoom, joinRoom, removeFromRoom, getRoom, getParticipantList }; | |