TODO: fix draw logic
[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 function getJsonFromUrl(url)
5 {
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 module.exports = function(wss) {
16 let clients = {}; //associative array sid --> socket
17 wss.on("connection", (socket, req) => {
18 const query = getJsonFromUrl(req.url);
19 const sid = query["sid"];
20 if (!!clients[sid])
21 return socket.send(JSON.stringify({code:"duplicate"}));
22 clients[sid] = {sock: socket, page: query["page"]};
23 const notifyRoom = (page,code,obj={},excluded=[]) => {
24 Object.keys(clients).forEach(k => {
25 if (k in excluded)
26 return;
27 if (k != sid && clients[k].page == page)
28 {
29 clients[k].sock.send(JSON.stringify(Object.assign(
30 {code:code, from:sid}, obj)));
31 }
32 });
33 };
34 // Wait for "connect" message to notify connection to the room,
35 // because if game loading is slow the message listener might
36 // not be ready too early.
37 socket.on("message", objtxt => {
38 let obj = JSON.parse(objtxt);
39 if (!!obj.target && !clients[obj.target])
40 return; //receiver not connected, nothing we can do
41 switch (obj.code)
42 {
43 case "connect":
44 notifyRoom(query["page"], "connect"); //Hall or Game
45 if (query["page"].indexOf("/game/") >= 0)
46 notifyRoom("/", "connect"); //notify main hall
47 break;
48 case "pollclients":
49 const curPage = clients[sid].page;
50 socket.send(JSON.stringify({code:"pollclients",
51 sockIds: Object.keys(clients).filter(k => k != sid &&
52 (clients[k].page == curPage ||
53 // Consider that people playing are in Hall too:
54 (curPage == "/" && clients[k].page.indexOf("/game/") >= 0))
55 )}));
56 break;
57 case "pagechange":
58 notifyRoom(clients[sid].page, "disconnect");
59 if (clients[sid].page.indexOf("/game/") >= 0)
60 notifyRoom("/", "disconnect");
61 clients[sid].page = obj.page;
62 notifyRoom(obj.page, "connect");
63 if (obj.page.indexOf("/game/") >= 0)
64 notifyRoom("/", "connect");
65 break;
66 case "askidentity":
67 clients[obj.target].sock.send(JSON.stringify(
68 {code:"askidentity",from:sid}));
69 break;
70 case "askchallenge":
71 clients[obj.target].sock.send(JSON.stringify(
72 {code:"askchallenge",from:sid}));
73 break;
74 case "askgames":
75 {
76 // Check all clients playing, and send them a "askgame" message
77 let gameSids = {}; //game ID --> [sid1, sid2]
78 const regexpGid = /\/[a-zA-Z0-9]+$/;
79 Object.keys(clients).forEach(k => {
80 if (k != sid && clients[k].page.indexOf("/game/") >= 0)
81 {
82 const gid = clients[k].page.match(regexpGid)[0];
83 if (!gameSids[gid])
84 gameSids[gid] = [k];
85 else
86 gameSids[gid].push(k);
87 }
88 });
89 // Request only one client out of 2 (TODO: this is a bit heavy)
90 // Alt: ask game to all, and filter later?
91 Object.keys(gameSids).forEach(gid => {
92 const L = gameSids[gid].length;
93 const idx = L > 1
94 ? Math.floor(Math.random() * Math.floor(L))
95 : 0;
96 const rid = gameSids[gid][idx];
97 clients[rid].sock.send(JSON.stringify(
98 {code:"askgame", from: sid}));
99 });
100 break;
101 }
102 case "askfullgame":
103 clients[obj.target].sock.send(JSON.stringify(
104 {code:"askfullgame", from:sid}));
105 break;
106 case "fullgame":
107 clients[obj.target].sock.send(JSON.stringify(
108 {code:"fullgame", game:obj.game}));
109 break;
110 case "identity":
111 clients[obj.target].sock.send(JSON.stringify(
112 {code:"identity",user:obj.user}));
113 break;
114 case "refusechallenge":
115 clients[obj.target].sock.send(JSON.stringify(
116 {code:"refusechallenge", cid:obj.cid, from:sid}));
117 break;
118 case "deletechallenge":
119 clients[obj.target].sock.send(JSON.stringify(
120 {code:"deletechallenge", cid:obj.cid, from:sid}));
121 break;
122 case "newgame":
123 clients[obj.target].sock.send(JSON.stringify(
124 {code:"newgame", gameInfo:obj.gameInfo, cid:obj.cid}));
125 break;
126 case "challenge":
127 clients[obj.target].sock.send(JSON.stringify(
128 {code:"challenge", chall:obj.chall, from:sid}));
129 break;
130 case "game":
131 if (!!obj.target)
132 {
133 clients[obj.target].sock.send(JSON.stringify(
134 {code:"game", game:obj.game, from:sid}));
135 }
136 else
137 {
138 // Notify all room except opponent and me:
139 notifyRoom("/", "game", {game:obj.game}, [obj.oppsid]);
140 }
141 break;
142 case "newchat":
143 // WARNING: do not use query["page"], because the page may change
144 notifyRoom(clients[sid].page, "newchat",
145 {msg: obj.msg, name: obj.name});
146 break;
147 // TODO: WebRTC instead in this case (most demanding?)
148 case "newmove":
149 clients[obj.target].sock.send(JSON.stringify(
150 {code:"newmove", move:obj.move}));
151 break;
152 case "lastate":
153 clients[obj.target].sock.send(JSON.stringify(
154 {code:"lastate", state:obj.state}));
155 break;
156 case "resign":
157 clients[obj.target].sock.send(JSON.stringify(
158 {code:"resign", side:obj.side}));
159 break;
160 case "abort":
161 clients[obj.target].sock.send(JSON.stringify(
162 {code:"abort"}));
163 break;
164 case "drawoffer":
165 clients[obj.target].sock.send(JSON.stringify(
166 {code:"drawoffer"}));
167 break;
168 case "draw":
169 clients[obj.target].sock.send(JSON.stringify(
170 {code:"draw", message:obj.message}));
171 break;
172 }
173 });
174 socket.on("close", () => {
175 const page = clients[sid].page;
176 delete clients[sid];
177 notifyRoom(page, "disconnect");
178 if (page.indexOf("/game/") >= 0)
179 notifyRoom("/", "disconnect"); //notify main hall
180 });
181 });
182 }