Update TODOs
[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
BA
23 // "page" is either "/" for hall or "/game/some_gid" for Game,
24 // tmpId is required if a same user (browser) has different tabs
25 let clients = {};
5bd05dba
BA
26 wss.on("connection", (socket, req) => {
27 const query = getJsonFromUrl(req.url);
28 const sid = query["sid"];
8418f0d7 29 const tmpId = query["tmpId"];
71468011
BA
30 const page = query["page"];
31 const notifyRoom = (page,code,obj={}) => {
1611a25f 32 if (!clients[page]) return;
71468011
BA
33 Object.keys(clients[page]).forEach(k => {
34 Object.keys(clients[page][k]).forEach(x => {
1611a25f
BA
35 if (k == sid && x == tmpId) return;
36 send(
37 clients[page][k][x],
38 Object.assign({code: code, from: sid}, obj)
39 );
71468011 40 });
92a523d1
BA
41 });
42 };
71468011
BA
43 const deleteConnexion = () => {
44 if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
45 return; //job already done
46 delete clients[page][sid][tmpId];
1611a25f 47 if (Object.keys(clients[page][sid]).length == 0) {
71468011 48 delete clients[page][sid];
1611a25f 49 if (Object.keys(clients[page]).length == 0)
71468011
BA
50 delete clients[page];
51 }
52 };
1611a25f 53
f5f51daf
BA
54 const doDisconnect = () => {
55 deleteConnexion();
1611a25f 56 if (!clients[page] || !clients[page][sid]) {
f5f51daf
BA
57 // I effectively disconnected from this page:
58 notifyRoom(page, "disconnect");
59 if (page.indexOf("/game/") >= 0)
60 notifyRoom("/", "gdisconnect", {page:page});
61 }
62 };
a3ac374b 63 const messageListener = (objtxt) => {
5bd05dba 64 let obj = JSON.parse(objtxt);
1611a25f 65 switch (obj.code) {
a3ac374b
BA
66 // Wait for "connect" message to notify connection to the room,
67 // because if game loading is slow the message listener might
68 // not be ready too early.
1611a25f 69 case "connect": {
71468011
BA
70 notifyRoom(page, "connect");
71 if (page.indexOf("/game/") >= 0)
72 notifyRoom("/", "gconnect", {page:page});
41c80bb6 73 break;
120fe373 74 }
8418f0d7 75 case "disconnect":
71468011 76 // When page changes:
f5f51daf 77 doDisconnect();
8418f0d7 78 break;
1611a25f 79 case "killme": {
51d87b52
BA
80 // Self multi-connect: manual removal + disconnect
81 const doKill = (pg) => {
82 Object.keys(clients[pg][obj.sid]).forEach(x => {
8b152ada 83 send(clients[pg][obj.sid][x], {code: "killed"});
51d87b52
BA
84 });
85 delete clients[pg][obj.sid];
86 };
87 const disconnectFromOtherConnexion = (pg,code,o={}) => {
88 Object.keys(clients[pg]).forEach(k => {
1611a25f 89 if (k != obj.sid) {
51d87b52 90 Object.keys(clients[pg][k]).forEach(x => {
1611a25f
BA
91 send(
92 clients[pg][k][x],
93 Object.assign({code: code, from: obj.sid}, o)
94 );
51d87b52
BA
95 });
96 }
97 });
98 };
99 Object.keys(clients).forEach(pg => {
1611a25f 100 if (clients[pg][obj.sid]) {
51d87b52
BA
101 doKill(pg);
102 disconnectFromOtherConnexion(pg, "disconnect");
1611a25f
BA
103 if (pg.indexOf("/game/") >= 0 && clients["/"])
104 disconnectFromOtherConnexion("/", "gdisconnect", {page: pg});
51d87b52
BA
105 }
106 });
107 break;
108 }
1611a25f
BA
109 case "pollclients": {
110 // From Hall or Game
71468011
BA
111 let sockIds = [];
112 Object.keys(clients[page]).forEach(k => {
51d87b52 113 // Avoid polling myself: no new information to get
1611a25f 114 if (k != sid) sockIds.push(k);
8418f0d7 115 });
1611a25f 116 send(socket, {code: "pollclients", sockIds: sockIds});
92a523d1 117 break;
ac8f441c 118 }
1611a25f
BA
119 case "pollclientsandgamers": {
120 // From Hall
71468011
BA
121 let sockIds = [];
122 Object.keys(clients["/"]).forEach(k => {
51d87b52 123 // Avoid polling myself: no new information to get
1611a25f 124 if (k != sid) sockIds.push({sid:k});
71468011
BA
125 });
126 // NOTE: a "gamer" could also just be an observer
127 Object.keys(clients).forEach(p => {
1611a25f 128 if (p != "/") {
71468011 129 Object.keys(clients[p]).forEach(k => {
1611a25f
BA
130 // 'page' indicator is needed for gamers
131 if (k != sid) sockIds.push({sid:k, page:p});
71468011
BA
132 });
133 }
8418f0d7 134 });
1611a25f 135 send(socket, {code: "pollclientsandgamers", sockIds: sockIds});
5a3da968 136 break;
8418f0d7 137 }
71468011
BA
138
139 // Asking something: from is fully identified,
140 // but the requested resource can be from any tmpId (except current!)
5a3da968 141 case "askidentity":
71468011
BA
142 case "asklastate":
143 case "askchallenge":
144 case "askgame":
1611a25f 145 case "askfullgame": {
8b152ada 146 const pg = obj.page || page; //required for askidentity and askgame
910d631b 147 // In cas askfullgame to wrong SID for example, would crash:
f9c36b2d 148 if (!!clients[pg] && !!clients[pg][obj.target]) {
910d631b 149 const tmpIds = Object.keys(clients[pg][obj.target]);
1611a25f
BA
150 if (obj.target == sid) {
151 // Targetting myself
910d631b 152 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
1611a25f 153 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
910d631b
BA
154 }
155 const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
156 send(
157 clients[pg][obj.target][tmpIds[tmpId_idx]],
1611a25f 158 {code: obj.code, from: [sid,tmpId,page]}
910d631b 159 );
71468011 160 }
81d9ce72 161 break;
8418f0d7 162 }
71468011
BA
163
164 // Some Hall events: target all tmpId's (except mine),
165 case "refusechallenge":
166 case "startgame":
167 Object.keys(clients[page][obj.target]).forEach(x => {
168 if (obj.target != sid || x != tmpId)
1611a25f
BA
169 send(
170 clients[page][obj.target][x],
171 {code: obj.code, data: obj.data}
172 );
c6788ecf 173 });
4d64881e 174 break;
71468011
BA
175
176 // Notify all room: mostly game events
5bd05dba 177 case "newchat":
71468011
BA
178 case "newchallenge":
179 case "newgame":
180 case "deletechallenge":
5bd05dba 181 case "newmove":
5bd05dba 182 case "resign":
b988c726 183 case "abort":
2cc10cdb 184 case "drawoffer":
2cc10cdb 185 case "draw":
f9c36b2d
BA
186 // TODO: if newmove, change "from" field to fully specified sid + tmpId
187 // ==> allow "gotmove" messages to be fully targetted
188 // Special case re-send newmove only to opponent:
189 if (!!obj.target) {
190 Object.keys(clients[page][obj.target]).forEach(x => {
191 send(
192 clients[page][obj.target][x],
193 {code: "newmove", data: obj.data}
194 );
195 });
196 }
197 else notifyRoom(page, obj.code, {data: obj.data});
198 break;
199
200 case "gotmove":
201 // TODO: should fully specify the target and be included in the last case below
202 if (!!clients[page][obj.target]) {
203 Object.keys(clients[page][obj.target]).forEach(x => {
204 send(
205 clients[pg][obj.target][x],
206 {code: "gotmove", data: obj.data}
207 );
208 });
209 }
71468011
BA
210 break;
211
48ab808f
BA
212 case "result":
213 // Special case: notify all, 'transroom': Game --> Hall
1611a25f
BA
214 notifyRoom("/", "result", {gid: obj.gid, score: obj.score});
215 break;
216
217 case "mconnect":
218 // Special case: notify some game rooms that
219 // I'm watching game state from MyGames
220 // TODO: this code is ignored for now
221 obj.gids.forEach(gid => {
222 const pg = "/game/" + gid;
223 Object.keys(clients[pg]).forEach(s => {
224 Object.keys(clients[pg][s]).forEach(x => {
225 send(
226 clients[pg][s][x],
227 {code: "mconnect", data: obj.data}
228 );
229 });
230 });
231 });
232 break;
233 case "mdisconnect":
234 // TODO
235 // Also TODO: pass newgame to MyGames, and gameover (result)
48ab808f
BA
236 break;
237
71468011
BA
238 // Passing, relaying something: from isn't needed,
239 // but target is fully identified (sid + tmpId)
240 case "challenge":
241 case "fullgame":
242 case "game":
243 case "identity":
244 case "lastate":
8b152ada
BA
245 {
246 const pg = obj.target[2] || page; //required for identity and game
8477e53d 247 // NOTE: if in game we ask identity to opponent still in Hall,
f9c36b2d
BA
248 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
249 if (!!clients[pg] && !!clients[pg][obj.target[0]])
8477e53d 250 send(clients[pg][obj.target[0]][obj.target[1]], {code:obj.code, data:obj.data});
2cc10cdb 251 break;
8b152ada 252 }
5bd05dba 253 }
a3ac374b
BA
254 };
255 const closeListener = () => {
092de306 256 // For browser or tab closing (including page reload):
f5f51daf 257 doDisconnect();
a3ac374b 258 };
71468011
BA
259 // Update clients object: add new connexion
260 if (!clients[page])
261 clients[page] = {[sid]: {[tmpId]: socket}};
262 else if (!clients[page][sid])
263 clients[page][sid] = {[tmpId]: socket};
264 else
265 clients[page][sid][tmpId] = socket;
a3ac374b
BA
266 socket.on("message", messageListener);
267 socket.on("close", closeListener);
5bd05dba 268 });
1d184b4c 269}