-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
185 lines (162 loc) · 5.14 KB
/
server.js
File metadata and controls
185 lines (162 loc) · 5.14 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
var http = require("http");
var fs = require("fs");
var ws = require("ws");
var path = require("path");
var URL = require("url");
// === Config ===
const MAX_DATAURL_SIZE = 1 * 1024 * 1024; // 1 MB max for data URL
// === Helper Functions ===
function setNoCorsHeaders(res) {
res.setHeader("Access-Control-Allow-Origin", "*");
}
function runStaticStuff(req, res, forceStatus) {
var url = URL.parse(req.url);
var pathname = url.pathname;
setNoCorsHeaders(res);
var file = path.join("./static/", pathname);
if (pathname == "/") file = "static/index.html";
if (file.split(".").length < 2) file += ".html";
if (!fs.existsSync(file)) {
file = "errors/404.html";
res.statusCode = 404;
}
if (typeof forceStatus !== "undefined") {
file = "errors/" + forceStatus + ".html";
res.statusCode = forceStatus;
}
fs.createReadStream(file).pipe(res);
}
function createRandomCharsString(length) {
var keys = "ABCDEFGHIJKLKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var key = "";
while (key.length < length) {
key += keys[Math.floor(Math.random() * keys.length)];
}
return key;
}
// === Main Server ===
const server = http.createServer(async function (req, res) {
var url = decodeURIComponent(req.url);
var urlsplit = url.split("/");
setNoCorsHeaders(res);
if (urlsplit[1] == "room" && urlsplit[2] == "create") {
const newRoomId = Date.now().toString();
createRoom(newRoomId); // create the room early
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ roomId: newRoomId }));
return;
}
runStaticStuff(req, res);
});
// === Room Management ===
var rooms = {}; // { roomId: { wsServer, timeout, createdAt, dataURL } }
function createRoom(roomId) {
if (rooms[roomId]) return rooms[roomId].wsServer;
const wsServer = new ws.WebSocketServer({ noServer: true });
let dataURL = "";
let idCounter = 0;
const room = {
wsServer,
timeout: null,
createdAt: Date.now(),
dataURL
};
function startCleanupTimeout() {
room.timeout = setTimeout(() => {
if (wsServer.clients.size === 0) {
wsServer.close();
delete rooms[roomId];
console.log(`[ROOM ${roomId}] Cleaned up`);
}
}, 5 * 60 * 1000); // 5 mins
}
wsServer.on("connection", function (socket) {
clearTimeout(room.timeout); // Cancel disposal timer
idCounter++;
socket._sid = idCounter;
socket._isAlive = true;
socket.send(JSON.stringify({ type: "canvasURL", url: room.dataURL }));
// Ghost WebSocket detection
const pingTimeout = setTimeout(() => {
if (!socket._hasResponded) {
console.log(`[ROOM ${roomId}] Ghost WebSocket disconnected`);
socket.terminate();
}
}, 15 * 1000); // Must respond in 15s
socket.on("message", function (msg) {
socket._hasResponded = true;
try {
const json = JSON.parse(msg.toString());
if (json.type === "canvasURL") {
if (typeof json.url === "string" && json.url.length <= MAX_DATAURL_SIZE) {
room.dataURL = json.url;
} else {
console.warn(`[ROOM ${roomId}] DataURL too large or invalid. Ignored.`);
}
} else if (json.type === "actionHistory") {
if (Array.isArray(json.cursor)) {
socket._cursorX = +json.cursor[0] || 0;
socket._cursorY = +json.cursor[1] || 0;
socket._cursorName = String(json.cursor[2]);
}
wsServer.clients.forEach((ws) => {
if (ws !== socket) {
ws.send(JSON.stringify({
type: "applyActionHistory",
history: json.history
}));
}
});
}
} catch (e) {
console.log("WebSocket message error:", e);
}
});
var cursorInterval = setInterval(() => {
var positions = [];
Array.from(wsServer.clients).filter((sock) => sock._sid !== socket._sid).forEach((sock) => {
if (sock._cursorName) {
positions.push([sock._cursorX,sock._cursorY,sock._cursorName]);
}
});
socket.send(JSON.stringify({
type: "cursors",
positions
}));
},1000/30);
socket.on("close", function () {
clearInterval(cursorInterval);
idCounter--;
if (wsServer.clients.size === 0) {
startCleanupTimeout();
}
});
});
// Ask one client for updates regularly
wsServer._serverInterval = setInterval(() => {
const [first] = wsServer.clients;
if (first) {
try {
first.send(JSON.stringify({ type: "updateCanvasURL" }));
} catch (e) {}
}
}, 100); // 10 FPS
rooms[roomId] = room;
return wsServer;
}
// === WebSocket Upgrade Routing ===
server.on("upgrade", function upgrade(request, socket, head) {
var url = decodeURIComponent(request.url);
var urlsplit = url.split("/");
var roomId = urlsplit[1];
if (!rooms[roomId]) {
createRoom(roomId);
}
const wsServer = rooms[roomId].wsServer;
wsServer.handleUpgrade(request, socket, head, function done(ws) {
wsServer.emit("connection", ws, request);
});
});
server.listen(8080, () => {
console.log("Server listening on http://localhost:8080");
});