Small fix + attempt to improve socket messages reliability...
[vchess.git] / server / sockets.js
CommitLineData
e8ea1e35
BA
1const Discord = require('discord.js');
2const { token, channel } = require('./config/discord.json');
3
2807f530 4// Node version in Ubuntu 16.04 does not know about URL class
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
16d06164
BA
21// https://www.npmjs.com/package/ws - detect lost connections...
22function noop() {}
23function heartbeat() {
24 this.isAlive = true;
25}
26
1d184b4c 27module.exports = function(wss) {
71468011 28 // Associative array page --> sid --> tmpId --> socket
8418f0d7 29 // "page" is either "/" for hall or "/game/some_gid" for Game,
a041d5d8 30 // or "/mygames" for Mygames page (simpler: no 'people' array).
8418f0d7
BA
31 // tmpId is required if a same user (browser) has different tabs
32 let clients = {};
7ebc0408 33 // NOTE: only purpose of sidToPages = know when to delete keys in idToSid
cafe0166
BA
34 let sidToPages = {};
35 let idToSid = {};
e8ea1e35
BA
36 const discordClient = new Discord.Client();
37 let discordChannel = null;
38 if (token.length > 0) {
4ac41c44
BA
39 discordClient.login(token);
40 discordClient.once("ready", () => {
e8ea1e35
BA
41 discordChannel = discordClient.channels.cache.get(channel);
42 });
43 }
5bd05dba 44 wss.on("connection", (socket, req) => {
16d06164
BA
45 socket.isAlive = true;
46 socket.on('pong', heartbeat);
5bd05dba
BA
47 const query = getJsonFromUrl(req.url);
48 const sid = query["sid"];
cafe0166 49 const id = query["id"];
8418f0d7 50 const tmpId = query["tmpId"];
71468011 51 const page = query["page"];
f14572c4 52 const notifyRoom = (page, code, obj={}, except) => {
a041d5d8 53 if (!clients[page]) return;
f14572c4 54 except = except || [];
a041d5d8 55 Object.keys(clients[page]).forEach(k => {
856f995c 56 if (except.includes(k)) return;
a041d5d8 57 Object.keys(clients[page][k]).forEach(x => {
f14572c4 58 if (k == sid && x == tmpId) return;
a041d5d8
BA
59 send(
60 clients[page][k][x].socket,
7ebc0408 61 Object.assign({ code: code, from: [sid, tmpId] }, obj)
1611a25f 62 );
71468011 63 });
92a523d1
BA
64 });
65 };
71468011
BA
66 const deleteConnexion = () => {
67 if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
68 return; //job already done
69 delete clients[page][sid][tmpId];
1611a25f 70 if (Object.keys(clients[page][sid]).length == 0) {
71468011 71 delete clients[page][sid];
cafe0166
BA
72 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
73 sidToPages[sid].splice(pgIndex, 1);
1611a25f 74 if (Object.keys(clients[page]).length == 0)
71468011 75 delete clients[page];
cafe0166
BA
76 // Am I totally offline?
77 if (sidToPages[sid].length == 0) {
78 delete sidToPages[sid];
79 delete idToSid[id];
80 }
71468011
BA
81 }
82 };
1611a25f 83
f5f51daf
BA
84 const doDisconnect = () => {
85 deleteConnexion();
cafe0166 86 // Nothing to notify when disconnecting from MyGames page:
7ebc0408 87 if (page != "/mygames") {
f5f51daf
BA
88 notifyRoom(page, "disconnect");
89 if (page.indexOf("/game/") >= 0)
7ebc0408 90 notifyRoom("/", "gdisconnect", { page: page });
f5f51daf
BA
91 }
92 };
a3ac374b 93 const messageListener = (objtxt) => {
5bd05dba 94 let obj = JSON.parse(objtxt);
1611a25f 95 switch (obj.code) {
a3ac374b
BA
96 // Wait for "connect" message to notify connection to the room,
97 // because if game loading is slow the message listener might
98 // not be ready too early.
1611a25f 99 case "connect": {
71468011
BA
100 notifyRoom(page, "connect");
101 if (page.indexOf("/game/") >= 0)
7ebc0408 102 notifyRoom("/", "gconnect", { page: page });
41c80bb6 103 break;
120fe373 104 }
8418f0d7 105 case "disconnect":
71468011 106 // When page changes:
f5f51daf 107 doDisconnect();
8418f0d7 108 break;
1611a25f 109 case "pollclients": {
7ebc0408
BA
110 // From Game
111 let sockIds = {};
71468011 112 Object.keys(clients[page]).forEach(k => {
0d5335de
BA
113 sockIds[k] = {};
114 Object.keys(clients[page][k]).forEach(x => {
115 // Avoid polling my tmpId: no information to get
116 if (k != sid || x != tmpId)
7ebc0408 117 sockIds[k][x] = { focus: clients[page][k][x].focus };
0d5335de 118 });
8418f0d7 119 });
aae89b49 120 send(socket, { code: "pollclients", sockIds: sockIds });
92a523d1 121 break;
ac8f441c 122 }
1611a25f
BA
123 case "pollclientsandgamers": {
124 // From Hall
7ebc0408 125 let sockIds = {};
71468011 126 Object.keys(clients["/"]).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
BA
131 sockIds[k][x] = {
132 page: "/",
133 focus: clients[page][k][x].focus
134 };
0d5335de
BA
135 }
136 });
71468011
BA
137 });
138 // NOTE: a "gamer" could also just be an observer
139 Object.keys(clients).forEach(p => {
cafe0166 140 if (p.indexOf("/game/") >= 0) {
71468011 141 Object.keys(clients[p]).forEach(k => {
0d5335de
BA
142 if (!sockIds[k]) sockIds[k] = {};
143 Object.keys(clients[p][k]).forEach(x => {
144 if (k != sid || x != tmpId) {
7ebc0408
BA
145 sockIds[k][x] = {
146 page: p,
147 focus: clients[p][k][x].focus
148 };
0d5335de
BA
149 }
150 });
71468011
BA
151 });
152 }
8418f0d7 153 });
aae89b49 154 send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
5a3da968 155 break;
8418f0d7 156 }
71468011
BA
157
158 // Asking something: from is fully identified,
159 // but the requested resource can be from any tmpId (except current!)
5a3da968 160 case "askidentity":
71468011 161 case "asklastate":
28b32b4f 162 case "askchallenges":
f54f4c26 163 case "askgame": {
8b152ada 164 const pg = obj.page || page; //required for askidentity and askgame
f9c36b2d 165 if (!!clients[pg] && !!clients[pg][obj.target]) {
f54f4c26 166 let tmpIds = Object.keys(clients[pg][obj.target]);
1611a25f
BA
167 if (obj.target == sid) {
168 // Targetting myself
910d631b 169 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
1611a25f 170 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
910d631b 171 }
f54f4c26
BA
172 if (tmpIds.length > 0) {
173 const ttmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)];
174 send(
175 clients[pg][obj.target][ttmpId].socket,
176 { code: obj.code, from: [sid,tmpId,page] }
177 );
178 }
179 }
180 break;
181 }
182
183 // Special situation of the previous "case":
184 // Full game can be asked to any observer.
185 case "askfullgame": {
186 if (!!clients[page]) {
187 let sids = Object.keys(clients[page]).filter(k => k != sid);
188 if (sids.length > 0) {
189 // Pick a SID at random in this set, and ask full game:
190 const rid = sids[Math.floor(Math.random() * sids.length)];
191 // ..to a random tmpId:
192 const tmpIds = Object.keys(clients[page][rid]);
193 const rtmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)];
194 send(
195 clients[page][rid][rtmpId].socket,
196 { code: "askfullgame", from: [sid,tmpId] }
197 );
c7550017
BA
198 } else {
199 // I'm the only person who have the game for the moment:
200 send(socket, { code: "fullgame", data: { empty: true } });
f54f4c26 201 }
71468011 202 }
81d9ce72 203 break;
8418f0d7 204 }
71468011
BA
205
206 // Some Hall events: target all tmpId's (except mine),
207 case "refusechallenge":
208 case "startgame":
209 Object.keys(clients[page][obj.target]).forEach(x => {
210 if (obj.target != sid || x != tmpId)
1611a25f 211 send(
a041d5d8 212 clients[page][obj.target][x].socket,
aae89b49 213 { code: obj.code, data: obj.data }
1611a25f 214 );
c6788ecf 215 });
4d64881e 216 break;
71468011
BA
217
218 // Notify all room: mostly game events
5bd05dba 219 case "newchat":
71468011 220 case "newchallenge":
28b32b4f 221 case "deletechallenge_s":
c292ebb2 222 case "newgame":
5bd05dba 223 case "resign":
b988c726 224 case "abort":
2cc10cdb 225 case "drawoffer":
c292ebb2 226 case "rematchoffer":
2cc10cdb 227 case "draw":
7ebc0408 228 // "newgame" message can provide a page (corr Game --> Hall)
4ac41c44
BA
229 if (obj.code == "newchallenge") {
230 // Filter out targeted challenges and correspondance games:
231 if (!obj.data.to && obj.data.cadence.indexOf('d') < 0) {
232 const challMsg = (
233 (obj.data.sender || "@nonymous") + " : " +
234 "**" + obj.data.vname + "** " +
235 "[" + obj.data.cadence + "] "
236 );
237 if (!!discordChannel) discordChannel.send(challMsg);
238 else
239 // Log when running locally (dev, debug):
240 console.log(challMsg);
241 }
242 delete obj.data["sender"];
243 }
2c5d7b20
BA
244 notifyRoom(
245 obj.page || page, obj.code, {data: obj.data}, obj.excluded);
c292ebb2
BA
246 break;
247
248 case "rnewgame":
585d0955 249 // A rematch game started:
f14572c4
BA
250 notifyRoom(page, "newgame", {data: obj.data});
251 // Explicitely notify Hall if gametype == corr.
252 // Live games will be polled from Hall after gconnect event.
253 if (obj.data.cadence.indexOf('d') >= 0)
254 notifyRoom("/", "newgame", {data: obj.data});
e5c1d0fb
BA
255 break;
256
257 case "newmove": {
aae89b49 258 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
f9c36b2d 259 // Special case re-send newmove only to opponent:
e5c1d0fb 260 if (!!obj.target && !!clients[page][obj.target]) {
f9c36b2d
BA
261 Object.keys(clients[page][obj.target]).forEach(x => {
262 send(
a041d5d8 263 clients[page][obj.target][x].socket,
aae89b49 264 Object.assign({ code: "newmove" }, dataWithFrom)
f9c36b2d
BA
265 );
266 });
e5c1d0fb
BA
267 } else {
268 // NOTE: data.from is useful only to opponent
269 notifyRoom(page, "newmove", dataWithFrom);
f9c36b2d 270 }
f9c36b2d 271 break;
e5c1d0fb 272 }
f9c36b2d 273 case "gotmove":
e5c1d0fb
BA
274 if (
275 !!clients[page][obj.target[0]] &&
276 !!clients[page][obj.target[0]][obj.target[1]]
277 ) {
278 send(
a041d5d8 279 clients[page][obj.target[0]][obj.target[1]].socket,
e01e086d 280 { code: "gotmove" }
e5c1d0fb 281 );
f9c36b2d 282 }
71468011
BA
283 break;
284
48ab808f
BA
285 case "result":
286 // Special case: notify all, 'transroom': Game --> Hall
aae89b49 287 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
1611a25f
BA
288 break;
289
aae89b49
BA
290 case "mabort": {
291 const gamePg = "/game/" + obj.gid;
292 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
3b0f26c1 293 Object.keys(clients[gamePg][obj.target]).forEach(x => {
aae89b49 294 send(
a041d5d8 295 clients[gamePg][obj.target][x].socket,
aae89b49
BA
296 { code: "abort" }
297 );
298 });
299 }
300 break;
301 }
48ab808f 302
cafe0166
BA
303 case "notifyscore":
304 case "notifyturn":
305 case "notifynewgame":
306 if (!!clients["/mygames"]) {
307 obj.targets.forEach(t => {
0234201f 308 const k = t.sid || idToSid[t.id];
cafe0166
BA
309 if (!!clients["/mygames"][k]) {
310 Object.keys(clients["/mygames"][k]).forEach(x => {
311 send(
312 clients["/mygames"][k][x].socket,
313 { code: obj.code, data: obj.data }
314 );
315 });
316 }
317 });
318 }
319 break;
320
a041d5d8
BA
321 case "getfocus":
322 case "losefocus":
49dad261
BA
323 if (
324 !!clients[page] &&
325 !!clients[page][sid] &&
326 !!clients[page][sid][tmpId]
327 ) {
328 clients[page][sid][tmpId].focus = (obj.code == "getfocus");
329 }
f14572c4 330 if (page == "/") notifyRoom("/", obj.code, { page: "/" }, [sid]);
a041d5d8
BA
331 else {
332 // Notify game room + Hall:
f14572c4
BA
333 notifyRoom(page, obj.code, {}, [sid]);
334 notifyRoom("/", obj.code, { page: page }, [sid]);
a041d5d8
BA
335 }
336 break;
337
71468011
BA
338 // Passing, relaying something: from isn't needed,
339 // but target is fully identified (sid + tmpId)
28b32b4f 340 case "challenges":
71468011
BA
341 case "fullgame":
342 case "game":
343 case "identity":
344 case "lastate":
8b152ada
BA
345 {
346 const pg = obj.target[2] || page; //required for identity and game
2c5d7b20
BA
347 // NOTE: if in game we ask identity to opponent still in Hall, but
348 // leaving Hall, clients[pg] or clients[pg][target] could be undef.
aae89b49
BA
349 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
350 send(
a041d5d8 351 clients[pg][obj.target[0]][obj.target[1]].socket,
aae89b49
BA
352 { code:obj.code, data:obj.data }
353 );
354 }
2cc10cdb 355 break;
8b152ada 356 }
5bd05dba 357 }
a3ac374b
BA
358 };
359 const closeListener = () => {
092de306 360 // For browser or tab closing (including page reload):
f5f51daf 361 doDisconnect();
a3ac374b 362 };
71468011 363 // Update clients object: add new connexion
a041d5d8 364 const newElt = { socket: socket, focus: true };
71468011 365 if (!clients[page])
a041d5d8 366 clients[page] = { [sid]: {[tmpId]: newElt } };
71468011 367 else if (!clients[page][sid])
a041d5d8 368 clients[page][sid] = { [tmpId]: newElt };
71468011 369 else
a041d5d8 370 clients[page][sid][tmpId] = newElt;
cafe0166
BA
371 // Also update helper correspondances
372 if (!idToSid[id]) idToSid[id] = sid;
373 if (!sidToPages[sid]) sidToPages[sid] = [];
374 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
375 if (pgIndex === -1) sidToPages[sid].push(page);
a3ac374b
BA
376 socket.on("message", messageListener);
377 socket.on("close", closeListener);
5bd05dba 378 });
16d06164
BA
379 const interval = setInterval(
380 () => {
381 wss.clients.forEach(ws => {
382 if (ws.isAlive === false) return ws.terminate();
383 ws.isAlive = false;
384 ws.ping(noop);
385 });
386 },
387 30000
388 );
389 wss.on('close', () => clearInterval(interval));
1d184b4c 390}