forked from ynoproject/forest-orb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.js
65 lines (57 loc) · 1.82 KB
/
session.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
let sessionWs;
const wsDelim = '\uffff';
let sessionCommandHandlers = {};
let sessionCommandCallbackQueue = {};
function initSessionWs(attempt) {
return new Promise(resolve => {
let url = `wss://${location.host}/connect/${ynoGameId}/session`;
if (loginToken)
url += `?token=${loginToken}`;
if (sessionWs)
closeSession(sessionWs);
sessionWs = new WebSocket(url);
sessionWs.onclose = () => {
if (!attempt)
attempt = 1;
const delay = Math.min(attempt * 5000, 30000);
setTimeout(() => initSessionWs(attempt + 1).then(() => resolve()), delay);
};
sessionWs.onopen = () => {
sessionWs.onclose = () => {
setTimeout(() => initSessionWs(1), 5000);
};
resolve();
};
sessionWs.onmessage = event => {
const args = event.data.split(wsDelim);
const command = args[0];
if (sessionCommandHandlers.hasOwnProperty(command)) {
const params = args.slice(1);
sessionCommandHandlers[command](params);
while (sessionCommandCallbackQueue[command].length)
sessionCommandCallbackQueue[command].shift()(params);
}
};
});
}
function closeSession() {
if (!sessionWs)
return;
sessionWs.onclose = null;
sessionWs.close();
sessionWs = null;
}
function addSessionCommandHandler(command, handler) {
sessionCommandHandlers[command] = handler;
sessionCommandCallbackQueue[command] = [];
}
function sendSessionCommand(command, commandParams, callbackCommand, callbackFunc) {
if (!sessionWs)
return;
let args = [ command ];
if (commandParams?.length)
args = args.concat(commandParams);
if (callbackCommand && callbackFunc && sessionCommandCallbackQueue.hasOwnProperty(callbackCommand))
sessionCommandCallbackQueue[callbackCommand].push(callbackFunc);
sessionWs.send(args.join(wsDelim));
}