forked from ynoproject/forest-orb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.js
91 lines (82 loc) · 2.43 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
let sessionWs;
const wsDelim = '\uffff';
let sessionCommandHandlers = {};
let sessionCommandCallbackQueue = {};
let hasConnected;
function initSessionWs(attempt) {
return new Promise(resolve => {
if (sessionWs)
closeSessionWs(sessionWs);
if (config.singlePlayer) {
resolve();
return;
}
let url = `wss://connect.ynoproject.net/${ynoGameId}/session`;
if (loginToken)
url += `?token=${loginToken}`;
sessionWs = new WebSocket(url);
sessionWs.onclose = e => {
if (e.code === 1028)
return;
if (!attempt)
attempt = 1;
const delay = Math.min(attempt * 5000, 30000);
setTimeout(() => initSessionWs(attempt + 1).then(() => resolve()), delay);
};
sessionWs.onopen = () => {
sessionWs.onclose = e => {
if (e.code === 1028)
return;
setTimeout(() => initSessionWs(1), 5000);
};
easyrpgPlayer.api.sessionReady();
if (config.privateMode)
sendSessionCommand('pr', [ 1 ]);
if (!hasConnected) {
syncChatHistory()
.catch(err => console.error(err))
.finally(addChatTip);
hasConnected = true;
} else
syncChatHistory()
.catch(err => console.error(err));
resolve();
};
sessionWs.onmessage = event => {
const args = event.data.split(wsDelim);
const command = args[0];
if (sessionCommandHandlers.hasOwnProperty(command)) {
const params = args.slice(1);
if (sessionCommandHandlers[command])
sessionCommandHandlers[command](params);
while (sessionCommandCallbackQueue[command].length)
sessionCommandCallbackQueue[command].shift()(params);
}
};
});
}
function closeSessionWs() {
if (!sessionWs)
return;
sessionWs.onclose = null;
sessionWs.close();
sessionWs = null;
}
function addSessionCommandHandler(command, handler) {
sessionCommandHandlers[command] = handler;
sessionCommandCallbackQueue[command] = [];
}
function sendSessionCommand(command, commandParams, callbackFunc, callbackCommand) {
if (!sessionWs)
return;
let args = [ command ];
if (commandParams?.length)
args = args.concat(commandParams);
if (callbackFunc) {
if (!callbackCommand)
callbackCommand = command;
if (sessionCommandCallbackQueue.hasOwnProperty(callbackCommand))
sessionCommandCallbackQueue[callbackCommand].push(callbackFunc);
}
sessionWs.send(args.join(wsDelim));
}