d96b69676dca3d1c993eca7a9d0bc7c6771cbe5e
[vchess.git] / server / sockets.js
1 const url = require('url');
2
3 // Node version in Ubuntu 16.04 does not know about URL class
4 // NOTE: url is already transformed, without ?xxx=yyy... parts
5 function getJsonFromUrl(url) {
6 const query = url.substr(2); //starts with "/?"
7 let result = {};
8 query.split("&").forEach((part) => {
9 const item = part.split("=");
10 result[item[0]] = decodeURIComponent(item[1]);
11 });
12 return result;
13 }
14
15 // Helper to safe-send some message through a (web-)socket:
16 function send(socket, message) {
17 if (!!socket && socket.readyState == 1)
18 socket.send(JSON.stringify(message));
19 }
20
21 module.exports = function(wss) {
22 // Associative array page --> sid --> tmpId --> socket
23 // "page" is either "/" for hall or "/game/some_gid" for Game,
24 // or "/mygames" for Mygames page (simpler: no 'people' array).
25 // tmpId is required if a same user (browser) has different tabs
26 let clients = {};
27 let sidToPages = {};
28 let idToSid = {};
29 wss.on("connection", (socket, req) => {
30 const query = getJsonFromUrl(req.url);
31 const sid = query["sid"];
32 const id = query["id"];
33 const tmpId = query["tmpId"];
34 const page = query["page"];
35 const notifyRoom = (page,code,obj={}) => {
36 if (!clients[page]) return;
37 Object.keys(clients[page]).forEach(k => {
38 Object.keys(clients[page][k]).forEach(x => {
39 if (k == sid && x == tmpId) return;
40 send(
41 clients[page][k][x].socket,
42 Object.assign({ code: code, from: sid }, obj)
43 );
44 });
45 });
46 };
47 // For focus events: no need to target self
48 const notifyAllBut = (page,code,obj={},except) => {
49 if (!clients[page]) return;
50 Object.keys(clients[page]).forEach(k => {
51 if (except.includes(k)) return;
52 Object.keys(clients[page][k]).forEach(x => {
53 send(
54 clients[page][k][x].socket,
55 Object.assign({ code: code, from: sid }, obj)
56 );
57 });
58 });
59 };
60 const deleteConnexion = () => {
61 if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
62 return; //job already done
63 delete clients[page][sid][tmpId];
64 if (Object.keys(clients[page][sid]).length == 0) {
65 delete clients[page][sid];
66 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
67 sidToPages[sid].splice(pgIndex, 1);
68 if (Object.keys(clients[page]).length == 0)
69 delete clients[page];
70 // Am I totally offline?
71 if (sidToPages[sid].length == 0) {
72 delete sidToPages[sid];
73 delete idToSid[id];
74 }
75 }
76 };
77
78 const doDisconnect = () => {
79 deleteConnexion();
80 // Nothing to notify when disconnecting from MyGames page:
81 if (page != "/mygames" && (!clients[page] || !clients[page][sid])) {
82 // I effectively disconnected from this page:
83 notifyRoom(page, "disconnect");
84 if (page.indexOf("/game/") >= 0)
85 notifyRoom("/", "gdisconnect", { page:page });
86 }
87 };
88 const messageListener = (objtxt) => {
89 let obj = JSON.parse(objtxt);
90 switch (obj.code) {
91 // Wait for "connect" message to notify connection to the room,
92 // because if game loading is slow the message listener might
93 // not be ready too early.
94 case "connect": {
95 notifyRoom(page, "connect");
96 if (page.indexOf("/game/") >= 0)
97 notifyRoom("/", "gconnect", { page:page });
98 break;
99 }
100 case "disconnect":
101 // When page changes:
102 doDisconnect();
103 break;
104 case "killme": {
105 // Self multi-connect: manual removal + disconnect
106 const doKill = (pg) => {
107 Object.keys(clients[pg][obj.sid]).forEach(x => {
108 send(clients[pg][obj.sid][x].socket, { code: "killed" });
109 });
110 delete clients[pg][obj.sid];
111 };
112 const disconnectFromOtherConnexion = (pg,code,o={}) => {
113 Object.keys(clients[pg]).forEach(k => {
114 if (k != obj.sid) {
115 Object.keys(clients[pg][k]).forEach(x => {
116 send(
117 clients[pg][k][x].socket,
118 Object.assign({ code: code, from: obj.sid }, o)
119 );
120 });
121 }
122 });
123 };
124 Object.keys(clients).forEach(pg => {
125 if (clients[pg][obj.sid]) {
126 doKill(pg);
127 disconnectFromOtherConnexion(pg, "disconnect");
128 if (pg.indexOf("/game/") >= 0 && clients["/"])
129 disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
130 }
131 });
132 break;
133 }
134 case "pollclients": {
135 // From Hall or Game
136 let sockIds = [];
137 Object.keys(clients[page]).forEach(k => {
138 // Avoid polling myself: no new information to get
139 if (k != sid) sockIds.push(k);
140 });
141 send(socket, { code: "pollclients", sockIds: sockIds });
142 break;
143 }
144 case "pollclientsandgamers": {
145 // From Hall
146 let sockIds = [];
147 Object.keys(clients["/"]).forEach(k => {
148 // Avoid polling myself: no new information to get
149 if (k != sid) sockIds.push({sid:k});
150 });
151 // NOTE: a "gamer" could also just be an observer
152 Object.keys(clients).forEach(p => {
153 if (p.indexOf("/game/") >= 0) {
154 Object.keys(clients[p]).forEach(k => {
155 // 'page' indicator is needed for gamers
156 if (k != sid) sockIds.push({ sid:k, page:p });
157 });
158 }
159 });
160 send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
161 break;
162 }
163
164 // Asking something: from is fully identified,
165 // but the requested resource can be from any tmpId (except current!)
166 case "askidentity":
167 case "asklastate":
168 case "askchallenge":
169 case "askgame":
170 case "askfullgame": {
171 const pg = obj.page || page; //required for askidentity and askgame
172 // In cas askfullgame to wrong SID for example, would crash:
173 if (!!clients[pg] && !!clients[pg][obj.target]) {
174 const tmpIds = Object.keys(clients[pg][obj.target]);
175 if (obj.target == sid) {
176 // Targetting myself
177 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
178 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
179 }
180 const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
181 send(
182 clients[pg][obj.target][tmpIds[tmpId_idx]].socket,
183 { code: obj.code, from: [sid,tmpId,page] }
184 );
185 }
186 break;
187 }
188
189 // Some Hall events: target all tmpId's (except mine),
190 case "refusechallenge":
191 case "startgame":
192 Object.keys(clients[page][obj.target]).forEach(x => {
193 if (obj.target != sid || x != tmpId)
194 send(
195 clients[page][obj.target][x].socket,
196 { code: obj.code, data: obj.data }
197 );
198 });
199 break;
200
201 // Notify all room: mostly game events
202 case "newchat":
203 case "newchallenge":
204 case "deletechallenge":
205 case "newgame":
206 case "resign":
207 case "abort":
208 case "drawoffer":
209 case "rematchoffer":
210 case "draw":
211 if (!!obj.oppsid)
212 // "newgame" message from Hall: do not target players
213 notifyAllBut(page, "newgame", {data: obj.data}, [sid, obj.oppsid]);
214 else notifyRoom(page, obj.code, {data: obj.data});
215 break;
216
217 case "rnewgame":
218 // A rematch game started: players are already informed
219 notifyAllBut(page, "newgame", {data: obj.data}, [sid]);
220 notifyAllBut("/", "newgame", {data: obj.data}, [sid, obj.oppsid]);
221 notifyRoom("/mygames", "newgame", {data: obj.data});
222 break;
223
224 case "newmove": {
225 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
226 // Special case re-send newmove only to opponent:
227 if (!!obj.target && !!clients[page][obj.target]) {
228 Object.keys(clients[page][obj.target]).forEach(x => {
229 send(
230 clients[page][obj.target][x].socket,
231 Object.assign({ code: "newmove" }, dataWithFrom)
232 );
233 });
234 } else {
235 // NOTE: data.from is useful only to opponent
236 notifyRoom(page, "newmove", dataWithFrom);
237 }
238 break;
239 }
240 case "gotmove":
241 if (
242 !!clients[page][obj.target[0]] &&
243 !!clients[page][obj.target[0]][obj.target[1]]
244 ) {
245 send(
246 clients[page][obj.target[0]][obj.target[1]].socket,
247 { code: "gotmove" }
248 );
249 }
250 break;
251
252 case "result":
253 // Special case: notify all, 'transroom': Game --> Hall
254 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
255 break;
256
257 case "mabort": {
258 const gamePg = "/game/" + obj.gid;
259 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
260 Object.keys(clients[gamePg][obj.target]).forEach(x => {
261 send(
262 clients[gamePg][obj.target][x].socket,
263 { code: "abort" }
264 );
265 });
266 }
267 break;
268 }
269
270 case "notifyscore":
271 case "notifyturn":
272 case "notifynewgame":
273 if (!!clients["/mygames"]) {
274 obj.targets.forEach(t => {
275 const k = t.sid || idToSid[t.uid];
276 if (!!clients["/mygames"][k]) {
277 Object.keys(clients["/mygames"][k]).forEach(x => {
278 send(
279 clients["/mygames"][k][x].socket,
280 { code: obj.code, data: obj.data }
281 );
282 });
283 }
284 });
285 }
286 break;
287
288 case "getfocus":
289 case "losefocus":
290 if (page == "/") notifyAllBut("/", obj.code, { page: "/" }, [sid]);
291 else {
292 // Notify game room + Hall:
293 notifyAllBut(page, obj.code, {}, [sid]);
294 notifyAllBut("/", obj.code, { page: page }, [sid]);
295 }
296 break;
297
298 // Passing, relaying something: from isn't needed,
299 // but target is fully identified (sid + tmpId)
300 case "challenge":
301 case "fullgame":
302 case "game":
303 case "identity":
304 case "lastate":
305 {
306 const pg = obj.target[2] || page; //required for identity and game
307 // NOTE: if in game we ask identity to opponent still in Hall,
308 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
309 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
310 send(
311 clients[pg][obj.target[0]][obj.target[1]].socket,
312 { code:obj.code, data:obj.data }
313 );
314 }
315 break;
316 }
317 }
318 };
319 const closeListener = () => {
320 // For browser or tab closing (including page reload):
321 doDisconnect();
322 };
323 // Update clients object: add new connexion
324 const newElt = { socket: socket, focus: true };
325 if (!clients[page])
326 clients[page] = { [sid]: {[tmpId]: newElt } };
327 else if (!clients[page][sid])
328 clients[page][sid] = { [tmpId]: newElt };
329 else
330 clients[page][sid][tmpId] = newElt;
331 // Also update helper correspondances
332 if (!idToSid[id]) idToSid[id] = sid;
333 if (!sidToPages[sid]) sidToPages[sid] = [];
334 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
335 if (pgIndex === -1) sidToPages[sid].push(page);
336 socket.on("message", messageListener);
337 socket.on("close", closeListener);
338 });
339 }