Teleport2 (no king repositioning) + do not relay some challenges
[vchess.git] / server / sockets.js
1 const Discord = require('discord.js');
2 const { token, channel } = require('./config/discord.json');
3
4 // Node version in Ubuntu 16.04 does not know about URL class
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 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 }
37 wss.on("connection", (socket, req) => {
38 const query = getJsonFromUrl(req.url);
39 const sid = query["sid"];
40 const id = query["id"];
41 const tmpId = query["tmpId"];
42 const page = query["page"];
43 const notifyRoom = (page, code, obj={}, except) => {
44 if (!clients[page]) return;
45 except = except || [];
46 Object.keys(clients[page]).forEach(k => {
47 if (except.includes(k)) return;
48 Object.keys(clients[page][k]).forEach(x => {
49 if (k == sid && x == tmpId) return;
50 send(
51 clients[page][k][x].socket,
52 Object.assign({ code: code, from: [sid, tmpId] }, obj)
53 );
54 });
55 });
56 };
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];
61 if (Object.keys(clients[page][sid]).length == 0) {
62 delete clients[page][sid];
63 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
64 sidToPages[sid].splice(pgIndex, 1);
65 if (Object.keys(clients[page]).length == 0)
66 delete clients[page];
67 // Am I totally offline?
68 if (sidToPages[sid].length == 0) {
69 delete sidToPages[sid];
70 delete idToSid[id];
71 }
72 }
73 };
74
75 const doDisconnect = () => {
76 deleteConnexion();
77 // Nothing to notify when disconnecting from MyGames page:
78 if (page != "/mygames") {
79 notifyRoom(page, "disconnect");
80 if (page.indexOf("/game/") >= 0)
81 notifyRoom("/", "gdisconnect", { page: page });
82 }
83 };
84 const messageListener = (objtxt) => {
85 let obj = JSON.parse(objtxt);
86 switch (obj.code) {
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.
90 case "connect": {
91 notifyRoom(page, "connect");
92 if (page.indexOf("/game/") >= 0)
93 notifyRoom("/", "gconnect", { page: page });
94 break;
95 }
96 case "disconnect":
97 // When page changes:
98 doDisconnect();
99 break;
100 case "pollclients": {
101 // From Game
102 let sockIds = {};
103 Object.keys(clients[page]).forEach(k => {
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)
108 sockIds[k][x] = { focus: clients[page][k][x].focus };
109 });
110 });
111 send(socket, { code: "pollclients", sockIds: sockIds });
112 break;
113 }
114 case "pollclientsandgamers": {
115 // From Hall
116 let sockIds = {};
117 Object.keys(clients["/"]).forEach(k => {
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) {
122 sockIds[k][x] = {
123 page: "/",
124 focus: clients[page][k][x].focus
125 };
126 }
127 });
128 });
129 // NOTE: a "gamer" could also just be an observer
130 Object.keys(clients).forEach(p => {
131 if (p.indexOf("/game/") >= 0) {
132 Object.keys(clients[p]).forEach(k => {
133 if (!sockIds[k]) sockIds[k] = {};
134 Object.keys(clients[p][k]).forEach(x => {
135 if (k != sid || x != tmpId) {
136 sockIds[k][x] = {
137 page: p,
138 focus: clients[p][k][x].focus
139 };
140 }
141 });
142 });
143 }
144 });
145 send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
146 break;
147 }
148
149 // Asking something: from is fully identified,
150 // but the requested resource can be from any tmpId (except current!)
151 case "askidentity":
152 case "asklastate":
153 case "askchallenges":
154 case "askgame": {
155 const pg = obj.page || page; //required for askidentity and askgame
156 if (!!clients[pg] && !!clients[pg][obj.target]) {
157 let tmpIds = Object.keys(clients[pg][obj.target]);
158 if (obj.target == sid) {
159 // Targetting myself
160 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
161 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
162 }
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 );
189 } else {
190 // I'm the only person who have the game for the moment:
191 send(socket, { code: "fullgame", data: { empty: true } });
192 }
193 }
194 break;
195 }
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)
202 send(
203 clients[page][obj.target][x].socket,
204 { code: obj.code, data: obj.data }
205 );
206 });
207 break;
208
209 // Notify all room: mostly game events
210 case "newchat":
211 case "newchallenge":
212 case "deletechallenge_s":
213 case "newgame":
214 case "resign":
215 case "abort":
216 case "drawoffer":
217 case "rematchoffer":
218 case "draw":
219 // "newgame" message can provide a page (corr Game --> Hall)
220 notifyRoom(
221 obj.page || page, obj.code, {data: obj.data}, obj.excluded);
222 if (
223 obj.code == "newchallenge" &&
224 !obj.data.to && //filter out targeted challenges
225 obj.data.cadence.indexOf('d') < 0 //and correspondance games
226 ) {
227 const challMsg = (
228 "New challenge: **" + obj.data.vname + "** " +
229 "[" + obj.data.cadence + "]"
230 );
231 if (!!discordChannel) discordChannel.send(challMsg);
232 else
233 // Log when running locally (dev, debug):
234 console.log(challMsg);
235 }
236 break;
237
238 case "rnewgame":
239 // A rematch game started:
240 notifyRoom(page, "newgame", {data: obj.data});
241 // Explicitely notify Hall if gametype == corr.
242 // Live games will be polled from Hall after gconnect event.
243 if (obj.data.cadence.indexOf('d') >= 0)
244 notifyRoom("/", "newgame", {data: obj.data});
245 break;
246
247 case "newmove": {
248 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
249 // Special case re-send newmove only to opponent:
250 if (!!obj.target && !!clients[page][obj.target]) {
251 Object.keys(clients[page][obj.target]).forEach(x => {
252 send(
253 clients[page][obj.target][x].socket,
254 Object.assign({ code: "newmove" }, dataWithFrom)
255 );
256 });
257 } else {
258 // NOTE: data.from is useful only to opponent
259 notifyRoom(page, "newmove", dataWithFrom);
260 }
261 break;
262 }
263 case "gotmove":
264 if (
265 !!clients[page][obj.target[0]] &&
266 !!clients[page][obj.target[0]][obj.target[1]]
267 ) {
268 send(
269 clients[page][obj.target[0]][obj.target[1]].socket,
270 { code: "gotmove" }
271 );
272 }
273 break;
274
275 case "result":
276 // Special case: notify all, 'transroom': Game --> Hall
277 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
278 break;
279
280 case "mabort": {
281 const gamePg = "/game/" + obj.gid;
282 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
283 Object.keys(clients[gamePg][obj.target]).forEach(x => {
284 send(
285 clients[gamePg][obj.target][x].socket,
286 { code: "abort" }
287 );
288 });
289 }
290 break;
291 }
292
293 case "notifyscore":
294 case "notifyturn":
295 case "notifynewgame":
296 if (!!clients["/mygames"]) {
297 obj.targets.forEach(t => {
298 const k = t.sid || idToSid[t.id];
299 if (!!clients["/mygames"][k]) {
300 Object.keys(clients["/mygames"][k]).forEach(x => {
301 send(
302 clients["/mygames"][k][x].socket,
303 { code: obj.code, data: obj.data }
304 );
305 });
306 }
307 });
308 }
309 break;
310
311 case "getfocus":
312 case "losefocus":
313 if (
314 !!clients[page] &&
315 !!clients[page][sid] &&
316 !!clients[page][sid][tmpId]
317 ) {
318 clients[page][sid][tmpId].focus = (obj.code == "getfocus");
319 }
320 if (page == "/") notifyRoom("/", obj.code, { page: "/" }, [sid]);
321 else {
322 // Notify game room + Hall:
323 notifyRoom(page, obj.code, {}, [sid]);
324 notifyRoom("/", obj.code, { page: page }, [sid]);
325 }
326 break;
327
328 // Passing, relaying something: from isn't needed,
329 // but target is fully identified (sid + tmpId)
330 case "challenges":
331 case "fullgame":
332 case "game":
333 case "identity":
334 case "lastate":
335 {
336 const pg = obj.target[2] || page; //required for identity and game
337 // NOTE: if in game we ask identity to opponent still in Hall, but
338 // leaving Hall, clients[pg] or clients[pg][target] could be undef.
339 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
340 send(
341 clients[pg][obj.target[0]][obj.target[1]].socket,
342 { code:obj.code, data:obj.data }
343 );
344 }
345 break;
346 }
347 }
348 };
349 const closeListener = () => {
350 // For browser or tab closing (including page reload):
351 doDisconnect();
352 };
353 // Update clients object: add new connexion
354 const newElt = { socket: socket, focus: true };
355 if (!clients[page])
356 clients[page] = { [sid]: {[tmpId]: newElt } };
357 else if (!clients[page][sid])
358 clients[page][sid] = { [tmpId]: newElt };
359 else
360 clients[page][sid][tmpId] = newElt;
361 // Also update helper correspondances
362 if (!idToSid[id]) idToSid[id] = sid;
363 if (!sidToPages[sid]) sidToPages[sid] = [];
364 const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
365 if (pgIndex === -1) sidToPages[sid].push(page);
366 socket.on("message", messageListener);
367 socket.on("close", closeListener);
368 });
369 }