Merge branch 'master' of auder.net:vchess
[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 notifyRoom(page, obj.code, {data: obj.data});
187 break;
188
189 case "result":
190 // Special case: notify all, 'transroom': Game --> Hall
191 notifyRoom("/", "result", {gid: obj.gid, score: obj.score});
192 break;
193
194 case "mconnect":
195 // Special case: notify some game rooms that
196 // I'm watching game state from MyGames
197 // TODO: this code is ignored for now
198 obj.gids.forEach(gid => {
199 const pg = "/game/" + gid;
200 Object.keys(clients[pg]).forEach(s => {
201 Object.keys(clients[pg][s]).forEach(x => {
202 send(
203 clients[pg][s][x],
204 {code: "mconnect", data: obj.data}
205 );
206 });
207 });
208 });
209 break;
210 case "mdisconnect":
211 // TODO
212 // Also TODO: pass newgame to MyGames, and gameover (result)
213 break;
214
215 // Passing, relaying something: from isn't needed,
216 // but target is fully identified (sid + tmpId)
217 case "challenge":
218 case "fullgame":
219 case "game":
220 case "identity":
221 case "lastate":
222 {
223 const pg = obj.target[2] || page; //required for identity and game
224 // NOTE: if in game we ask identity to opponent still in Hall,
225 // but leaving Hall, clients[pg] or clients[pg][target] could be ndefined
226 if (clients[pg] && clients[pg][obj.target[0]])
227 send(clients[pg][obj.target[0]][obj.target[1]], {code:obj.code, data:obj.data});
228 break;
229 }
230 }
231 };
232 const closeListener = () => {
233 // For browser or tab closing (including page reload):
234 doDisconnect();
235 };
236 // Update clients object: add new connexion
237 if (!clients[page])
238 clients[page] = {[sid]: {[tmpId]: socket}};
239 else if (!clients[page][sid])
240 clients[page][sid] = {[tmpId]: socket};
241 else
242 clients[page][sid][tmpId] = socket;
243 socket.on("message", messageListener);
244 socket.on("close", closeListener);
245 });
246 }