-
Notifications
You must be signed in to change notification settings - Fork 0
/
SessionManagerWebSocket.js
73 lines (60 loc) · 2.06 KB
/
SessionManagerWebSocket.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
import { SessionManagerApi } from './SessionManagerApi.js';
export class SessionManagerWebSocket {
constructor(retry = true) {
this.onLockStatusChanged = null;
this.onUserChanged = null;
this._ws = null;
this._retry = retry;
}
async connectWebSocket(id) {
var token = await this.getToken(id);
this._ws = new WebSocket(`wss://k8s.haidinger.me/api/session-manager/ws?token=${token}`);
this._ws.addEventListener('open', (event) => {
console.log('WebSocket connection opened:', event);
});
this._ws.addEventListener('message', (event) => {
console.log('WebSocket message received:', event.data);
const data = JSON.parse(event.data);
if (data.type === 'lockStatusChanged' && this.onLockStatusChanged) {
this.onLockStatusChanged(data.lockStatus);
}
else if (data.type === "userChanged" && this.onUserChanged) {
this.onUserChanged(data.user, data.action);
}
});
this._ws.addEventListener('close', (event) => {
console.log('WebSocket connection closed:', event);
// Attempt to reconnect after a delay
setTimeout(() => this.connectWebSocket(id), 5000);
});
this._ws.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
setTimeout(() => this.connectWebSocket(id), 5000);
});
}
async getToken(id) {
var sessionManagerApi = new SessionManagerApi();
let token;
do {
try {
while (!sessionManagerApi) {
// Wait until sessionManagerApi is defined
await new Promise(resolve => setTimeout(resolve, 100));
}
token = await sessionManagerApi.generateToken(id);
if (token) {
console.log(`Got token`);
break;
}
}
catch (err) {
console.warn("Got error while generating token, try again later (retry = " + this._retry + "): ");
await new Promise(resolve => setTimeout(resolve, 2500));
}
} while (this._retry);
if (!token) {
throw new Error("Could not get token");
}
return token;
}
}