Draft rematch (not working yet) + fix Crazyhouse getPromotedFen()
[vchess.git] / server / sockets.js
1 const url = require('url');
2
3 // Node version in Ubuntu 16.04 does not know about URL class
4 // NOTE: url is already transformed, without ?xxx=yyy... parts
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 wss.on("connection", (socket, req) => {
28 const query = getJsonFromUrl(req.url);
29 const sid = query["sid"];
30 const tmpId = query["tmpId"];
31 const page = query["page"];
32 const notifyRoom = (page,code,obj={}) => {
33 if (!clients[page]) return;
34 Object.keys(clients[page]).forEach(k => {
35 Object.keys(clients[page][k]).forEach(x => {
36 if (k == sid && x == tmpId) return;
37 send(
38 clients[page][k][x].socket,
39 Object.assign({ code: code, from: sid }, obj)
40 );
41 });
42 });
43 };
44 // For focus events: no need to target self
45 const notifyAllButMe = (page,code,obj={}) => {
46 if (!clients[page]) return;
47 Object.keys(clients[page]).forEach(k => {
48 if (k == sid) return;
49 Object.keys(clients[page][k]).forEach(x => {
50 send(
51 clients[page][k][x].socket,
52 Object.assign({ code: code, from: sid }, 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 if (Object.keys(clients[page]).length == 0)
64 delete clients[page];
65 }
66 };
67
68 const doDisconnect = () => {
69 deleteConnexion();
70 if (!clients[page] || !clients[page][sid]) {
71 // I effectively disconnected from this page:
72 notifyRoom(page, "disconnect");
73 if (page.indexOf("/game/") >= 0)
74 notifyRoom("/", "gdisconnect", { page:page });
75 }
76 };
77 const messageListener = (objtxt) => {
78 let obj = JSON.parse(objtxt);
79 switch (obj.code) {
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.
83 case "connect": {
84 notifyRoom(page, "connect");
85 if (page.indexOf("/game/") >= 0)
86 notifyRoom("/", "gconnect", { page:page });
87 break;
88 }
89 case "disconnect":
90 // When page changes:
91 doDisconnect();
92 break;
93 case "killme": {
94 // Self multi-connect: manual removal + disconnect
95 const doKill = (pg) => {
96 Object.keys(clients[pg][obj.sid]).forEach(x => {
97 send(clients[pg][obj.sid][x].socket, { code: "killed" });
98 });
99 delete clients[pg][obj.sid];
100 };
101 const disconnectFromOtherConnexion = (pg,code,o={}) => {
102 Object.keys(clients[pg]).forEach(k => {
103 if (k != obj.sid) {
104 Object.keys(clients[pg][k]).forEach(x => {
105 send(
106 clients[pg][k][x].socket,
107 Object.assign({ code: code, from: obj.sid }, o)
108 );
109 });
110 }
111 });
112 };
113 Object.keys(clients).forEach(pg => {
114 if (clients[pg][obj.sid]) {
115 doKill(pg);
116 disconnectFromOtherConnexion(pg, "disconnect");
117 if (pg.indexOf("/game/") >= 0 && clients["/"])
118 disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
119 }
120 });
121 break;
122 }
123 case "pollclients": {
124 // From Hall or Game
125 let sockIds = [];
126 Object.keys(clients[page]).forEach(k => {
127 // Avoid polling myself: no new information to get
128 if (k != sid) sockIds.push(k);
129 });
130 send(socket, { code: "pollclients", sockIds: sockIds });
131 break;
132 }
133 case "pollclientsandgamers": {
134 // From Hall
135 let sockIds = [];
136 Object.keys(clients["/"]).forEach(k => {
137 // Avoid polling myself: no new information to get
138 if (k != sid) sockIds.push({sid:k});
139 });
140 // NOTE: a "gamer" could also just be an observer
141 Object.keys(clients).forEach(p => {
142 if (p != "/") {
143 Object.keys(clients[p]).forEach(k => {
144 // 'page' indicator is needed for gamers
145 if (k != sid) sockIds.push({ sid:k, page:p });
146 });
147 }
148 });
149 send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
150 break;
151 }
152
153 // Asking something: from is fully identified,
154 // but the requested resource can be from any tmpId (except current!)
155 case "askidentity":
156 case "asklastate":
157 case "askchallenge":
158 case "askgame":
159 case "askfullgame": {
160 const pg = obj.page || page; //required for askidentity and askgame
161 // In cas askfullgame to wrong SID for example, would crash:
162 if (!!clients[pg] && !!clients[pg][obj.target]) {
163 const tmpIds = Object.keys(clients[pg][obj.target]);
164 if (obj.target == sid) {
165 // Targetting myself
166 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
167 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
168 }
169 const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
170 send(
171 clients[pg][obj.target][tmpIds[tmpId_idx]].socket,
172 { code: obj.code, from: [sid,tmpId,page] }
173 );
174 }
175 break;
176 }
177
178 // Some Hall events: target all tmpId's (except mine),
179 case "refusechallenge":
180 case "startgame":
181 Object.keys(clients[page][obj.target]).forEach(x => {
182 if (obj.target != sid || x != tmpId)
183 send(
184 clients[page][obj.target][x].socket,
185 { code: obj.code, data: obj.data }
186 );
187 });
188 break;
189
190 // Notify all room: mostly game events
191 case "newchat":
192 case "newchallenge":
193 case "deletechallenge":
194 case "newgame":
195 case "resign":
196 case "abort":
197 case "drawoffer":
198 case "rematchoffer":
199 case "draw":
200 if (!!obj.oppsid)
201 // "newgame" message from Hall: do not target players
202 notifyAllBut(page, "newgame", {data: obj.data}, [sid, obj.oppsid]);
203 else notifyRoom(page, obj.code, {data: obj.data});
204 break;
205
206 case "rnewgame":
207 // A rematch game started: players are already informed
208 notifyAllBut(page, "newgame", {data: obj.data}, [sid, obj.oppsid]);
209 notifyAllBut("/", "newgame", {data: obj.data}, [sid, obj.oppsid]);
210 notifyRoom("/mygames", "newgame", {data: obj.data});
211 break;
212
213 case "newmove": {
214 const dataWithFrom = { from: [sid,tmpId], data: obj.data };
215 // Special case re-send newmove only to opponent:
216 if (!!obj.target && !!clients[page][obj.target]) {
217 Object.keys(clients[page][obj.target]).forEach(x => {
218 send(
219 clients[page][obj.target][x].socket,
220 Object.assign({ code: "newmove" }, dataWithFrom)
221 );
222 });
223 } else {
224 // NOTE: data.from is useful only to opponent
225 notifyRoom(page, "newmove", dataWithFrom);
226 }
227 break;
228 }
229 case "gotmove":
230 if (
231 !!clients[page][obj.target[0]] &&
232 !!clients[page][obj.target[0]][obj.target[1]]
233 ) {
234 send(
235 clients[page][obj.target[0]][obj.target[1]].socket,
236 { code: "gotmove" }
237 );
238 }
239 break;
240
241 case "result":
242 // Special case: notify all, 'transroom': Game --> Hall
243 notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
244 break;
245
246 case "mconnect":
247 // Special case: notify some game rooms that
248 // I'm watching game state from MyGames
249 // TODO: this code is ignored for now
250 obj.gids.forEach(gid => {
251 const pg = "/game/" + gid;
252 Object.keys(clients[pg]).forEach(s => {
253 Object.keys(clients[pg][s]).forEach(x => {
254 send(
255 clients[pg][s][x].socket,
256 { code: "mconnect", from: sid }
257 );
258 });
259 });
260 });
261 break;
262 case "mdisconnect":
263 // TODO
264 // Also TODO: pass newgame to MyGames, and gameover (result)
265 break;
266 case "mabort": {
267 const gamePg = "/game/" + obj.gid;
268 if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
269 Object.keys(clients[gamePg][obj.target]).forEach(x => {
270 send(
271 clients[gamePg][obj.target][x].socket,
272 { code: "abort" }
273 );
274 });
275 }
276 break;
277 }
278
279 case "getfocus":
280 case "losefocus":
281 if (page == "/") notifyAllBut("/", obj.code, { page: "/" }, [sid]);
282 else {
283 // Notify game room + Hall:
284 notifyAllBut(page, obj.code, {}, [sid]);
285 notifyAllBut("/", obj.code, { page: page }, [sid]);
286 }
287 break;
288
289 // Passing, relaying something: from isn't needed,
290 // but target is fully identified (sid + tmpId)
291 case "challenge":
292 case "fullgame":
293 case "game":
294 case "identity":
295 case "lastate":
296 {
297 const pg = obj.target[2] || page; //required for identity and game
298 // NOTE: if in game we ask identity to opponent still in Hall,
299 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
300 if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
301 send(
302 clients[pg][obj.target[0]][obj.target[1]].socket,
303 { code:obj.code, data:obj.data }
304 );
305 }
306 break;
307 }
308 }
309 };
310 const closeListener = () => {
311 // For browser or tab closing (including page reload):
312 doDisconnect();
313 };
314 // Update clients object: add new connexion
315 const newElt = { socket: socket, focus: true };
316 if (!clients[page])
317 clients[page] = { [sid]: {[tmpId]: newElt } };
318 else if (!clients[page][sid])
319 clients[page][sid] = { [tmpId]: newElt };
320 else
321 clients[page][sid][tmpId] = newElt;
322 socket.on("message", messageListener);
323 socket.on("close", closeListener);
324 });
325 }