Fix rematch process
[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 = {};
5bd05dba
BA
27 wss.on("connection", (socket, req) => {
28 const query = getJsonFromUrl(req.url);
29 const sid = query["sid"];
8418f0d7 30 const tmpId = query["tmpId"];
71468011
BA
31 const page = query["page"];
32 const notifyRoom = (page,code,obj={}) => {
1611a25f 33 if (!clients[page]) return;
71468011
BA
34 Object.keys(clients[page]).forEach(k => {
35 Object.keys(clients[page][k]).forEach(x => {
1611a25f
BA
36 if (k == sid && x == tmpId) return;
37 send(
a041d5d8
BA
38 clients[page][k][x].socket,
39 Object.assign({ code: code, from: sid }, obj)
40 );
41 });
42 });
43 };
44 // For focus events: no need to target self
856f995c 45 const notifyAllBut = (page,code,obj={},except) => {
a041d5d8
BA
46 if (!clients[page]) return;
47 Object.keys(clients[page]).forEach(k => {
856f995c 48 if (except.includes(k)) return;
a041d5d8
BA
49 Object.keys(clients[page][k]).forEach(x => {
50 send(
51 clients[page][k][x].socket,
aae89b49 52 Object.assign({ code: code, from: sid }, obj)
1611a25f 53 );
71468011 54 });
92a523d1
BA
55 });
56 };
71468011
BA
57 const deleteConnexion = () => {
58 if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
59 return; //job already done
60 delete clients[page][sid][tmpId];
1611a25f 61 if (Object.keys(clients[page][sid]).length == 0) {
71468011 62 delete clients[page][sid];
1611a25f 63 if (Object.keys(clients[page]).length == 0)
71468011
BA
64 delete clients[page];
65 }
66 };
1611a25f 67
f5f51daf
BA
68 const doDisconnect = () => {
69 deleteConnexion();
1611a25f 70 if (!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 => {
1611a25f 142 if (p != "/") {
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
BA
156 case "asklastate":
157 case "askchallenge":
158 case "askgame":
1611a25f 159 case "askfullgame": {
8b152ada 160 const pg = obj.page || page; //required for askidentity and askgame
910d631b 161 // In cas askfullgame to wrong SID for example, would crash:
f9c36b2d 162 if (!!clients[pg] && !!clients[pg][obj.target]) {
910d631b 163 const tmpIds = Object.keys(clients[pg][obj.target]);
1611a25f
BA
164 if (obj.target == sid) {
165 // Targetting myself
910d631b 166 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
1611a25f 167 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
910d631b
BA
168 }
169 const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
170 send(
a041d5d8 171 clients[pg][obj.target][tmpIds[tmpId_idx]].socket,
aae89b49 172 { code: obj.code, from: [sid,tmpId,page] }
910d631b 173 );
71468011 174 }
81d9ce72 175 break;
8418f0d7 176 }
71468011
BA
177
178 // Some Hall events: target all tmpId's (except mine),
179 case "refusechallenge":
180 case "startgame":
181 Object.keys(clients[page][obj.target]).forEach(x => {
182 if (obj.target != sid || x != tmpId)
1611a25f 183 send(
a041d5d8 184 clients[page][obj.target][x].socket,
aae89b49 185 { code: obj.code, data: obj.data }
1611a25f 186 );
c6788ecf 187 });
4d64881e 188 break;
71468011
BA
189
190 // Notify all room: mostly game events
5bd05dba 191 case "newchat":
71468011 192 case "newchallenge":
71468011 193 case "deletechallenge":
c292ebb2 194 case "newgame":
5bd05dba 195 case "resign":
b988c726 196 case "abort":
2cc10cdb 197 case "drawoffer":
c292ebb2 198 case "rematchoffer":
2cc10cdb 199 case "draw":
c292ebb2
BA
200 if (!!obj.oppsid)
201 // "newgame" message from Hall: do not target players
202 notifyAllBut(page, "newgame", {data: obj.data}, [sid, obj.oppsid]);
203 else notifyRoom(page, obj.code, {data: obj.data});
204 break;
205
206 case "rnewgame":
207 // A rematch game started: players are already informed
584f81b9 208 notifyAllBut(page, "newgame", {data: obj.data}, [sid]);
c292ebb2
BA
209 notifyAllBut("/", "newgame", {data: obj.data}, [sid, obj.oppsid]);
210 notifyRoom("/mygames", "newgame", {data: obj.data});
e5c1d0fb
BA
211 break;
212
213 case "newmove": {
aae89b49 214 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
f9c36b2d 215 // Special case re-send newmove only to opponent:
e5c1d0fb 216 if (!!obj.target && !!clients[page][obj.target]) {
f9c36b2d
BA
217 Object.keys(clients[page][obj.target]).forEach(x => {
218 send(
a041d5d8 219 clients[page][obj.target][x].socket,
aae89b49 220 Object.assign({ code: "newmove" }, dataWithFrom)
f9c36b2d
BA
221 );
222 });
e5c1d0fb
BA
223 } else {
224 // NOTE: data.from is useful only to opponent
225 notifyRoom(page, "newmove", dataWithFrom);
f9c36b2d 226 }
f9c36b2d 227 break;
e5c1d0fb 228 }
f9c36b2d 229 case "gotmove":
e5c1d0fb
BA
230 if (
231 !!clients[page][obj.target[0]] &&
232 !!clients[page][obj.target[0]][obj.target[1]]
233 ) {
234 send(
a041d5d8 235 clients[page][obj.target[0]][obj.target[1]].socket,
e01e086d 236 { code: "gotmove" }
e5c1d0fb 237 );
f9c36b2d 238 }
71468011
BA
239 break;
240
48ab808f
BA
241 case "result":
242 // Special case: notify all, 'transroom': Game --> Hall
aae89b49 243 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
1611a25f
BA
244 break;
245
246 case "mconnect":
247 // Special case: notify some game rooms that
248 // I'm watching game state from MyGames
249 // TODO: this code is ignored for now
250 obj.gids.forEach(gid => {
251 const pg = "/game/" + gid;
252 Object.keys(clients[pg]).forEach(s => {
253 Object.keys(clients[pg][s]).forEach(x => {
254 send(
a041d5d8 255 clients[pg][s][x].socket,
e01e086d 256 { code: "mconnect", from: sid }
1611a25f
BA
257 );
258 });
259 });
260 });
261 break;
262 case "mdisconnect":
263 // TODO
264 // Also TODO: pass newgame to MyGames, and gameover (result)
48ab808f 265 break;
aae89b49
BA
266 case "mabort": {
267 const gamePg = "/game/" + obj.gid;
268 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
3b0f26c1 269 Object.keys(clients[gamePg][obj.target]).forEach(x => {
aae89b49 270 send(
a041d5d8 271 clients[gamePg][obj.target][x].socket,
aae89b49
BA
272 { code: "abort" }
273 );
274 });
275 }
276 break;
277 }
48ab808f 278
a041d5d8
BA
279 case "getfocus":
280 case "losefocus":
c292ebb2 281 if (page == "/") notifyAllBut("/", obj.code, { page: "/" }, [sid]);
a041d5d8
BA
282 else {
283 // Notify game room + Hall:
c292ebb2
BA
284 notifyAllBut(page, obj.code, {}, [sid]);
285 notifyAllBut("/", obj.code, { page: page }, [sid]);
a041d5d8
BA
286 }
287 break;
288
71468011
BA
289 // Passing, relaying something: from isn't needed,
290 // but target is fully identified (sid + tmpId)
291 case "challenge":
292 case "fullgame":
293 case "game":
294 case "identity":
295 case "lastate":
8b152ada
BA
296 {
297 const pg = obj.target[2] || page; //required for identity and game
8477e53d 298 // NOTE: if in game we ask identity to opponent still in Hall,
f9c36b2d 299 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
aae89b49
BA
300 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
301 send(
a041d5d8 302 clients[pg][obj.target[0]][obj.target[1]].socket,
aae89b49
BA
303 { code:obj.code, data:obj.data }
304 );
305 }
2cc10cdb 306 break;
8b152ada 307 }
5bd05dba 308 }
a3ac374b
BA
309 };
310 const closeListener = () => {
092de306 311 // For browser or tab closing (including page reload):
f5f51daf 312 doDisconnect();
a3ac374b 313 };
71468011 314 // Update clients object: add new connexion
a041d5d8 315 const newElt = { socket: socket, focus: true };
71468011 316 if (!clients[page])
a041d5d8 317 clients[page] = { [sid]: {[tmpId]: newElt } };
71468011 318 else if (!clients[page][sid])
a041d5d8 319 clients[page][sid] = { [tmpId]: newElt };
71468011 320 else
a041d5d8 321 clients[page][sid][tmpId] = newElt;
a3ac374b
BA
322 socket.on("message", messageListener);
323 socket.on("close", closeListener);
5bd05dba 324 });
1d184b4c 325}