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