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