const { WebSocket, WebSocketServer } = require("ws"); const dotenv = require("dotenv"); dotenv.config(); const express = require("express"); const PORT = process.env.PORT || 3000; const PREFIX = process.env.PREFIX || ""; const PUBLIC = process.env.PUBLIC || ""; const router = express.Router(); const routes = (app) => { app.get("/", (req, res) => { res.render("index", { address: PREFIX, }); }); app.get("/destination", (req, res) => { res.render("destination", { address: PREFIX, }); }); app.get("/*", (req, res) => { res.sendFile(req.url, { root: "public" }); }); return app; }; const server = express() .set("view engine", "html") .engine("html", require("hbs").__express) .use(PREFIX, routes(router, {})) .use(express.static("public")) .listen(PORT, () => console.log(`Listening on ${PORT}`)); const wss = new WebSocketServer({ server, clientTracking: true }); let DESTINATIONS = new Set(); let USERS = new Set(); var theme = ""; const messageProcessor = { default: (ws, msg) => unknownMsg(msg), hello: (ws, msg) => registerDest(ws, msg), drawings: (ws, msg) => toDest(msg), theme: (ws, msg) => ((theme = msg.theme), broadcast(msg)), }; const unknownMsg = (msg) => { console.log("Unknown message type..."); console.log(msg); }; const registerDest = (ws, msg) => { console.log("Destination client connected"); DESTINATIONS.add(ws); ws.on("close", () => { DESTINATIONS.delete(ws); }); }; const toDest = (msg) => { DESTINATIONS.forEach((DESTINATION) => { if (DESTINATION?.readyState === WebSocket.OPEN) { DESTINATION.send(JSON.stringify(msg)); } }); }; const broadcast = (msg) => { let message = JSON.stringify(msg); for (const user of USERS.values()) { if (user?.readyState === WebSocket.OPEN && !DESTINATIONS.has(user)) { user.send(message); } } }; wss.on("connection", (ws) => { USERS.add(ws); ws.send(JSON.stringify({ type: "theme", theme: theme })); ws.on("message", (data) => { let message; try { message = JSON.parse(data); } catch (e) {} if (message) { (messageProcessor[message.type] || messageProcessor.default)(ws, message); } }); ws.on("close", () => { USERS.delete(ws); }); });