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