Fixes for corr games update + incomplete info (do not show board)
[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
BA
23 // "page" is either "/" for hall or "/game/some_gid" for Game,
24 // tmpId is required if a same user (browser) has different tabs
25 let clients = {};
5bd05dba
BA
26 wss.on("connection", (socket, req) => {
27 const query = getJsonFromUrl(req.url);
28 const sid = query["sid"];
8418f0d7 29 const tmpId = query["tmpId"];
71468011
BA
30 const page = query["page"];
31 const notifyRoom = (page,code,obj={}) => {
1611a25f 32 if (!clients[page]) return;
71468011
BA
33 Object.keys(clients[page]).forEach(k => {
34 Object.keys(clients[page][k]).forEach(x => {
1611a25f
BA
35 if (k == sid && x == tmpId) return;
36 send(
37 clients[page][k][x],
aae89b49 38 Object.assign({ code: code, from: sid }, obj)
1611a25f 39 );
71468011 40 });
92a523d1
BA
41 });
42 };
71468011
BA
43 const deleteConnexion = () => {
44 if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
45 return; //job already done
46 delete clients[page][sid][tmpId];
1611a25f 47 if (Object.keys(clients[page][sid]).length == 0) {
71468011 48 delete clients[page][sid];
1611a25f 49 if (Object.keys(clients[page]).length == 0)
71468011
BA
50 delete clients[page];
51 }
52 };
1611a25f 53
f5f51daf
BA
54 const doDisconnect = () => {
55 deleteConnexion();
1611a25f 56 if (!clients[page] || !clients[page][sid]) {
f5f51daf
BA
57 // I effectively disconnected from this page:
58 notifyRoom(page, "disconnect");
59 if (page.indexOf("/game/") >= 0)
aae89b49 60 notifyRoom("/", "gdisconnect", { page:page });
f5f51daf
BA
61 }
62 };
a3ac374b 63 const messageListener = (objtxt) => {
5bd05dba 64 let obj = JSON.parse(objtxt);
1611a25f 65 switch (obj.code) {
a3ac374b
BA
66 // Wait for "connect" message to notify connection to the room,
67 // because if game loading is slow the message listener might
68 // not be ready too early.
1611a25f 69 case "connect": {
71468011
BA
70 notifyRoom(page, "connect");
71 if (page.indexOf("/game/") >= 0)
aae89b49 72 notifyRoom("/", "gconnect", { page:page });
41c80bb6 73 break;
120fe373 74 }
8418f0d7 75 case "disconnect":
71468011 76 // When page changes:
f5f51daf 77 doDisconnect();
8418f0d7 78 break;
1611a25f 79 case "killme": {
51d87b52
BA
80 // Self multi-connect: manual removal + disconnect
81 const doKill = (pg) => {
82 Object.keys(clients[pg][obj.sid]).forEach(x => {
8b152ada 83 send(clients[pg][obj.sid][x], {code: "killed"});
51d87b52
BA
84 });
85 delete clients[pg][obj.sid];
86 };
87 const disconnectFromOtherConnexion = (pg,code,o={}) => {
88 Object.keys(clients[pg]).forEach(k => {
1611a25f 89 if (k != obj.sid) {
51d87b52 90 Object.keys(clients[pg][k]).forEach(x => {
1611a25f
BA
91 send(
92 clients[pg][k][x],
aae89b49 93 Object.assign({ code: code, from: obj.sid }, o)
1611a25f 94 );
51d87b52
BA
95 });
96 }
97 });
98 };
99 Object.keys(clients).forEach(pg => {
1611a25f 100 if (clients[pg][obj.sid]) {
51d87b52
BA
101 doKill(pg);
102 disconnectFromOtherConnexion(pg, "disconnect");
1611a25f 103 if (pg.indexOf("/game/") >= 0 && clients["/"])
aae89b49 104 disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
51d87b52
BA
105 }
106 });
107 break;
108 }
1611a25f
BA
109 case "pollclients": {
110 // From Hall or Game
71468011
BA
111 let sockIds = [];
112 Object.keys(clients[page]).forEach(k => {
51d87b52 113 // Avoid polling myself: no new information to get
1611a25f 114 if (k != sid) sockIds.push(k);
8418f0d7 115 });
aae89b49 116 send(socket, { code: "pollclients", sockIds: sockIds });
92a523d1 117 break;
ac8f441c 118 }
1611a25f
BA
119 case "pollclientsandgamers": {
120 // From Hall
71468011
BA
121 let sockIds = [];
122 Object.keys(clients["/"]).forEach(k => {
51d87b52 123 // Avoid polling myself: no new information to get
1611a25f 124 if (k != sid) sockIds.push({sid:k});
71468011
BA
125 });
126 // NOTE: a "gamer" could also just be an observer
127 Object.keys(clients).forEach(p => {
1611a25f 128 if (p != "/") {
71468011 129 Object.keys(clients[p]).forEach(k => {
1611a25f 130 // 'page' indicator is needed for gamers
aae89b49 131 if (k != sid) sockIds.push({ sid:k, page:p });
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
BA
142 case "asklastate":
143 case "askchallenge":
144 case "askgame":
1611a25f 145 case "askfullgame": {
8b152ada 146 const pg = obj.page || page; //required for askidentity and askgame
910d631b 147 // In cas askfullgame to wrong SID for example, would crash:
f9c36b2d 148 if (!!clients[pg] && !!clients[pg][obj.target]) {
910d631b 149 const tmpIds = Object.keys(clients[pg][obj.target]);
1611a25f
BA
150 if (obj.target == sid) {
151 // Targetting myself
910d631b 152 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
1611a25f 153 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
910d631b
BA
154 }
155 const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
156 send(
157 clients[pg][obj.target][tmpIds[tmpId_idx]],
aae89b49 158 { code: obj.code, from: [sid,tmpId,page] }
910d631b 159 );
71468011 160 }
81d9ce72 161 break;
8418f0d7 162 }
71468011
BA
163
164 // Some Hall events: target all tmpId's (except mine),
165 case "refusechallenge":
166 case "startgame":
167 Object.keys(clients[page][obj.target]).forEach(x => {
168 if (obj.target != sid || x != tmpId)
1611a25f
BA
169 send(
170 clients[page][obj.target][x],
aae89b49 171 { code: obj.code, data: obj.data }
1611a25f 172 );
c6788ecf 173 });
4d64881e 174 break;
71468011
BA
175
176 // Notify all room: mostly game events
5bd05dba 177 case "newchat":
71468011
BA
178 case "newchallenge":
179 case "newgame":
180 case "deletechallenge":
5bd05dba 181 case "resign":
b988c726 182 case "abort":
2cc10cdb 183 case "drawoffer":
2cc10cdb 184 case "draw":
e5c1d0fb
BA
185 notifyRoom(page, obj.code, {data: obj.data});
186 break;
187
188 case "newmove": {
aae89b49 189 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
f9c36b2d 190 // Special case re-send newmove only to opponent:
e5c1d0fb 191 if (!!obj.target && !!clients[page][obj.target]) {
f9c36b2d
BA
192 Object.keys(clients[page][obj.target]).forEach(x => {
193 send(
194 clients[page][obj.target][x],
aae89b49 195 Object.assign({ code: "newmove" }, dataWithFrom)
f9c36b2d
BA
196 );
197 });
e5c1d0fb
BA
198 } else {
199 // NOTE: data.from is useful only to opponent
200 notifyRoom(page, "newmove", dataWithFrom);
f9c36b2d 201 }
f9c36b2d 202 break;
e5c1d0fb 203 }
f9c36b2d 204 case "gotmove":
e5c1d0fb
BA
205 if (
206 !!clients[page][obj.target[0]] &&
207 !!clients[page][obj.target[0]][obj.target[1]]
208 ) {
209 send(
210 clients[page][obj.target[0]][obj.target[1]],
aae89b49 211 { code: "gotmove", data: obj.data }
e5c1d0fb 212 );
f9c36b2d 213 }
71468011
BA
214 break;
215
48ab808f
BA
216 case "result":
217 // Special case: notify all, 'transroom': Game --> Hall
aae89b49 218 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
1611a25f
BA
219 break;
220
221 case "mconnect":
222 // Special case: notify some game rooms that
223 // I'm watching game state from MyGames
224 // TODO: this code is ignored for now
225 obj.gids.forEach(gid => {
226 const pg = "/game/" + gid;
227 Object.keys(clients[pg]).forEach(s => {
228 Object.keys(clients[pg][s]).forEach(x => {
229 send(
230 clients[pg][s][x],
aae89b49 231 { code: "mconnect", data: obj.data }
1611a25f
BA
232 );
233 });
234 });
235 });
236 break;
237 case "mdisconnect":
238 // TODO
239 // Also TODO: pass newgame to MyGames, and gameover (result)
48ab808f 240 break;
aae89b49
BA
241 case "mabort": {
242 const gamePg = "/game/" + obj.gid;
243 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
244 Object.keys(clients[gamePg][target]).forEach(x => {
245 send(
246 clients[gamePg][obj.target][x],
247 { code: "abort" }
248 );
249 });
250 }
251 break;
252 }
48ab808f 253
71468011
BA
254 // Passing, relaying something: from isn't needed,
255 // but target is fully identified (sid + tmpId)
256 case "challenge":
257 case "fullgame":
258 case "game":
259 case "identity":
260 case "lastate":
8b152ada
BA
261 {
262 const pg = obj.target[2] || page; //required for identity and game
8477e53d 263 // NOTE: if in game we ask identity to opponent still in Hall,
f9c36b2d 264 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
aae89b49
BA
265 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
266 send(
267 clients[pg][obj.target[0]][obj.target[1]],
268 { code:obj.code, data:obj.data }
269 );
270 }
2cc10cdb 271 break;
8b152ada 272 }
5bd05dba 273 }
a3ac374b
BA
274 };
275 const closeListener = () => {
092de306 276 // For browser or tab closing (including page reload):
f5f51daf 277 doDisconnect();
a3ac374b 278 };
71468011
BA
279 // Update clients object: add new connexion
280 if (!clients[page])
aae89b49 281 clients[page] = { [sid]: {[tmpId]: socket } };
71468011 282 else if (!clients[page][sid])
aae89b49 283 clients[page][sid] = { [tmpId]: socket };
71468011
BA
284 else
285 clients[page][sid][tmpId] = socket;
a3ac374b
BA
286 socket.on("message", messageListener);
287 socket.on("close", closeListener);
5bd05dba 288 });
1d184b4c 289}