1 const Discord
= require('discord.js');
2 const { token
, channel
} = require('./config/discord.json');
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 "/?"
8 query
.split("&").forEach((part
) => {
9 const item
= part
.split("=");
10 result
[item
[0]] = decodeURIComponent(item
[1]);
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
));
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
27 // NOTE: only purpose of sidToPages = know when to delete keys in 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
);
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;
51 clients
[page
][k
][x
].socket
,
52 Object
.assign({ code: code
, from: [sid
, tmpId
] }, obj
)
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)
67 // Am I totally offline?
68 if (sidToPages
[sid
].length
== 0) {
69 delete sidToPages
[sid
];
75 const doDisconnect
= () => {
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
});
84 const messageListener
= (objtxt
) => {
85 let obj
= JSON
.parse(objtxt
);
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.
91 notifyRoom(page
, "connect");
92 if (page
.indexOf("/game/") >= 0)
93 notifyRoom("/", "gconnect", { page: page
});
100 case "pollclients": {
103 Object
.keys(clients
[page
]).forEach(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
};
111 send(socket
, { code: "pollclients", sockIds: sockIds
});
114 case "pollclientsandgamers": {
117 Object
.keys(clients
["/"]).forEach(k
=> {
119 Object
.keys(clients
[page
][k
]).forEach(x
=> {
120 // Avoid polling my tmpId: no information to get
121 if (k
!= sid
|| x
!= tmpId
) {
124 focus: clients
[page
][k
][x
].focus
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
) {
138 focus: clients
[p
][k
][x
].focus
145 send(socket
, { code: "pollclientsandgamers", sockIds: sockIds
});
149 // Asking something: from is fully identified,
150 // but the requested resource can be from any tmpId (except current!)
153 case "askchallenges":
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
) {
160 const idx_myTmpid
= tmpIds
.findIndex(x
=> x
== tmpId
);
161 if (idx_myTmpid
>= 0) tmpIds
.splice(idx_myTmpid
, 1);
163 if (tmpIds
.length
> 0) {
164 const ttmpId
= tmpIds
[Math
.floor(Math
.random() * tmpIds
.length
)];
166 clients
[pg
][obj
.target
][ttmpId
].socket
,
167 { code: obj
.code
, from: [sid
,tmpId
,page
] }
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
)];
186 clients
[page
][rid
][rtmpId
].socket
,
187 { code: "askfullgame", from: [sid
,tmpId
] }
190 // I'm the only person who have the game for the moment:
191 send(socket
, { code: "fullgame", data: { empty: true } });
197 // Some Hall events: target all tmpId's (except mine),
198 case "refusechallenge":
200 Object
.keys(clients
[page
][obj
.target
]).forEach(x
=> {
201 if (obj
.target
!= sid
|| x
!= tmpId
)
203 clients
[page
][obj
.target
][x
].socket
,
204 { code: obj
.code
, data: obj
.data
}
209 // Notify all room: mostly game events
212 case "deletechallenge_s":
219 // "newgame" message can provide a page (corr Game --> Hall)
221 obj
.page
|| page
, obj
.code
, {data: obj
.data
}, obj
.excluded
);
223 obj
.code
== "newchallenge" &&
224 !obj
.data
.to
&& //filter out targeted challenges
225 obj
.data
.cadence
.indexOf('d') < 0 //and correspondance games
228 "New challenge: **" + obj
.data
.vname
+ "** " +
229 "[" + obj
.data
.cadence
+ "]"
231 if (!!discordChannel
) discordChannel
.send(challMsg
);
233 // Log when running locally (dev, debug):
234 console
.log(challMsg
);
239 // A rematch game started:
240 notifyRoom(page
, "newgame", {data: obj
.data
});
241 // Explicitely notify Hall if gametype == corr.
242 // Live games will be polled from Hall after gconnect event.
243 if (obj
.data
.cadence
.indexOf('d') >= 0)
244 notifyRoom("/", "newgame", {data: obj
.data
});
248 const dataWithFrom
= { from: [sid
,tmpId
], data: obj
.data
};
249 // Special case re-send newmove only to opponent:
250 if (!!obj
.target
&& !!clients
[page
][obj
.target
]) {
251 Object
.keys(clients
[page
][obj
.target
]).forEach(x
=> {
253 clients
[page
][obj
.target
][x
].socket
,
254 Object
.assign({ code: "newmove" }, dataWithFrom
)
258 // NOTE: data.from is useful only to opponent
259 notifyRoom(page
, "newmove", dataWithFrom
);
265 !!clients
[page
][obj
.target
[0]] &&
266 !!clients
[page
][obj
.target
[0]][obj
.target
[1]]
269 clients
[page
][obj
.target
[0]][obj
.target
[1]].socket
,
276 // Special case: notify all, 'transroom': Game --> Hall
277 notifyRoom("/", "result", { gid: obj
.gid
, score: obj
.score
});
281 const gamePg
= "/game/" + obj
.gid
;
282 if (!!clients
[gamePg
] && !!clients
[gamePg
][obj
.target
]) {
283 Object
.keys(clients
[gamePg
][obj
.target
]).forEach(x
=> {
285 clients
[gamePg
][obj
.target
][x
].socket
,
295 case "notifynewgame":
296 if (!!clients
["/mygames"]) {
297 obj
.targets
.forEach(t
=> {
298 const k
= t
.sid
|| idToSid
[t
.id
];
299 if (!!clients
["/mygames"][k
]) {
300 Object
.keys(clients
["/mygames"][k
]).forEach(x
=> {
302 clients
["/mygames"][k
][x
].socket
,
303 { code: obj
.code
, data: obj
.data
}
315 !!clients
[page
][sid
] &&
316 !!clients
[page
][sid
][tmpId
]
318 clients
[page
][sid
][tmpId
].focus
= (obj
.code
== "getfocus");
320 if (page
== "/") notifyRoom("/", obj
.code
, { page: "/" }, [sid
]);
322 // Notify game room + Hall:
323 notifyRoom(page
, obj
.code
, {}, [sid
]);
324 notifyRoom("/", obj
.code
, { page: page
}, [sid
]);
328 // Passing, relaying something: from isn't needed,
329 // but target is fully identified (sid + tmpId)
336 const pg
= obj
.target
[2] || page
; //required for identity and game
337 // NOTE: if in game we ask identity to opponent still in Hall, but
338 // leaving Hall, clients[pg] or clients[pg][target] could be undef.
339 if (!!clients
[pg
] && !!clients
[pg
][obj
.target
[0]]) {
341 clients
[pg
][obj
.target
[0]][obj
.target
[1]].socket
,
342 { code:obj
.code
, data:obj
.data
}
349 const closeListener
= () => {
350 // For browser or tab closing (including page reload):
353 // Update clients object: add new connexion
354 const newElt
= { socket: socket
, focus: true };
356 clients
[page
] = { [sid
]: {[tmpId
]: newElt
} };
357 else if (!clients
[page
][sid
])
358 clients
[page
][sid
] = { [tmpId
]: newElt
};
360 clients
[page
][sid
][tmpId
] = newElt
;
361 // Also update helper correspondances
362 if (!idToSid
[id
]) idToSid
[id
] = sid
;
363 if (!sidToPages
[sid
]) sidToPages
[sid
] = [];
364 const pgIndex
= sidToPages
[sid
].findIndex(pg
=> pg
== page
);
365 if (pgIndex
=== -1) sidToPages
[sid
].push(page
);
366 socket
.on("message", messageListener
);
367 socket
.on("close", closeListener
);