| 1 | const Discord = require('discord.js'); |
| 2 | const { token, channel } = require('./config/discord.json'); |
| 3 | |
| 4 | // Node version in Ubuntu 16.04 does not know about URL class |
| 5 | function getJsonFromUrl(url) { |
| 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 | // Helper to safe-send some message through a (web-)socket: |
| 16 | function send(socket, message) { |
| 17 | if (!!socket && socket.readyState == 1) |
| 18 | socket.send(JSON.stringify(message)); |
| 19 | } |
| 20 | |
| 21 | module.exports = function(wss) { |
| 22 | // Associative array page --> sid --> tmpId --> socket |
| 23 | // "page" is either "/" for hall or "/game/some_gid" for Game, |
| 24 | // or "/mygames" for Mygames page (simpler: no 'people' array). |
| 25 | // tmpId is required if a same user (browser) has different tabs |
| 26 | let clients = {}; |
| 27 | // NOTE: only purpose of sidToPages = know when to delete keys in idToSid |
| 28 | let sidToPages = {}; |
| 29 | let idToSid = {}; |
| 30 | const discordClient = new Discord.Client(); |
| 31 | let discordChannel = null; |
| 32 | if (token.length > 0) { |
| 33 | discordClient.login(token).then( () => { |
| 34 | discordChannel = discordClient.channels.cache.get(channel); |
| 35 | }); |
| 36 | } |
| 37 | wss.on("connection", (socket, req) => { |
| 38 | const query = getJsonFromUrl(req.url); |
| 39 | const sid = query["sid"]; |
| 40 | const id = query["id"]; |
| 41 | const tmpId = query["tmpId"]; |
| 42 | const page = query["page"]; |
| 43 | const notifyRoom = (page, code, obj={}, except) => { |
| 44 | if (!clients[page]) return; |
| 45 | except = except || []; |
| 46 | Object.keys(clients[page]).forEach(k => { |
| 47 | if (except.includes(k)) return; |
| 48 | Object.keys(clients[page][k]).forEach(x => { |
| 49 | if (k == sid && x == tmpId) return; |
| 50 | send( |
| 51 | clients[page][k][x].socket, |
| 52 | Object.assign({ code: code, from: [sid, tmpId] }, obj) |
| 53 | ); |
| 54 | }); |
| 55 | }); |
| 56 | }; |
| 57 | const deleteConnexion = () => { |
| 58 | if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId]) |
| 59 | return; //job already done |
| 60 | delete clients[page][sid][tmpId]; |
| 61 | if (Object.keys(clients[page][sid]).length == 0) { |
| 62 | delete clients[page][sid]; |
| 63 | const pgIndex = sidToPages[sid].findIndex(pg => pg == page); |
| 64 | sidToPages[sid].splice(pgIndex, 1); |
| 65 | if (Object.keys(clients[page]).length == 0) |
| 66 | delete clients[page]; |
| 67 | // Am I totally offline? |
| 68 | if (sidToPages[sid].length == 0) { |
| 69 | delete sidToPages[sid]; |
| 70 | delete idToSid[id]; |
| 71 | } |
| 72 | } |
| 73 | }; |
| 74 | |
| 75 | const doDisconnect = () => { |
| 76 | deleteConnexion(); |
| 77 | // Nothing to notify when disconnecting from MyGames page: |
| 78 | if (page != "/mygames") { |
| 79 | notifyRoom(page, "disconnect"); |
| 80 | if (page.indexOf("/game/") >= 0) |
| 81 | notifyRoom("/", "gdisconnect", { page: page }); |
| 82 | } |
| 83 | }; |
| 84 | const messageListener = (objtxt) => { |
| 85 | let obj = JSON.parse(objtxt); |
| 86 | switch (obj.code) { |
| 87 | // Wait for "connect" message to notify connection to the room, |
| 88 | // because if game loading is slow the message listener might |
| 89 | // not be ready too early. |
| 90 | case "connect": { |
| 91 | notifyRoom(page, "connect"); |
| 92 | if (page.indexOf("/game/") >= 0) |
| 93 | notifyRoom("/", "gconnect", { page: page }); |
| 94 | break; |
| 95 | } |
| 96 | case "disconnect": |
| 97 | // When page changes: |
| 98 | doDisconnect(); |
| 99 | break; |
| 100 | case "pollclients": { |
| 101 | // From Game |
| 102 | let sockIds = {}; |
| 103 | Object.keys(clients[page]).forEach(k => { |
| 104 | sockIds[k] = {}; |
| 105 | Object.keys(clients[page][k]).forEach(x => { |
| 106 | // Avoid polling my tmpId: no information to get |
| 107 | if (k != sid || x != tmpId) |
| 108 | sockIds[k][x] = { focus: clients[page][k][x].focus }; |
| 109 | }); |
| 110 | }); |
| 111 | send(socket, { code: "pollclients", sockIds: sockIds }); |
| 112 | break; |
| 113 | } |
| 114 | case "pollclientsandgamers": { |
| 115 | // From Hall |
| 116 | let sockIds = {}; |
| 117 | Object.keys(clients["/"]).forEach(k => { |
| 118 | sockIds[k] = {}; |
| 119 | Object.keys(clients[page][k]).forEach(x => { |
| 120 | // Avoid polling my tmpId: no information to get |
| 121 | if (k != sid || x != tmpId) { |
| 122 | sockIds[k][x] = { |
| 123 | page: "/", |
| 124 | focus: clients[page][k][x].focus |
| 125 | }; |
| 126 | } |
| 127 | }); |
| 128 | }); |
| 129 | // NOTE: a "gamer" could also just be an observer |
| 130 | Object.keys(clients).forEach(p => { |
| 131 | if (p.indexOf("/game/") >= 0) { |
| 132 | Object.keys(clients[p]).forEach(k => { |
| 133 | if (!sockIds[k]) sockIds[k] = {}; |
| 134 | Object.keys(clients[p][k]).forEach(x => { |
| 135 | if (k != sid || x != tmpId) { |
| 136 | sockIds[k][x] = { |
| 137 | page: p, |
| 138 | focus: clients[p][k][x].focus |
| 139 | }; |
| 140 | } |
| 141 | }); |
| 142 | }); |
| 143 | } |
| 144 | }); |
| 145 | send(socket, { code: "pollclientsandgamers", sockIds: sockIds }); |
| 146 | break; |
| 147 | } |
| 148 | |
| 149 | // Asking something: from is fully identified, |
| 150 | // but the requested resource can be from any tmpId (except current!) |
| 151 | case "askidentity": |
| 152 | case "asklastate": |
| 153 | case "askchallenges": |
| 154 | case "askgame": { |
| 155 | const pg = obj.page || page; //required for askidentity and askgame |
| 156 | if (!!clients[pg] && !!clients[pg][obj.target]) { |
| 157 | let tmpIds = Object.keys(clients[pg][obj.target]); |
| 158 | if (obj.target == sid) { |
| 159 | // Targetting myself |
| 160 | const idx_myTmpid = tmpIds.findIndex(x => x == tmpId); |
| 161 | if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1); |
| 162 | } |
| 163 | if (tmpIds.length > 0) { |
| 164 | const ttmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)]; |
| 165 | send( |
| 166 | clients[pg][obj.target][ttmpId].socket, |
| 167 | { code: obj.code, from: [sid,tmpId,page] } |
| 168 | ); |
| 169 | } |
| 170 | } |
| 171 | break; |
| 172 | } |
| 173 | |
| 174 | // Special situation of the previous "case": |
| 175 | // Full game can be asked to any observer. |
| 176 | case "askfullgame": { |
| 177 | if (!!clients[page]) { |
| 178 | let sids = Object.keys(clients[page]).filter(k => k != sid); |
| 179 | if (sids.length > 0) { |
| 180 | // Pick a SID at random in this set, and ask full game: |
| 181 | const rid = sids[Math.floor(Math.random() * sids.length)]; |
| 182 | // ..to a random tmpId: |
| 183 | const tmpIds = Object.keys(clients[page][rid]); |
| 184 | const rtmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)]; |
| 185 | send( |
| 186 | clients[page][rid][rtmpId].socket, |
| 187 | { code: "askfullgame", from: [sid,tmpId] } |
| 188 | ); |
| 189 | } else { |
| 190 | // I'm the only person who have the game for the moment: |
| 191 | send(socket, { code: "fullgame", data: { empty: true } }); |
| 192 | } |
| 193 | } |
| 194 | break; |
| 195 | } |
| 196 | |
| 197 | // Some Hall events: target all tmpId's (except mine), |
| 198 | case "refusechallenge": |
| 199 | case "startgame": |
| 200 | Object.keys(clients[page][obj.target]).forEach(x => { |
| 201 | if (obj.target != sid || x != tmpId) |
| 202 | send( |
| 203 | clients[page][obj.target][x].socket, |
| 204 | { code: obj.code, data: obj.data } |
| 205 | ); |
| 206 | }); |
| 207 | break; |
| 208 | |
| 209 | // Notify all room: mostly game events |
| 210 | case "newchat": |
| 211 | case "newchallenge": |
| 212 | case "deletechallenge_s": |
| 213 | case "newgame": |
| 214 | case "resign": |
| 215 | case "abort": |
| 216 | case "drawoffer": |
| 217 | case "rematchoffer": |
| 218 | case "draw": |
| 219 | // "newgame" message can provide a page (corr Game --> Hall) |
| 220 | notifyRoom( |
| 221 | obj.page || page, obj.code, {data: obj.data}, obj.excluded); |
| 222 | if (!!discordChannel && obj.code == "newchallenge") { |
| 223 | discordChannel.send("New challenge: " + |
| 224 | obj.data.vname + |
| 225 | " [" + obj.data.cadence + "]" + |
| 226 | " - https://vchess.club"); |
| 227 | } |
| 228 | break; |
| 229 | |
| 230 | case "rnewgame": |
| 231 | // A rematch game started: |
| 232 | notifyRoom(page, "newgame", {data: obj.data}); |
| 233 | // Explicitely notify Hall if gametype == corr. |
| 234 | // Live games will be polled from Hall after gconnect event. |
| 235 | if (obj.data.cadence.indexOf('d') >= 0) |
| 236 | notifyRoom("/", "newgame", {data: obj.data}); |
| 237 | break; |
| 238 | |
| 239 | case "newmove": { |
| 240 | const dataWithFrom = { from: [sid,tmpId], data: obj.data }; |
| 241 | // Special case re-send newmove only to opponent: |
| 242 | if (!!obj.target && !!clients[page][obj.target]) { |
| 243 | Object.keys(clients[page][obj.target]).forEach(x => { |
| 244 | send( |
| 245 | clients[page][obj.target][x].socket, |
| 246 | Object.assign({ code: "newmove" }, dataWithFrom) |
| 247 | ); |
| 248 | }); |
| 249 | } else { |
| 250 | // NOTE: data.from is useful only to opponent |
| 251 | notifyRoom(page, "newmove", dataWithFrom); |
| 252 | } |
| 253 | break; |
| 254 | } |
| 255 | case "gotmove": |
| 256 | if ( |
| 257 | !!clients[page][obj.target[0]] && |
| 258 | !!clients[page][obj.target[0]][obj.target[1]] |
| 259 | ) { |
| 260 | send( |
| 261 | clients[page][obj.target[0]][obj.target[1]].socket, |
| 262 | { code: "gotmove" } |
| 263 | ); |
| 264 | } |
| 265 | break; |
| 266 | |
| 267 | case "result": |
| 268 | // Special case: notify all, 'transroom': Game --> Hall |
| 269 | notifyRoom("/", "result", { gid: obj.gid, score: obj.score }); |
| 270 | break; |
| 271 | |
| 272 | case "mabort": { |
| 273 | const gamePg = "/game/" + obj.gid; |
| 274 | if (!!clients[gamePg] && !!clients[gamePg][obj.target]) { |
| 275 | Object.keys(clients[gamePg][obj.target]).forEach(x => { |
| 276 | send( |
| 277 | clients[gamePg][obj.target][x].socket, |
| 278 | { code: "abort" } |
| 279 | ); |
| 280 | }); |
| 281 | } |
| 282 | break; |
| 283 | } |
| 284 | |
| 285 | case "notifyscore": |
| 286 | case "notifyturn": |
| 287 | case "notifynewgame": |
| 288 | if (!!clients["/mygames"]) { |
| 289 | obj.targets.forEach(t => { |
| 290 | const k = t.sid || idToSid[t.id]; |
| 291 | if (!!clients["/mygames"][k]) { |
| 292 | Object.keys(clients["/mygames"][k]).forEach(x => { |
| 293 | send( |
| 294 | clients["/mygames"][k][x].socket, |
| 295 | { code: obj.code, data: obj.data } |
| 296 | ); |
| 297 | }); |
| 298 | } |
| 299 | }); |
| 300 | } |
| 301 | break; |
| 302 | |
| 303 | case "getfocus": |
| 304 | case "losefocus": |
| 305 | if ( |
| 306 | !!clients[page] && |
| 307 | !!clients[page][sid] && |
| 308 | !!clients[page][sid][tmpId] |
| 309 | ) { |
| 310 | clients[page][sid][tmpId].focus = (obj.code == "getfocus"); |
| 311 | } |
| 312 | if (page == "/") notifyRoom("/", obj.code, { page: "/" }, [sid]); |
| 313 | else { |
| 314 | // Notify game room + Hall: |
| 315 | notifyRoom(page, obj.code, {}, [sid]); |
| 316 | notifyRoom("/", obj.code, { page: page }, [sid]); |
| 317 | } |
| 318 | break; |
| 319 | |
| 320 | // Passing, relaying something: from isn't needed, |
| 321 | // but target is fully identified (sid + tmpId) |
| 322 | case "challenges": |
| 323 | case "fullgame": |
| 324 | case "game": |
| 325 | case "identity": |
| 326 | case "lastate": |
| 327 | { |
| 328 | const pg = obj.target[2] || page; //required for identity and game |
| 329 | // NOTE: if in game we ask identity to opponent still in Hall, but |
| 330 | // leaving Hall, clients[pg] or clients[pg][target] could be undef. |
| 331 | if (!!clients[pg] && !!clients[pg][obj.target[0]]) { |
| 332 | send( |
| 333 | clients[pg][obj.target[0]][obj.target[1]].socket, |
| 334 | { code:obj.code, data:obj.data } |
| 335 | ); |
| 336 | } |
| 337 | break; |
| 338 | } |
| 339 | } |
| 340 | }; |
| 341 | const closeListener = () => { |
| 342 | // For browser or tab closing (including page reload): |
| 343 | doDisconnect(); |
| 344 | }; |
| 345 | // Update clients object: add new connexion |
| 346 | const newElt = { socket: socket, focus: true }; |
| 347 | if (!clients[page]) |
| 348 | clients[page] = { [sid]: {[tmpId]: newElt } }; |
| 349 | else if (!clients[page][sid]) |
| 350 | clients[page][sid] = { [tmpId]: newElt }; |
| 351 | else |
| 352 | clients[page][sid][tmpId] = newElt; |
| 353 | // Also update helper correspondances |
| 354 | if (!idToSid[id]) idToSid[id] = sid; |
| 355 | if (!sidToPages[sid]) sidToPages[sid] = []; |
| 356 | const pgIndex = sidToPages[sid].findIndex(pg => pg == page); |
| 357 | if (pgIndex === -1) sidToPages[sid].push(page); |
| 358 | socket.on("message", messageListener); |
| 359 | socket.on("close", closeListener); |
| 360 | }); |
| 361 | } |