Fix passing games
[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 {
7 const query = url.substr(2); //starts with "/?"
8 let result = {};
9 query.split("&").forEach((part) => {
10 const item = part.split("=");
11 result[item[0]] = decodeURIComponent(item[1]);
12 });
13 return result;
14 }
15
16 module.exports = function(wss) {
17 let clients = {}; //associative array sid --> socket
18 wss.on("connection", (socket, req) => {
19 const query = getJsonFromUrl(req.url);
20 const sid = query["sid"];
21 if (!!clients[sid])
22 {
23 // Dummy messages listener: just send "duplicate" event on anything
24 // ('connect' events for Hall and Game, 'askfullgame' for observers)
25 return socket.on("message", objtxt => {
26 if (["connect","askfullgame"].includes(JSON.parse(objtxt).code))
27 socket.send(JSON.stringify({code:"duplicate"}));
28 });
29 }
30 clients[sid] = {sock: socket, page: query["page"]};
31 const notifyRoom = (page,code,obj={},excluded=[]) => {
32 Object.keys(clients).forEach(k => {
33 if (k in excluded)
34 return;
35 if (k != sid && clients[k].page == page)
36 {
37 clients[k].sock.send(JSON.stringify(Object.assign(
38 {code:code, from:sid}, obj)));
39 }
40 });
41 };
42 // Wait for "connect" message to notify connection to the room,
43 // because if game loading is slow the message listener might
44 // not be ready too early.
45 socket.on("message", objtxt => {
46 let obj = JSON.parse(objtxt);
47 if (!!obj.target && !clients[obj.target])
48 return; //receiver not connected, nothing we can do
49 switch (obj.code)
50 {
51 case "connect":
52 {
53 const curPage = clients[sid].page;
54 notifyRoom(curPage, "connect"); //Hall or Game
55 if (curPage.indexOf("/game/") >= 0)
56 notifyRoom("/", "gconnect"); //notify main hall
57 break;
58 }
59 case "pollclients":
60 {
61 const curPage = clients[sid].page;
62 socket.send(JSON.stringify({code:"pollclients",
63 sockIds: Object.keys(clients).filter(k =>
64 k != sid && clients[k].page == curPage
65 )}));
66 break;
67 }
68 case "pollgamers":
69 socket.send(JSON.stringify({code:"pollgamers",
70 sockIds: Object.keys(clients).filter(k =>
71 k != sid && clients[k].page.indexOf("/game/") >= 0
72 )}));
73 break;
74 case "pagechange":
75 // page change clients[sid].page --> obj.page
76 // TODO: some offline rooms don't need to receive disconnect event
77 notifyRoom(clients[sid].page, "disconnect");
78 if (clients[sid].page.indexOf("/game/") >= 0)
79 notifyRoom("/", "gdisconnect");
80 clients[sid].page = obj.page;
81 // No need to notify connection: it's self-sent in .vue file
82 //notifyRoom(obj.page, "connect");
83 if (obj.page.indexOf("/game/") >= 0)
84 notifyRoom("/", "gconnect");
85 break;
86 case "askidentity":
87 clients[obj.target].sock.send(JSON.stringify(
88 {code:"askidentity",from:sid}));
89 break;
90 case "asklastate":
91 clients[obj.target].sock.send(JSON.stringify(
92 {code:"asklastate",from:sid}));
93 break;
94 case "askchallenge":
95 clients[obj.target].sock.send(JSON.stringify(
96 {code:"askchallenge",from:sid}));
97 break;
98 case "askgames":
99 {
100 // Check all clients playing, and send them a "askgame" message
101 let gameSids = {}; //game ID --> [sid1, sid2]
102 const regexpGid = /\/[a-zA-Z0-9]+$/;
103 Object.keys(clients).forEach(k => {
104 if (k != sid && clients[k].page.indexOf("/game/") >= 0)
105 {
106 const gid = clients[k].page.match(regexpGid)[0];
107 if (!gameSids[gid])
108 gameSids[gid] = [k];
109 else
110 gameSids[gid].push(k);
111 }
112 });
113 // Request only one client out of 2 (TODO: this is a bit heavy)
114 // Alt: ask game to all, and filter later?
115 Object.keys(gameSids).forEach(gid => {
116 const L = gameSids[gid].length;
117 const idx = L > 1
118 ? Math.floor(Math.random() * Math.floor(L))
119 : 0;
120 const rid = gameSids[gid][idx];
121 clients[rid].sock.send(JSON.stringify(
122 {code:"askgame", from: sid}));
123 });
124 break;
125 }
126 case "askgame":
127 clients[obj.target].sock.send(JSON.stringify(
128 {code:"askgame", from:sid}));
129 break;
130 case "askfullgame":
131 clients[obj.target].sock.send(JSON.stringify(
132 {code:"askfullgame", from:sid}));
133 break;
134 case "fullgame":
135 clients[obj.target].sock.send(JSON.stringify(
136 {code:"fullgame", game:obj.game}));
137 break;
138 case "identity":
139 clients[obj.target].sock.send(JSON.stringify(
140 {code:"identity",user:obj.user}));
141 break;
142 case "refusechallenge":
143 clients[obj.target].sock.send(JSON.stringify(
144 {code:"refusechallenge", cid:obj.cid, from:sid}));
145 break;
146 case "deletechallenge":
147 clients[obj.target].sock.send(JSON.stringify(
148 {code:"deletechallenge", cid:obj.cid, from:sid}));
149 break;
150 case "newgame":
151 clients[obj.target].sock.send(JSON.stringify(
152 {code:"newgame", gameInfo:obj.gameInfo, cid:obj.cid}));
153 break;
154 case "challenge":
155 clients[obj.target].sock.send(JSON.stringify(
156 {code:"challenge", chall:obj.chall, from:sid}));
157 break;
158 case "game":
159 if (!!obj.target)
160 {
161 clients[obj.target].sock.send(JSON.stringify(
162 {code:"game", game:obj.game, from:sid}));
163 }
164 else
165 {
166 // Notify all room except opponent and me:
167 notifyRoom("/", "game", {game:obj.game}, [obj.oppsid]);
168 }
169 break;
170 case "newchat":
171 notifyRoom(clients[sid].page, "newchat", {chat:obj.chat});
172 break;
173 // TODO: WebRTC instead in this case (most demanding?)
174 // --> Or else: at least do a "notifyRoom" (also for draw, resign...)
175 case "newmove":
176 clients[obj.target].sock.send(JSON.stringify(
177 {code:"newmove", move:obj.move}));
178 break;
179 case "lastate":
180 clients[obj.target].sock.send(JSON.stringify(
181 {code:"lastate", state:obj.state}));
182 break;
183 case "resign":
184 clients[obj.target].sock.send(JSON.stringify(
185 {code:"resign", side:obj.side}));
186 break;
187 case "abort":
188 clients[obj.target].sock.send(JSON.stringify(
189 {code:"abort"}));
190 break;
191 case "drawoffer":
192 clients[obj.target].sock.send(JSON.stringify(
193 {code:"drawoffer"}));
194 break;
195 case "draw":
196 clients[obj.target].sock.send(JSON.stringify(
197 {code:"draw", message:obj.message}));
198 break;
199 }
200 });
201 socket.on("close", () => {
202 const page = clients[sid].page;
203 delete clients[sid];
204 notifyRoom(page, "disconnect");
205 if (page.indexOf("/game/") >= 0)
206 notifyRoom("/", "gdisconnect"); //notify main hall
207 });
208 });
209 }