Experimental improved behavior of login/logout/multitabs
[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
98db2082
BA
5function getJsonFromUrl(url)
6{
80ee5d5a
BA
7 const query = url.substr(2); //starts with "/?"
8 let result = {};
9 query.split("&").forEach((part) => {
5bd05dba
BA
10 const item = part.split("=");
11 result[item[0]] = decodeURIComponent(item[1]);
12 });
13 return result;
2807f530
BA
14}
15
1d184b4c 16module.exports = function(wss) {
5bd05dba
BA
17 let clients = {}; //associative array sid --> socket
18 wss.on("connection", (socket, req) => {
19 const query = getJsonFromUrl(req.url);
20 const sid = query["sid"];
c6788ecf 21 const notifyRoom = (page,code,obj={},excluded=[]) => {
92a523d1 22 Object.keys(clients).forEach(k => {
c6788ecf
BA
23 if (k in excluded)
24 return;
92a523d1 25 if (k != sid && clients[k].page == page)
5c8e044f
BA
26 {
27 clients[k].sock.send(JSON.stringify(Object.assign(
c6788ecf 28 {code:code, from:sid}, obj)));
5c8e044f 29 }
92a523d1
BA
30 });
31 };
a3ac374b 32 const messageListener = (objtxt) => {
5bd05dba 33 let obj = JSON.parse(objtxt);
5a3da968 34 if (!!obj.target && !clients[obj.target])
b4d619d1 35 return; //receiver not connected, nothing we can do
5bd05dba
BA
36 switch (obj.code)
37 {
a3ac374b
BA
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.
41c80bb6 52 case "connect":
120fe373
BA
53 {
54 const curPage = clients[sid].page;
55 notifyRoom(curPage, "connect"); //Hall or Game
56 if (curPage.indexOf("/game/") >= 0)
ac8f441c 57 notifyRoom("/", "gconnect"); //notify main hall
41c80bb6 58 break;
120fe373 59 }
81d9ce72 60 case "pollclients":
ac8f441c 61 {
f41ce580 62 const curPage = clients[sid].page;
81d9ce72 63 socket.send(JSON.stringify({code:"pollclients",
ac8f441c
BA
64 sockIds: Object.keys(clients).filter(k =>
65 k != sid && clients[k].page == curPage
c6788ecf 66 )}));
92a523d1 67 break;
ac8f441c
BA
68 }
69 case "pollgamers":
ac8f441c
BA
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;
92a523d1 75 case "pagechange":
9335d45b 76 // page change clients[sid].page --> obj.page
a0c41e7e 77 // TODO: some offline rooms don't need to receive disconnect event
c6788ecf 78 notifyRoom(clients[sid].page, "disconnect");
bcaa8c00 79 if (clients[sid].page.indexOf("/game/") >= 0)
ac8f441c 80 notifyRoom("/", "gdisconnect");
92a523d1 81 clients[sid].page = obj.page;
a0c41e7e
BA
82 // No need to notify connection: it's self-sent in .vue file
83 //notifyRoom(obj.page, "connect");
bcaa8c00 84 if (obj.page.indexOf("/game/") >= 0)
ac8f441c 85 notifyRoom("/", "gconnect");
5a3da968
BA
86 break;
87 case "askidentity":
f41ce580
BA
88 clients[obj.target].sock.send(JSON.stringify(
89 {code:"askidentity",from:sid}));
81d9ce72 90 break;
a0c41e7e
BA
91 case "asklastate":
92 clients[obj.target].sock.send(JSON.stringify(
93 {code:"asklastate",from:sid}));
94 break;
dd75774d 95 case "askchallenge":
f41ce580
BA
96 clients[obj.target].sock.send(JSON.stringify(
97 {code:"askchallenge",from:sid}));
81d9ce72 98 break;
cd0d7743 99 case "askgames":
dc284d90 100 {
c6788ecf 101 // Check all clients playing, and send them a "askgame" message
dc284d90
BA
102 let gameSids = {}; //game ID --> [sid1, sid2]
103 const regexpGid = /\/[a-zA-Z0-9]+$/;
c6788ecf
BA
104 Object.keys(clients).forEach(k => {
105 if (k != sid && clients[k].page.indexOf("/game/") >= 0)
106 {
dc284d90
BA
107 const gid = clients[k].page.match(regexpGid)[0];
108 if (!gameSids[gid])
109 gameSids[gid] = [k];
110 else
111 gameSids[gid].push(k);
c6788ecf
BA
112 }
113 });
dc284d90
BA
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(
ab6f48ea 123 {code:"askgame", from: sid}));
dc284d90
BA
124 });
125 break;
126 }
26f3a887
BA
127 case "askgame":
128 clients[obj.target].sock.send(JSON.stringify(
129 {code:"askgame", from:sid}));
130 break;
dc284d90
BA
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}));
5a3da968
BA
138 break;
139 case "identity":
f41ce580
BA
140 clients[obj.target].sock.send(JSON.stringify(
141 {code:"identity",user:obj.user}));
4d64881e 142 break;
5bd05dba 143 case "refusechallenge":
f41ce580
BA
144 clients[obj.target].sock.send(JSON.stringify(
145 {code:"refusechallenge", cid:obj.cid, from:sid}));
5bd05dba 146 break;
98f48579 147 case "deletechallenge":
f41ce580
BA
148 clients[obj.target].sock.send(JSON.stringify(
149 {code:"deletechallenge", cid:obj.cid, from:sid}));
98f48579 150 break;
a6bddfc6 151 case "newgame":
92a523d1 152 clients[obj.target].sock.send(JSON.stringify(
5bd05dba 153 {code:"newgame", gameInfo:obj.gameInfo, cid:obj.cid}));
a6bddfc6 154 break;
42c15a75 155 case "challenge":
92a523d1 156 clients[obj.target].sock.send(JSON.stringify(
42c15a75
BA
157 {code:"challenge", chall:obj.chall, from:sid}));
158 break;
dd75774d 159 case "game":
c6788ecf
BA
160 if (!!obj.target)
161 {
162 clients[obj.target].sock.send(JSON.stringify(
80ee5d5a 163 {code:"game", game:obj.game, from:sid}));
c6788ecf
BA
164 }
165 else
166 {
167 // Notify all room except opponent and me:
80ee5d5a 168 notifyRoom("/", "game", {game:obj.game}, [obj.oppsid]);
c6788ecf 169 }
4d64881e 170 break;
5bd05dba 171 case "newchat":
ac8f441c 172 notifyRoom(clients[sid].page, "newchat", {chat:obj.chat});
5bd05dba 173 break;
5bd05dba 174 // TODO: WebRTC instead in this case (most demanding?)
26f3a887 175 // --> Or else: at least do a "notifyRoom" (also for draw, resign...)
5bd05dba 176 case "newmove":
f41ce580 177 clients[obj.target].sock.send(JSON.stringify(
c6788ecf 178 {code:"newmove", move:obj.move}));
5bd05dba
BA
179 break;
180 case "lastate":
f41ce580
BA
181 clients[obj.target].sock.send(JSON.stringify(
182 {code:"lastate", state:obj.state}));
5bd05dba 183 break;
5bd05dba 184 case "resign":
f41ce580 185 clients[obj.target].sock.send(JSON.stringify(
3837d4f7 186 {code:"resign", side:obj.side}));
5bd05dba 187 break;
b988c726 188 case "abort":
f41ce580 189 clients[obj.target].sock.send(JSON.stringify(
3837d4f7 190 {code:"abort"}));
b988c726 191 break;
2cc10cdb 192 case "drawoffer":
f41ce580
BA
193 clients[obj.target].sock.send(JSON.stringify(
194 {code:"drawoffer"}));
2cc10cdb
BA
195 break;
196 case "draw":
f41ce580 197 clients[obj.target].sock.send(JSON.stringify(
dcd68c41 198 {code:"draw", message:obj.message}));
2cc10cdb 199 break;
5bd05dba 200 }
a3ac374b
BA
201 };
202 const closeListener = () => {
92a523d1 203 const page = clients[sid].page;
5bd05dba 204 delete clients[sid];
92a523d1 205 notifyRoom(page, "disconnect");
bcaa8c00 206 if (page.indexOf("/game/") >= 0)
ac8f441c 207 notifyRoom("/", "gdisconnect"); //notify main hall
a3ac374b
BA
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);
5bd05dba 218 });
1d184b4c 219}