Cosmetics
[xogo.git] / server.js
CommitLineData
41534b92 1const params = require("./parameters.js");
f46a68b8 2const WebSocket = require("ws");
41534b92
BA
3const wss = new WebSocket.Server(
4 {port: params.socket_port, path: params.socket_path});
5
6let challenges = {}; //variantName --> socketId, name
f46a68b8 7let games = {}; //gameId --> gameInfo (vname, fen, players, options, time)
41534b92
BA
8let sockets = {}; //socketId --> socket
9const variants = require("./variants.js");
f46a68b8
BA
10const Crypto = require("crypto");
11const randstrSize = 8;
8a9f61ce 12
524e87ed 13function send(sid, code, data) {
41534b92 14 const socket = sockets[sid];
f46a68b8 15 // If a player deletes local infos and then tries to resume a game,
41534b92
BA
16 // sockets[oppSid] will probably not exist anymore:
17 if (socket) socket.send(JSON.stringify(Object.assign({ code: code }, data)));
524e87ed 18}
41534b92 19
524e87ed 20wss.on("connection", (socket, req) => {
41534b92
BA
21 const sid = req.url.split("=")[1]; //...?sid=...
22 sockets[sid] = socket;
23 socket.isAlive = true;
f46a68b8 24 socket.on("pong", () => socket.isAlive = true);
41534b92
BA
25
26 function launchGame(vname, players, options) {
f46a68b8
BA
27 const gid =
28 Crypto.randomBytes(randstrSize).toString("hex").slice(0, randstrSize);
41534b92
BA
29 games[gid] = {
30 vname: vname,
31 players: players.map(p => {
32 return (!p ? null : {sid: p.sid, name: p.name});
33 }),
f46a68b8
BA
34 options: options,
35 time: Date.now()
41534b92
BA
36 };
37 if (players.every(p => p)) {
38 const gameInfo = Object.assign(
39 // Provide seed so that both players initialize with same FEN
40 {seed: Math.floor(Math.random() * 1984), gid: gid},
41 games[gid]);
f46a68b8
BA
42 for (const p of players) {
43 send(p.sid,
44 "gamestart",
45 Object.assign({randvar: p.randvar}, gameInfo));
41534b92
BA
46 }
47 }
48 else {
49 // Incomplete players array: do not start game yet
50 send(sid, "gamecreated", {gid: gid});
f46a68b8 51 // If nobody joins within 5 minutes, delete game
41534b92
BA
52 setTimeout(
53 () => {
54 if (games[gid] && games[gid].players.some(p => !p))
55 delete games[gid];
56 },
f46a68b8 57 5 * 60000
41534b92
BA
58 );
59 }
60 }
61
f46a68b8 62 socket.on("message", (msg) => {
41534b92
BA
63 const obj = JSON.parse(msg);
64 switch (obj.code) {
65 // Send challenge (may trigger game creation)
66 case "seekgame": {
41534b92
BA
67 let opponent = undefined,
68 choice = undefined;
69 const vname = obj.vname,
70 randvar = (obj.vname == "_random");
71 if (vname == "_random") {
f46a68b8 72 // Pick any current challenge if possible
41534b92
BA
73 const currentChalls = Object.keys(challenges);
74 if (currentChalls.length >= 1) {
75 choice =
76 currentChalls[Math.floor(Math.random() * currentChalls.length)];
77 opponent = challenges[choice];
78 }
79 }
80 else if (challenges[vname]) {
81 opponent = challenges[vname];
82 choice = vname;
83 }
84 if (opponent) {
85 delete challenges[choice];
86 if (choice == "_random") {
87 // Pick a variant at random in the list
88 const index = Math.floor(Math.random() * variants.length);
89 choice = variants[index].name;
90 }
91 // Launch game
92 let players = [
93 {sid: sid, name: obj.name, randvar: randvar},
94 opponent
95 ];
96 if (Math.random() < 0.5) players = players.reverse();
97 launchGame(choice, players, {}); //empty options => default
98 }
99 else
100 // Place challenge and wait. 'randvar' indicate if we play anything
101 challenges[vname] = {sid: sid, name: obj.name, randvar: randvar};
102 break;
103 }
f46a68b8 104 // Set FEN after game was created (received twice)
41534b92
BA
105 case "setfen":
106 games[obj.gid].fen = obj.fen;
107 break;
108 // Send back game informations
109 case "getgame": {
110 if (!games[obj.gid]) send(sid, "nogame");
111 else send(sid, "gameinfo", games[obj.gid]);
112 break;
113 }
114 // Cancel challenge
115 case "cancelseek":
116 delete challenges[obj.vname];
117 break;
118 // Receive rematch
8a9f61ce 119 case "rematch":
41534b92
BA
120 if (!games[obj.gid]) send(sid, "closerematch");
121 else {
122 const myIndex = (games[obj.gid].players[0].sid == sid ? 0 : 1);
123 if (!games[obj.gid].rematch) games[obj.gid].rematch = [false, false];
124 games[obj.gid].rematch[myIndex] = true;
125 if (games[obj.gid].rematch[1-myIndex]) {
126 // Launch new game, colors reversed
127 launchGame(games[obj.gid].vname,
128 games[obj.gid].players.reverse(),
129 games[obj.gid].options);
130 }
131 }
132 break;
8a9f61ce
BA
133 // Rematch cancellation
134 case "norematch":
41534b92
BA
135 if (games[obj.gid]) {
136 const myIndex = (games[obj.gid].players[0].sid == sid ? 0 : 1);
137 send(games[obj.gid].players[1-myIndex].sid, "closerematch");
138 }
139 break;
41534b92 140 // Create game vs. friend
8a9f61ce 141 case "creategame": {
41534b92 142 let players = [
f46a68b8 143 {sid: obj.player.sid, name: obj.player.name},
41534b92
BA
144 undefined
145 ];
146 if (
147 obj.player.color == 'b' ||
148 (obj.player.color == '' && Math.random() < 0.5)
149 ) {
150 players = players.reverse();
151 }
152 launchGame(obj.vname, players, obj.options);
153 break;
8a9f61ce 154 }
41534b92 155 // Join game vs. friend
8a9f61ce 156 case "joingame":
41534b92
BA
157 if (!games[obj.gid]) send(sid, "jointoolate");
158 else {
159 // Join a game (started by some other player)
160 const emptySlot = games[obj.gid].players.findIndex(p => !p);
161 if (emptySlot < 0) send(sid, "jointoolate");
162 games[obj.gid].players[emptySlot] = {sid: sid, name: obj.name};
163 const gameInfo = Object.assign(
164 // Provide seed so that both players initialize with same FEN
165 {seed: Math.floor(Math.random()*1984), gid: obj.gid},
166 games[obj.gid]);
f46a68b8
BA
167 for (const p of games[obj.gid].players)
168 send(p.sid, "gamestart", gameInfo);
41534b92
BA
169 }
170 break;
41534b92 171 // Relay a move + update games object
8a9f61ce 172 case "newmove":
41534b92 173 games[obj.gid].fen = obj.fen;
f46a68b8 174 games[obj.gid].time = Date.now(); //update timestamp in case of
41534b92
BA
175 const playingWhite = (games[obj.gid].players[0].sid == sid);
176 const oppSid = games[obj.gid].players[playingWhite ? 1 : 0].sid;
f46a68b8 177 send(oppSid, "newmove", {moves: obj.moves});
41534b92 178 break;
41534b92 179 // Relay "game ends" message
f46a68b8
BA
180 case "gameover":
181 if (obj.relay) {
182 const playingWhite = (games[obj.gid].players[0].sid == sid);
183 const oppSid = games[obj.gid].players[playingWhite ? 1 : 0].sid;
184 send(oppSid, "gameover", { gid: obj.gid });
185 }
186 // 2 minutes timeout for rematch:
187 setTimeout(() => delete games[obj.gid], 2 * 60000);
41534b92 188 break;
41534b92
BA
189 }
190 });
191 socket.on("close", () => {
192 delete sockets[sid];
193 for (const [key, value] of Object.entries(challenges)) {
194 if (value.sid == sid) {
195 delete challenges[key];
196 break; //only one challenge per player
197 }
198 }
199 });
200});
201
f46a68b8 202const heartbeat = setInterval(() => {
41534b92
BA
203 wss.clients.forEach((ws) => {
204 if (ws.isAlive === false) return ws.terminate();
205 ws.isAlive = false;
206 ws.ping();
207 });
208}, 30000);
f46a68b8
BA
209
210// Every 24 hours, scan games and remove if last move older than 24h
211const dayInMillisecs = 24 * 60 * 60 * 1000;
212const killOldGames = setInterval(() => {
213 const now = Date.now();
214 Object.keys(games).forEach(gid => {
215 if (now - games[gid].time >= dayInMillisecs) delete games[gid];
216 });
217}, dayInMillisecs);
218
219// TODO: useful code here?
220wss.on("close", () => {
221 clearInterval(heartbeat);
222 clearInterval(killOldGames);
223});