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