Fixes
[vchess.git] / server / sockets.js
CommitLineData
a29d9d6b 1const url = require('url');
1d184b4c 2
2807f530 3// Node version in Ubuntu 16.04 does not know about URL class
a0c41e7e 4// NOTE: url is already transformed, without ?xxx=yyy... parts
1611a25f 5function getJsonFromUrl(url) {
80ee5d5a
BA
6 const query = url.substr(2); //starts with "/?"
7 let result = {};
8 query.split("&").forEach((part) => {
5bd05dba
BA
9 const item = part.split("=");
10 result[item[0]] = decodeURIComponent(item[1]);
11 });
12 return result;
2807f530
BA
13}
14
8b152ada 15// Helper to safe-send some message through a (web-)socket:
1611a25f 16function send(socket, message) {
f9c36b2d 17 if (!!socket && socket.readyState == 1)
8b152ada
BA
18 socket.send(JSON.stringify(message));
19}
20
1d184b4c 21module.exports = function(wss) {
71468011 22 // Associative array page --> sid --> tmpId --> socket
8418f0d7 23 // "page" is either "/" for hall or "/game/some_gid" for Game,
a041d5d8 24 // or "/mygames" for Mygames page (simpler: no 'people' array).
8418f0d7
BA
25 // tmpId is required if a same user (browser) has different tabs
26 let clients = {};
cafe0166
BA
27 let sidToPages = {};
28 let idToSid = {};
5bd05dba
BA
29 wss.on("connection", (socket, req) => {
30 const query = getJsonFromUrl(req.url);
31 const sid = query["sid"];
cafe0166 32 const id = query["id"];
8418f0d7 33 const tmpId = query["tmpId"];
71468011
BA
34 const page = query["page"];
35 const notifyRoom = (page,code,obj={}) => {
1611a25f 36 if (!clients[page]) return;
71468011
BA
37 Object.keys(clients[page]).forEach(k => {
38 Object.keys(clients[page][k]).forEach(x => {
1611a25f
BA
39 if (k == sid && x == tmpId) return;
40 send(
a041d5d8
BA
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
856f995c 48 const notifyAllBut = (page,code,obj={},except) => {
a041d5d8
BA
49 if (!clients[page]) return;
50 Object.keys(clients[page]).forEach(k => {
856f995c 51 if (except.includes(k)) return;
a041d5d8
BA
52 Object.keys(clients[page][k]).forEach(x => {
53 send(
54 clients[page][k][x].socket,
aae89b49 55 Object.assign({ code: code, from: sid }, obj)
1611a25f 56 );
71468011 57 });
92a523d1
BA
58 });
59 };
71468011
BA
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];
1611a25f 64 if (Object.keys(clients[page][sid]).length == 0) {
71468011 65 delete clients[page][sid];
cafe0166
BA
66 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
67 sidToPages[sid].splice(pgIndex, 1);
1611a25f 68 if (Object.keys(clients[page]).length == 0)
71468011 69 delete clients[page];
cafe0166
BA
70 // Am I totally offline?
71 if (sidToPages[sid].length == 0) {
72 delete sidToPages[sid];
73 delete idToSid[id];
74 }
71468011
BA
75 }
76 };
1611a25f 77
f5f51daf
BA
78 const doDisconnect = () => {
79 deleteConnexion();
cafe0166
BA
80 // Nothing to notify when disconnecting from MyGames page:
81 if (page != "/mygames" && (!clients[page] || !clients[page][sid])) {
f5f51daf
BA
82 // I effectively disconnected from this page:
83 notifyRoom(page, "disconnect");
84 if (page.indexOf("/game/") >= 0)
aae89b49 85 notifyRoom("/", "gdisconnect", { page:page });
f5f51daf
BA
86 }
87 };
a3ac374b 88 const messageListener = (objtxt) => {
5bd05dba 89 let obj = JSON.parse(objtxt);
1611a25f 90 switch (obj.code) {
a3ac374b
BA
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.
1611a25f 94 case "connect": {
71468011
BA
95 notifyRoom(page, "connect");
96 if (page.indexOf("/game/") >= 0)
aae89b49 97 notifyRoom("/", "gconnect", { page:page });
41c80bb6 98 break;
120fe373 99 }
8418f0d7 100 case "disconnect":
71468011 101 // When page changes:
f5f51daf 102 doDisconnect();
8418f0d7 103 break;
1611a25f 104 case "killme": {
51d87b52
BA
105 // Self multi-connect: manual removal + disconnect
106 const doKill = (pg) => {
107 Object.keys(clients[pg][obj.sid]).forEach(x => {
a041d5d8 108 send(clients[pg][obj.sid][x].socket, { code: "killed" });
51d87b52
BA
109 });
110 delete clients[pg][obj.sid];
111 };
112 const disconnectFromOtherConnexion = (pg,code,o={}) => {
113 Object.keys(clients[pg]).forEach(k => {
1611a25f 114 if (k != obj.sid) {
51d87b52 115 Object.keys(clients[pg][k]).forEach(x => {
1611a25f 116 send(
a041d5d8 117 clients[pg][k][x].socket,
aae89b49 118 Object.assign({ code: code, from: obj.sid }, o)
1611a25f 119 );
51d87b52
BA
120 });
121 }
122 });
123 };
124 Object.keys(clients).forEach(pg => {
1611a25f 125 if (clients[pg][obj.sid]) {
51d87b52
BA
126 doKill(pg);
127 disconnectFromOtherConnexion(pg, "disconnect");
1611a25f 128 if (pg.indexOf("/game/") >= 0 && clients["/"])
aae89b49 129 disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
51d87b52
BA
130 }
131 });
132 break;
133 }
1611a25f
BA
134 case "pollclients": {
135 // From Hall or Game
71468011
BA
136 let sockIds = [];
137 Object.keys(clients[page]).forEach(k => {
51d87b52 138 // Avoid polling myself: no new information to get
1611a25f 139 if (k != sid) sockIds.push(k);
8418f0d7 140 });
aae89b49 141 send(socket, { code: "pollclients", sockIds: sockIds });
92a523d1 142 break;
ac8f441c 143 }
1611a25f
BA
144 case "pollclientsandgamers": {
145 // From Hall
71468011
BA
146 let sockIds = [];
147 Object.keys(clients["/"]).forEach(k => {
51d87b52 148 // Avoid polling myself: no new information to get
1611a25f 149 if (k != sid) sockIds.push({sid:k});
71468011
BA
150 });
151 // NOTE: a "gamer" could also just be an observer
152 Object.keys(clients).forEach(p => {
cafe0166 153 if (p.indexOf("/game/") >= 0) {
71468011 154 Object.keys(clients[p]).forEach(k => {
1611a25f 155 // 'page' indicator is needed for gamers
aae89b49 156 if (k != sid) sockIds.push({ sid:k, page:p });
71468011
BA
157 });
158 }
8418f0d7 159 });
aae89b49 160 send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
5a3da968 161 break;
8418f0d7 162 }
71468011
BA
163
164 // Asking something: from is fully identified,
165 // but the requested resource can be from any tmpId (except current!)
5a3da968 166 case "askidentity":
71468011 167 case "asklastate":
28b32b4f 168 case "askchallenges":
71468011 169 case "askgame":
1611a25f 170 case "askfullgame": {
8b152ada 171 const pg = obj.page || page; //required for askidentity and askgame
910d631b 172 // In cas askfullgame to wrong SID for example, would crash:
f9c36b2d 173 if (!!clients[pg] && !!clients[pg][obj.target]) {
910d631b 174 const tmpIds = Object.keys(clients[pg][obj.target]);
1611a25f
BA
175 if (obj.target == sid) {
176 // Targetting myself
910d631b 177 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
1611a25f 178 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
910d631b
BA
179 }
180 const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
181 send(
a041d5d8 182 clients[pg][obj.target][tmpIds[tmpId_idx]].socket,
aae89b49 183 { code: obj.code, from: [sid,tmpId,page] }
910d631b 184 );
71468011 185 }
81d9ce72 186 break;
8418f0d7 187 }
71468011
BA
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)
1611a25f 194 send(
a041d5d8 195 clients[page][obj.target][x].socket,
aae89b49 196 { code: obj.code, data: obj.data }
1611a25f 197 );
c6788ecf 198 });
4d64881e 199 break;
71468011
BA
200
201 // Notify all room: mostly game events
5bd05dba 202 case "newchat":
71468011 203 case "newchallenge":
28b32b4f 204 case "deletechallenge_s":
c292ebb2 205 case "newgame":
5bd05dba 206 case "resign":
b988c726 207 case "abort":
2cc10cdb 208 case "drawoffer":
c292ebb2 209 case "rematchoffer":
2cc10cdb 210 case "draw":
c292ebb2
BA
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
584f81b9 219 notifyAllBut(page, "newgame", {data: obj.data}, [sid]);
c292ebb2
BA
220 notifyAllBut("/", "newgame", {data: obj.data}, [sid, obj.oppsid]);
221 notifyRoom("/mygames", "newgame", {data: obj.data});
e5c1d0fb
BA
222 break;
223
224 case "newmove": {
aae89b49 225 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
f9c36b2d 226 // Special case re-send newmove only to opponent:
e5c1d0fb 227 if (!!obj.target && !!clients[page][obj.target]) {
f9c36b2d
BA
228 Object.keys(clients[page][obj.target]).forEach(x => {
229 send(
a041d5d8 230 clients[page][obj.target][x].socket,
aae89b49 231 Object.assign({ code: "newmove" }, dataWithFrom)
f9c36b2d
BA
232 );
233 });
e5c1d0fb
BA
234 } else {
235 // NOTE: data.from is useful only to opponent
236 notifyRoom(page, "newmove", dataWithFrom);
f9c36b2d 237 }
f9c36b2d 238 break;
e5c1d0fb 239 }
f9c36b2d 240 case "gotmove":
e5c1d0fb
BA
241 if (
242 !!clients[page][obj.target[0]] &&
243 !!clients[page][obj.target[0]][obj.target[1]]
244 ) {
245 send(
a041d5d8 246 clients[page][obj.target[0]][obj.target[1]].socket,
e01e086d 247 { code: "gotmove" }
e5c1d0fb 248 );
f9c36b2d 249 }
71468011
BA
250 break;
251
48ab808f
BA
252 case "result":
253 // Special case: notify all, 'transroom': Game --> Hall
aae89b49 254 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
1611a25f
BA
255 break;
256
aae89b49
BA
257 case "mabort": {
258 const gamePg = "/game/" + obj.gid;
259 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
3b0f26c1 260 Object.keys(clients[gamePg][obj.target]).forEach(x => {
aae89b49 261 send(
a041d5d8 262 clients[gamePg][obj.target][x].socket,
aae89b49
BA
263 { code: "abort" }
264 );
265 });
266 }
267 break;
268 }
48ab808f 269
cafe0166
BA
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
a041d5d8
BA
288 case "getfocus":
289 case "losefocus":
c292ebb2 290 if (page == "/") notifyAllBut("/", obj.code, { page: "/" }, [sid]);
a041d5d8
BA
291 else {
292 // Notify game room + Hall:
c292ebb2
BA
293 notifyAllBut(page, obj.code, {}, [sid]);
294 notifyAllBut("/", obj.code, { page: page }, [sid]);
a041d5d8
BA
295 }
296 break;
297
71468011
BA
298 // Passing, relaying something: from isn't needed,
299 // but target is fully identified (sid + tmpId)
28b32b4f 300 case "challenges":
71468011
BA
301 case "fullgame":
302 case "game":
303 case "identity":
304 case "lastate":
8b152ada
BA
305 {
306 const pg = obj.target[2] || page; //required for identity and game
8477e53d 307 // NOTE: if in game we ask identity to opponent still in Hall,
f9c36b2d 308 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
aae89b49
BA
309 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
310 send(
a041d5d8 311 clients[pg][obj.target[0]][obj.target[1]].socket,
aae89b49
BA
312 { code:obj.code, data:obj.data }
313 );
314 }
2cc10cdb 315 break;
8b152ada 316 }
5bd05dba 317 }
a3ac374b
BA
318 };
319 const closeListener = () => {
092de306 320 // For browser or tab closing (including page reload):
f5f51daf 321 doDisconnect();
a3ac374b 322 };
71468011 323 // Update clients object: add new connexion
a041d5d8 324 const newElt = { socket: socket, focus: true };
71468011 325 if (!clients[page])
a041d5d8 326 clients[page] = { [sid]: {[tmpId]: newElt } };
71468011 327 else if (!clients[page][sid])
a041d5d8 328 clients[page][sid] = { [tmpId]: newElt };
71468011 329 else
a041d5d8 330 clients[page][sid][tmpId] = newElt;
cafe0166
BA
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);
a3ac374b
BA
336 socket.on("message", messageListener);
337 socket.on("close", closeListener);
5bd05dba 338 });
1d184b4c 339}