614696f327fe9bd4d7e181177fb22327a45b5239
[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 // tmpId is required if a same user (browser) has different tabs
25 let clients = {};
26 wss.on("connection", (socket, req) => {
27 const query = getJsonFromUrl(req.url);
28 const sid = query["sid"];
29 const tmpId = query["tmpId"];
30 const page = query["page"];
31 const notifyRoom = (page,code,obj={}) => {
32 if (!clients[page]) return;
33 Object.keys(clients[page]).forEach(k => {
34 Object.keys(clients[page][k]).forEach(x => {
35 if (k == sid && x == tmpId) return;
36 send(
37 clients[page][k][x],
38 Object.assign({code: code, from: sid}, obj)
39 );
40 });
41 });
42 };
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];
47 if (Object.keys(clients[page][sid]).length == 0) {
48 delete clients[page][sid];
49 if (Object.keys(clients[page]).length == 0)
50 delete clients[page];
51 }
52 };
53
54 const doDisconnect = () => {
55 deleteConnexion();
56 if (!clients[page] || !clients[page][sid]) {
57 // I effectively disconnected from this page:
58 notifyRoom(page, "disconnect");
59 if (page.indexOf("/game/") >= 0)
60 notifyRoom("/", "gdisconnect", {page:page});
61 }
62 };
63 const messageListener = (objtxt) => {
64 let obj = JSON.parse(objtxt);
65 switch (obj.code) {
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.
69 case "connect": {
70 notifyRoom(page, "connect");
71 if (page.indexOf("/game/") >= 0)
72 notifyRoom("/", "gconnect", {page:page});
73 break;
74 }
75 case "disconnect":
76 // When page changes:
77 doDisconnect();
78 break;
79 case "killme": {
80 // Self multi-connect: manual removal + disconnect
81 const doKill = (pg) => {
82 Object.keys(clients[pg][obj.sid]).forEach(x => {
83 send(clients[pg][obj.sid][x], {code: "killed"});
84 });
85 delete clients[pg][obj.sid];
86 };
87 const disconnectFromOtherConnexion = (pg,code,o={}) => {
88 Object.keys(clients[pg]).forEach(k => {
89 if (k != obj.sid) {
90 Object.keys(clients[pg][k]).forEach(x => {
91 send(
92 clients[pg][k][x],
93 Object.assign({code: code, from: obj.sid}, o)
94 );
95 });
96 }
97 });
98 };
99 Object.keys(clients).forEach(pg => {
100 if (clients[pg][obj.sid]) {
101 doKill(pg);
102 disconnectFromOtherConnexion(pg, "disconnect");
103 if (pg.indexOf("/game/") >= 0 && clients["/"])
104 disconnectFromOtherConnexion("/", "gdisconnect", {page: pg});
105 }
106 });
107 break;
108 }
109 case "pollclients": {
110 // From Hall or Game
111 let sockIds = [];
112 Object.keys(clients[page]).forEach(k => {
113 // Avoid polling myself: no new information to get
114 if (k != sid) sockIds.push(k);
115 });
116 send(socket, {code: "pollclients", sockIds: sockIds});
117 break;
118 }
119 case "pollclientsandgamers": {
120 // From Hall
121 let sockIds = [];
122 Object.keys(clients["/"]).forEach(k => {
123 // Avoid polling myself: no new information to get
124 if (k != sid) sockIds.push({sid:k});
125 });
126 // NOTE: a "gamer" could also just be an observer
127 Object.keys(clients).forEach(p => {
128 if (p != "/") {
129 Object.keys(clients[p]).forEach(k => {
130 // 'page' indicator is needed for gamers
131 if (k != sid) sockIds.push({sid:k, page:p});
132 });
133 }
134 });
135 send(socket, {code: "pollclientsandgamers", sockIds: sockIds});
136 break;
137 }
138
139 // Asking something: from is fully identified,
140 // but the requested resource can be from any tmpId (except current!)
141 case "askidentity":
142 case "asklastate":
143 case "askchallenge":
144 case "askgame":
145 case "askfullgame": {
146 const pg = obj.page || page; //required for askidentity and askgame
147 // In cas askfullgame to wrong SID for example, would crash:
148 if (!!clients[pg] && !!clients[pg][obj.target]) {
149 const tmpIds = Object.keys(clients[pg][obj.target]);
150 if (obj.target == sid) {
151 // Targetting myself
152 const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
153 if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
154 }
155 const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
156 send(
157 clients[pg][obj.target][tmpIds[tmpId_idx]],
158 {code: obj.code, from: [sid,tmpId,page]}
159 );
160 }
161 break;
162 }
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)
169 send(
170 clients[page][obj.target][x],
171 {code: obj.code, data: obj.data}
172 );
173 });
174 break;
175
176 // Notify all room: mostly game events
177 case "newchat":
178 case "newchallenge":
179 case "newgame":
180 case "deletechallenge":
181 case "newmove":
182 case "resign":
183 case "abort":
184 case "drawoffer":
185 case "draw":
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 }
210 break;
211
212 case "result":
213 // Special case: notify all, 'transroom': Game --> Hall
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)
236 break;
237
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":
245 {
246 const pg = obj.target[2] || page; //required for identity and game
247 // NOTE: if in game we ask identity to opponent still in Hall,
248 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
249 if (!!clients[pg] && !!clients[pg][obj.target[0]])
250 send(clients[pg][obj.target[0]][obj.target[1]], {code:obj.code, data:obj.data});
251 break;
252 }
253 }
254 };
255 const closeListener = () => {
256 // For browser or tab closing (including page reload):
257 doDisconnect();
258 };
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;
266 socket.on("message", messageListener);
267 socket.on("close", closeListener);
268 });
269 }