c3190aa28bb392fd1eaa8b7abbeb85c261f883c3
[vchess.git] / sockets.js
1 //const url = require('url');
2 const Variants = require("./variants");
3
4 function getJsonFromUrl(url) {
5 var query = url.substr(2); //starts with "/?"
6 var result = {};
7 query.split("&").forEach(function(part) {
8 var item = part.split("=");
9 result[item[0]] = decodeURIComponent(item[1]);
10 });
11 return result;
12 }
13
14 module.exports = function(wss) {
15
16 let clients = { "index": {} };
17 let games = {}; //pending games (player sid)
18 for (const v of Variants)
19 clients[v.name] = {};
20
21 // TODO: when relaying to opponent, check readyState, potential setTimeout()? + send opponent (re)disconnect
22 // (resign, newgame, newmove). See https://github.com/websockets/ws/blob/master/lib/websocket.js around line 313
23
24 wss.on("connection", (socket, req) => {
25 //const params = new URL("http://localhost" + req.url).searchParams;
26 var query = getJsonFromUrl(req.url);
27 const sid = query["sid"]; //params.get("sid");
28 const page = query["page"]; //params.get("page");
29 clients[page][sid] = socket;
30 if (page == "index")
31 {
32 // Send counting info
33 const countings = {};
34 for (const v of Variants)
35 countings[v.name] = Object.keys(clients[v.name]).length;
36 socket.send(JSON.stringify({code:"counts",counts:countings}));
37 }
38 else
39 {
40 // Send to every client connected on index an update message for counts
41 Object.keys(clients["index"]).forEach( k => {
42 clients["index"][k].send(JSON.stringify({code:"increase",vname:page}));
43 });
44 // Also notify potential opponents: hit all clients which check if sid corresponds
45 Object.keys(clients[page]).forEach( k => {
46 clients[page][k].send(JSON.stringify({code:"connect",id:sid}));
47 });
48 socket.on("message", objtxt => {
49 let obj = JSON.parse(objtxt);
50 switch (obj.code)
51 {
52 case "newmove":
53 clients[page][obj.oppid].send(JSON.stringify({code:"newmove",move:obj.move}));
54 break;
55 case "ping":
56 if (!!clients[page][obj.oppid])
57 socket.send(JSON.stringify({code:"pong"}));
58 break;
59 case "newgame":
60 if (!!games[page])
61 {
62 // Start a new game
63 const oppId = games[page]["id"];
64 const fen = games[page]["fen"];
65 delete games[page];
66 const mycolor = Math.random() < 0.5 ? 'w' : 'b';
67 socket.send(JSON.stringify({code:"newgame",fen:fen,oppid:oppId,color:mycolor}));
68 clients[page][oppId].send(JSON.stringify({code:"newgame",fen:fen,oppid:sid,color:mycolor=="w"?"b":"w"}));
69 }
70 else
71 games[page] = {id:sid, fen:obj.fen}; //wait for opponent
72 break;
73 case "resign":
74 clients[page][obj.oppid].send(JSON.stringify({code:"resign"}));
75 break;
76 }
77 });
78 }
79 socket.on("close", () => {
80 delete clients[page][sid];
81 // Remove potential pending game
82 if (!!games[page] && games[page]["id"] == sid)
83 delete games[page];
84 if (page != "index")
85 {
86 // Send to every client connected on index an update message for counts
87 Object.keys(clients["index"]).forEach( k => {
88 clients["index"][k].send(JSON.stringify({code:"decrease",vname:page}));
89 });
90 }
91 // Also notify potential opponents: hit all clients which check if sid corresponds
92 Object.keys(clients[page]).forEach( k => {
93 clients[page][k].send(JSON.stringify({code:"disconnect",id:sid}));
94 });
95 });
96 });
97 }