Draft Ball variant + some fixes, enhancements and code cleaning
[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 34 const page = query["page"];
f14572c4 35 const notifyRoom = (page, code, obj={}, except) => {
a041d5d8 36 if (!clients[page]) return;
f14572c4 37 except = except || [];
a041d5d8 38 Object.keys(clients[page]).forEach(k => {
856f995c 39 if (except.includes(k)) return;
a041d5d8 40 Object.keys(clients[page][k]).forEach(x => {
f14572c4 41 if (k == sid && x == tmpId) return;
a041d5d8
BA
42 send(
43 clients[page][k][x].socket,
aae89b49 44 Object.assign({ code: code, from: sid }, obj)
1611a25f 45 );
71468011 46 });
92a523d1
BA
47 });
48 };
71468011
BA
49 const deleteConnexion = () => {
50 if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
51 return; //job already done
52 delete clients[page][sid][tmpId];
1611a25f 53 if (Object.keys(clients[page][sid]).length == 0) {
71468011 54 delete clients[page][sid];
cafe0166
BA
55 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
56 sidToPages[sid].splice(pgIndex, 1);
1611a25f 57 if (Object.keys(clients[page]).length == 0)
71468011 58 delete clients[page];
cafe0166
BA
59 // Am I totally offline?
60 if (sidToPages[sid].length == 0) {
61 delete sidToPages[sid];
62 delete idToSid[id];
63 }
71468011
BA
64 }
65 };
1611a25f 66
f5f51daf
BA
67 const doDisconnect = () => {
68 deleteConnexion();
cafe0166
BA
69 // Nothing to notify when disconnecting from MyGames page:
70 if (page != "/mygames" && (!clients[page] || !clients[page][sid])) {
f5f51daf
BA
71 // I effectively disconnected from this page:
72 notifyRoom(page, "disconnect");
73 if (page.indexOf("/game/") >= 0)
aae89b49 74 notifyRoom("/", "gdisconnect", { page:page });
f5f51daf
BA
75 }
76 };
a3ac374b 77 const messageListener = (objtxt) => {
5bd05dba 78 let obj = JSON.parse(objtxt);
1611a25f 79 switch (obj.code) {
a3ac374b
BA
80 // Wait for "connect" message to notify connection to the room,
81 // because if game loading is slow the message listener might
82 // not be ready too early.
1611a25f 83 case "connect": {
71468011
BA
84 notifyRoom(page, "connect");
85 if (page.indexOf("/game/") >= 0)
aae89b49 86 notifyRoom("/", "gconnect", { page:page });
41c80bb6 87 break;
120fe373 88 }
8418f0d7 89 case "disconnect":
71468011 90 // When page changes:
f5f51daf 91 doDisconnect();
8418f0d7 92 break;
1611a25f 93 case "killme": {
51d87b52
BA
94 // Self multi-connect: manual removal + disconnect
95 const doKill = (pg) => {
96 Object.keys(clients[pg][obj.sid]).forEach(x => {
a041d5d8 97 send(clients[pg][obj.sid][x].socket, { code: "killed" });
51d87b52
BA
98 });
99 delete clients[pg][obj.sid];
100 };
101 const disconnectFromOtherConnexion = (pg,code,o={}) => {
102 Object.keys(clients[pg]).forEach(k => {
1611a25f 103 if (k != obj.sid) {
51d87b52 104 Object.keys(clients[pg][k]).forEach(x => {
1611a25f 105 send(
a041d5d8 106 clients[pg][k][x].socket,
aae89b49 107 Object.assign({ code: code, from: obj.sid }, o)
1611a25f 108 );
51d87b52
BA
109 });
110 }
111 });
112 };
113 Object.keys(clients).forEach(pg => {
1611a25f 114 if (clients[pg][obj.sid]) {
51d87b52
BA
115 doKill(pg);
116 disconnectFromOtherConnexion(pg, "disconnect");
1611a25f 117 if (pg.indexOf("/game/") >= 0 && clients["/"])
aae89b49 118 disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
51d87b52
BA
119 }
120 });
121 break;
122 }
1611a25f
BA
123 case "pollclients": {
124 // From Hall or Game
71468011
BA
125 let sockIds = [];
126 Object.keys(clients[page]).forEach(k => {
51d87b52 127 // Avoid polling myself: no new information to get
1611a25f 128 if (k != sid) sockIds.push(k);
8418f0d7 129 });
aae89b49 130 send(socket, { code: "pollclients", sockIds: sockIds });
92a523d1 131 break;
ac8f441c 132 }
1611a25f
BA
133 case "pollclientsandgamers": {
134 // From Hall
71468011
BA
135 let sockIds = [];
136 Object.keys(clients["/"]).forEach(k => {
51d87b52 137 // Avoid polling myself: no new information to get
1611a25f 138 if (k != sid) sockIds.push({sid:k});
71468011
BA
139 });
140 // NOTE: a "gamer" could also just be an observer
141 Object.keys(clients).forEach(p => {
cafe0166 142 if (p.indexOf("/game/") >= 0) {
71468011 143 Object.keys(clients[p]).forEach(k => {
1611a25f 144 // 'page' indicator is needed for gamers
aae89b49 145 if (k != sid) sockIds.push({ sid:k, page:p });
71468011
BA
146 });
147 }
8418f0d7 148 });
aae89b49 149 send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
5a3da968 150 break;
8418f0d7 151 }
71468011
BA
152
153 // Asking something: from is fully identified,
154 // but the requested resource can be from any tmpId (except current!)
5a3da968 155 case "askidentity":
71468011 156 case "asklastate":
28b32b4f 157 case "askchallenges":
f54f4c26 158 case "askgame": {
8b152ada 159 const pg = obj.page || page; //required for askidentity and askgame
f9c36b2d 160 if (!!clients[pg] && !!clients[pg][obj.target]) {
f54f4c26 161 let tmpIds = Object.keys(clients[pg][obj.target]);
1611a25f
BA
162 if (obj.target == sid) {
163 // Targetting myself
910d631b 164 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
1611a25f 165 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
910d631b 166 }
f54f4c26
BA
167 if (tmpIds.length > 0) {
168 const ttmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)];
169 send(
170 clients[pg][obj.target][ttmpId].socket,
171 { code: obj.code, from: [sid,tmpId,page] }
172 );
173 }
174 }
175 break;
176 }
177
178 // Special situation of the previous "case":
179 // Full game can be asked to any observer.
180 case "askfullgame": {
181 if (!!clients[page]) {
182 let sids = Object.keys(clients[page]).filter(k => k != sid);
183 if (sids.length > 0) {
184 // Pick a SID at random in this set, and ask full game:
185 const rid = sids[Math.floor(Math.random() * sids.length)];
186 // ..to a random tmpId:
187 const tmpIds = Object.keys(clients[page][rid]);
188 const rtmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)];
189 send(
190 clients[page][rid][rtmpId].socket,
191 { code: "askfullgame", from: [sid,tmpId] }
192 );
193 }
71468011 194 }
81d9ce72 195 break;
8418f0d7 196 }
71468011
BA
197
198 // Some Hall events: target all tmpId's (except mine),
199 case "refusechallenge":
200 case "startgame":
201 Object.keys(clients[page][obj.target]).forEach(x => {
202 if (obj.target != sid || x != tmpId)
1611a25f 203 send(
a041d5d8 204 clients[page][obj.target][x].socket,
aae89b49 205 { code: obj.code, data: obj.data }
1611a25f 206 );
c6788ecf 207 });
4d64881e 208 break;
71468011
BA
209
210 // Notify all room: mostly game events
5bd05dba 211 case "newchat":
71468011 212 case "newchallenge":
28b32b4f 213 case "deletechallenge_s":
c292ebb2 214 case "newgame":
5bd05dba 215 case "resign":
b988c726 216 case "abort":
2cc10cdb 217 case "drawoffer":
c292ebb2 218 case "rematchoffer":
2cc10cdb 219 case "draw":
f14572c4 220 notifyRoom(page, obj.code, {data: obj.data}, obj.excluded);
c292ebb2
BA
221 break;
222
223 case "rnewgame":
585d0955 224 // A rematch game started:
f14572c4
BA
225 notifyRoom(page, "newgame", {data: obj.data});
226 // Explicitely notify Hall if gametype == corr.
227 // Live games will be polled from Hall after gconnect event.
228 if (obj.data.cadence.indexOf('d') >= 0)
229 notifyRoom("/", "newgame", {data: obj.data});
e5c1d0fb
BA
230 break;
231
232 case "newmove": {
aae89b49 233 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
f9c36b2d 234 // Special case re-send newmove only to opponent:
e5c1d0fb 235 if (!!obj.target && !!clients[page][obj.target]) {
f9c36b2d
BA
236 Object.keys(clients[page][obj.target]).forEach(x => {
237 send(
a041d5d8 238 clients[page][obj.target][x].socket,
aae89b49 239 Object.assign({ code: "newmove" }, dataWithFrom)
f9c36b2d
BA
240 );
241 });
e5c1d0fb
BA
242 } else {
243 // NOTE: data.from is useful only to opponent
244 notifyRoom(page, "newmove", dataWithFrom);
f9c36b2d 245 }
f9c36b2d 246 break;
e5c1d0fb 247 }
f9c36b2d 248 case "gotmove":
e5c1d0fb
BA
249 if (
250 !!clients[page][obj.target[0]] &&
251 !!clients[page][obj.target[0]][obj.target[1]]
252 ) {
253 send(
a041d5d8 254 clients[page][obj.target[0]][obj.target[1]].socket,
e01e086d 255 { code: "gotmove" }
e5c1d0fb 256 );
f9c36b2d 257 }
71468011
BA
258 break;
259
48ab808f
BA
260 case "result":
261 // Special case: notify all, 'transroom': Game --> Hall
aae89b49 262 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
1611a25f
BA
263 break;
264
aae89b49
BA
265 case "mabort": {
266 const gamePg = "/game/" + obj.gid;
267 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
3b0f26c1 268 Object.keys(clients[gamePg][obj.target]).forEach(x => {
aae89b49 269 send(
a041d5d8 270 clients[gamePg][obj.target][x].socket,
aae89b49
BA
271 { code: "abort" }
272 );
273 });
274 }
275 break;
276 }
48ab808f 277
cafe0166
BA
278 case "notifyscore":
279 case "notifyturn":
280 case "notifynewgame":
281 if (!!clients["/mygames"]) {
282 obj.targets.forEach(t => {
0234201f 283 const k = t.sid || idToSid[t.id];
cafe0166
BA
284 if (!!clients["/mygames"][k]) {
285 Object.keys(clients["/mygames"][k]).forEach(x => {
286 send(
287 clients["/mygames"][k][x].socket,
288 { code: obj.code, data: obj.data }
289 );
290 });
291 }
292 });
293 }
294 break;
295
a041d5d8
BA
296 case "getfocus":
297 case "losefocus":
f14572c4 298 if (page == "/") notifyRoom("/", obj.code, { page: "/" }, [sid]);
a041d5d8
BA
299 else {
300 // Notify game room + Hall:
f14572c4
BA
301 notifyRoom(page, obj.code, {}, [sid]);
302 notifyRoom("/", obj.code, { page: page }, [sid]);
a041d5d8
BA
303 }
304 break;
305
71468011
BA
306 // Passing, relaying something: from isn't needed,
307 // but target is fully identified (sid + tmpId)
28b32b4f 308 case "challenges":
71468011
BA
309 case "fullgame":
310 case "game":
311 case "identity":
312 case "lastate":
8b152ada
BA
313 {
314 const pg = obj.target[2] || page; //required for identity and game
8477e53d 315 // NOTE: if in game we ask identity to opponent still in Hall,
f9c36b2d 316 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
aae89b49
BA
317 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
318 send(
a041d5d8 319 clients[pg][obj.target[0]][obj.target[1]].socket,
aae89b49
BA
320 { code:obj.code, data:obj.data }
321 );
322 }
2cc10cdb 323 break;
8b152ada 324 }
5bd05dba 325 }
a3ac374b
BA
326 };
327 const closeListener = () => {
092de306 328 // For browser or tab closing (including page reload):
f5f51daf 329 doDisconnect();
a3ac374b 330 };
71468011 331 // Update clients object: add new connexion
a041d5d8 332 const newElt = { socket: socket, focus: true };
71468011 333 if (!clients[page])
a041d5d8 334 clients[page] = { [sid]: {[tmpId]: newElt } };
71468011 335 else if (!clients[page][sid])
a041d5d8 336 clients[page][sid] = { [tmpId]: newElt };
71468011 337 else
a041d5d8 338 clients[page][sid][tmpId] = newElt;
cafe0166
BA
339 // Also update helper correspondances
340 if (!idToSid[id]) idToSid[id] = sid;
341 if (!sidToPages[sid]) sidToPages[sid] = [];
342 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
343 if (pgIndex === -1) sidToPages[sid].push(page);
a3ac374b
BA
344 socket.on("message", messageListener);
345 socket.on("close", closeListener);
5bd05dba 346 });
1d184b4c 347}