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