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