+ clients[obj.target[0]][obj.target[1]].sock.send(JSON.stringify(
+ {code:"askchallenge",from:[sid,tmpId]}));
+ break;
+ case "askgames":
+ {
+ // Check all clients playing, and send them a "askgame" message
+ // game ID --> [ sid1 --> array of tmpIds, sid2 --> array of tmpIds]
+ let gameSids = {};
+ const regexpGid = /\/[a-zA-Z0-9]+$/;
+ Object.keys(clients).forEach(k => {
+ Object.keys(clients[k]).forEach(x => {
+ if ((k != sid || x != tmpId)
+ && clients[k][x].page.indexOf("/game/") >= 0)
+ {
+ const gid = clients[k][x].page.match(regexpGid)[0];
+ if (!gameSids[gid])
+ gameSids[gid] = [{k: [x]}];
+ else if (k == Object.keys(gameSids[gid][0])[0])
+ gameSids[gid][0][k].push(x);
+ else if (gameSids[gid].length == 1)
+ gameSids[gid].push({k: [x]});
+ else
+ Object.values(gameSids[gid][1]).push(x);
+ }
+ });
+ // Request only one client out of 2 (TODO: this is a bit heavy)
+ // Alt: ask game to all, and filter later?
+ Object.keys(gameSids).forEach(gid => {
+ const L = gameSids[gid].length;
+ const sidIdx = L > 1
+ ? Math.floor(Math.random() * Math.floor(L))
+ : 0;
+ const tmpIdx = Object.values(gameSids[gid][sidIdx]
+ const rid = gameSids[gid][sidIdx][tmpIdx];
+ clients[sidIdx][tmpIdx].sock.send(JSON.stringify(
+ {code:"askgame", from: [sid,tmpId]}));
+ });
+ break;
+ }