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