Add unambiguous section in the PGN + some fixes + code formatting and fix typos
[vchess.git] / server / sockets.js
1 const url = require('url');
2
3 // Node version in Ubuntu 16.04 does not know about URL class
4 // NOTE: url is already transformed, without ?xxx=yyy... parts
5 function getJsonFromUrl(url) {
6 const query = url.substr(2); //starts with "/?"
7 let result = {};
8 query.split("&").forEach((part) => {
9 const item = part.split("=");
10 result[item[0]] = decodeURIComponent(item[1]);
11 });
12 return result;
13 }
14
15 // Helper to safe-send some message through a (web-)socket:
16 function send(socket, message) {
17 if (!!socket && socket.readyState == 1)
18 socket.send(JSON.stringify(message));
19 }
20
21 module.exports = function(wss) {
22 // Associative array page --> sid --> tmpId --> socket
23 // "page" is either "/" for hall or "/game/some_gid" for Game,
24 // or "/mygames" for Mygames page (simpler: no 'people' array).
25 // tmpId is required if a same user (browser) has different tabs
26 let clients = {};
27 // NOTE: only purpose of sidToPages = know when to delete keys in idToSid
28 let sidToPages = {};
29 let idToSid = {};
30 wss.on("connection", (socket, req) => {
31 const query = getJsonFromUrl(req.url);
32 const sid = query["sid"];
33 const id = query["id"];
34 const tmpId = query["tmpId"];
35 const page = query["page"];
36 const notifyRoom = (page, code, obj={}, except) => {
37 if (!clients[page]) return;
38 except = except || [];
39 Object.keys(clients[page]).forEach(k => {
40 if (except.includes(k)) return;
41 Object.keys(clients[page][k]).forEach(x => {
42 if (k == sid && x == tmpId) return;
43 send(
44 clients[page][k][x].socket,
45 Object.assign({ code: code, from: [sid, tmpId] }, obj)
46 );
47 });
48 });
49 };
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];
54 if (Object.keys(clients[page][sid]).length == 0) {
55 delete clients[page][sid];
56 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
57 sidToPages[sid].splice(pgIndex, 1);
58 if (Object.keys(clients[page]).length == 0)
59 delete clients[page];
60 // Am I totally offline?
61 if (sidToPages[sid].length == 0) {
62 delete sidToPages[sid];
63 delete idToSid[id];
64 }
65 }
66 };
67
68 const doDisconnect = () => {
69 deleteConnexion();
70 // Nothing to notify when disconnecting from MyGames page:
71 if (page != "/mygames") {
72 notifyRoom(page, "disconnect");
73 if (page.indexOf("/game/") >= 0)
74 notifyRoom("/", "gdisconnect", { page: page });
75 }
76 };
77 const messageListener = (objtxt) => {
78 let obj = JSON.parse(objtxt);
79 switch (obj.code) {
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.
83 case "connect": {
84 notifyRoom(page, "connect");
85 if (page.indexOf("/game/") >= 0)
86 notifyRoom("/", "gconnect", { page: page });
87 break;
88 }
89 case "disconnect":
90 // When page changes:
91 doDisconnect();
92 break;
93 case "killme": {
94 // Self multi-connect: manual removal + disconnect
95 const doKill = (pg) => {
96 Object.keys(clients[pg][obj.sid]).forEach(x => {
97 send(clients[pg][obj.sid][x].socket, { code: "killed" });
98 });
99 delete clients[pg][obj.sid];
100 };
101 const disconnectFromOtherConnexion = (pg,code,o={}) => {
102 Object.keys(clients[pg]).forEach(k => {
103 if (k != obj.sid) {
104 Object.keys(clients[pg][k]).forEach(x => {
105 send(
106 clients[pg][k][x].socket,
107 Object.assign({ code: code, from: obj.sid }, o)
108 );
109 });
110 }
111 });
112 };
113 Object.keys(clients).forEach(pg => {
114 if (clients[pg][obj.sid]) {
115 doKill(pg);
116 disconnectFromOtherConnexion(pg, "disconnect");
117 if (pg.indexOf("/game/") >= 0 && clients["/"])
118 disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
119 }
120 });
121 break;
122 }
123 case "pollclients": {
124 // From Game
125 let sockIds = {};
126 Object.keys(clients[page]).forEach(k => {
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)
131 sockIds[k][x] = { focus: clients[page][k][x].focus };
132 });
133 });
134 send(socket, { code: "pollclients", sockIds: sockIds });
135 break;
136 }
137 case "pollclientsandgamers": {
138 // From Hall
139 let sockIds = {};
140 Object.keys(clients["/"]).forEach(k => {
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) {
145 sockIds[k][x] = {
146 page: "/",
147 focus: clients[page][k][x].focus
148 };
149 }
150 });
151 });
152 // NOTE: a "gamer" could also just be an observer
153 Object.keys(clients).forEach(p => {
154 if (p.indexOf("/game/") >= 0) {
155 Object.keys(clients[p]).forEach(k => {
156 if (!sockIds[k]) sockIds[k] = {};
157 Object.keys(clients[p][k]).forEach(x => {
158 if (k != sid || x != tmpId) {
159 sockIds[k][x] = {
160 page: p,
161 focus: clients[p][k][x].focus
162 };
163 }
164 });
165 });
166 }
167 });
168 send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
169 break;
170 }
171
172 // Asking something: from is fully identified,
173 // but the requested resource can be from any tmpId (except current!)
174 case "askidentity":
175 case "asklastate":
176 case "askchallenges":
177 case "askgame": {
178 const pg = obj.page || page; //required for askidentity and askgame
179 if (!!clients[pg] && !!clients[pg][obj.target]) {
180 let tmpIds = Object.keys(clients[pg][obj.target]);
181 if (obj.target == sid) {
182 // Targetting myself
183 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
184 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
185 }
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 );
212 } else {
213 // I'm the only person who have the game for the moment:
214 send(socket, { code: "fullgame", data: { empty: true } });
215 }
216 }
217 break;
218 }
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)
225 send(
226 clients[page][obj.target][x].socket,
227 { code: obj.code, data: obj.data }
228 );
229 });
230 break;
231
232 // Notify all room: mostly game events
233 case "newchat":
234 case "newchallenge":
235 case "deletechallenge_s":
236 case "newgame":
237 case "resign":
238 case "abort":
239 case "drawoffer":
240 case "rematchoffer":
241 case "draw":
242 // "newgame" message can provide a page (corr Game --> Hall)
243 notifyRoom(
244 obj.page || page, obj.code, {data: obj.data}, obj.excluded);
245 break;
246
247 case "rnewgame":
248 // A rematch game started:
249 notifyRoom(page, "newgame", {data: obj.data});
250 // Explicitely notify Hall if gametype == corr.
251 // Live games will be polled from Hall after gconnect event.
252 if (obj.data.cadence.indexOf('d') >= 0)
253 notifyRoom("/", "newgame", {data: obj.data});
254 break;
255
256 case "newmove": {
257 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
258 // Special case re-send newmove only to opponent:
259 if (!!obj.target && !!clients[page][obj.target]) {
260 Object.keys(clients[page][obj.target]).forEach(x => {
261 send(
262 clients[page][obj.target][x].socket,
263 Object.assign({ code: "newmove" }, dataWithFrom)
264 );
265 });
266 } else {
267 // NOTE: data.from is useful only to opponent
268 notifyRoom(page, "newmove", dataWithFrom);
269 }
270 break;
271 }
272 case "gotmove":
273 if (
274 !!clients[page][obj.target[0]] &&
275 !!clients[page][obj.target[0]][obj.target[1]]
276 ) {
277 send(
278 clients[page][obj.target[0]][obj.target[1]].socket,
279 { code: "gotmove" }
280 );
281 }
282 break;
283
284 case "result":
285 // Special case: notify all, 'transroom': Game --> Hall
286 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
287 break;
288
289 case "mabort": {
290 const gamePg = "/game/" + obj.gid;
291 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
292 Object.keys(clients[gamePg][obj.target]).forEach(x => {
293 send(
294 clients[gamePg][obj.target][x].socket,
295 { code: "abort" }
296 );
297 });
298 }
299 break;
300 }
301
302 case "notifyscore":
303 case "notifyturn":
304 case "notifynewgame":
305 if (!!clients["/mygames"]) {
306 obj.targets.forEach(t => {
307 const k = t.sid || idToSid[t.id];
308 if (!!clients["/mygames"][k]) {
309 Object.keys(clients["/mygames"][k]).forEach(x => {
310 send(
311 clients["/mygames"][k][x].socket,
312 { code: obj.code, data: obj.data }
313 );
314 });
315 }
316 });
317 }
318 break;
319
320 case "getfocus":
321 case "losefocus":
322 clients[page][sid][tmpId].focus = (obj.code == "getfocus");
323 if (page == "/") notifyRoom("/", obj.code, { page: "/" }, [sid]);
324 else {
325 // Notify game room + Hall:
326 notifyRoom(page, obj.code, {}, [sid]);
327 notifyRoom("/", obj.code, { page: page }, [sid]);
328 }
329 break;
330
331 // Passing, relaying something: from isn't needed,
332 // but target is fully identified (sid + tmpId)
333 case "challenges":
334 case "fullgame":
335 case "game":
336 case "identity":
337 case "lastate":
338 {
339 const pg = obj.target[2] || page; //required for identity and game
340 // NOTE: if in game we ask identity to opponent still in Hall, but
341 // leaving Hall, clients[pg] or clients[pg][target] could be undef.
342 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
343 send(
344 clients[pg][obj.target[0]][obj.target[1]].socket,
345 { code:obj.code, data:obj.data }
346 );
347 }
348 break;
349 }
350 }
351 };
352 const closeListener = () => {
353 // For browser or tab closing (including page reload):
354 doDisconnect();
355 };
356 // Update clients object: add new connexion
357 const newElt = { socket: socket, focus: true };
358 if (!clients[page])
359 clients[page] = { [sid]: {[tmpId]: newElt } };
360 else if (!clients[page][sid])
361 clients[page][sid] = { [tmpId]: newElt };
362 else
363 clients[page][sid][tmpId] = newElt;
364 // Also update helper correspondances
365 if (!idToSid[id]) idToSid[id] = sid;
366 if (!sidToPages[sid]) sidToPages[sid] = [];
367 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
368 if (pgIndex === -1) sidToPages[sid].push(page);
369 socket.on("message", messageListener);
370 socket.on("close", closeListener);
371 });
372 }