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