81 lines
2.2 KiB
JavaScript
81 lines
2.2 KiB
JavaScript
import { getAuthToken, getItem } from "./storage";
|
|
|
|
export const GatewayPayloadType = {
|
|
Hello: 0,
|
|
Authenticate: 1,
|
|
Ready: 2,
|
|
Ping: 3,
|
|
|
|
ChannelCreate: 110,
|
|
ChannelUpdate: 111,
|
|
ChannelDelete: 112,
|
|
|
|
MessageCreate: 120,
|
|
MessageUpdate: 121,
|
|
MessageDelete: 122,
|
|
}
|
|
|
|
export default {
|
|
ws: null,
|
|
authenticated: false,
|
|
heartbeatInterval: null,
|
|
user: null,
|
|
channels: null,
|
|
reconnectDelay: 400,
|
|
reconnectTimeout: null,
|
|
init() {
|
|
const token = getAuthToken();
|
|
if (!token) {
|
|
return false;
|
|
}
|
|
this.ws = new WebSocket(getItem("gatewayBase"));
|
|
this.ws.onopen = () => {
|
|
if (this.reconnectTimeout) {
|
|
clearTimeout(this.reconnectTimeout);
|
|
}
|
|
this.reconnectDelay = 400;
|
|
};
|
|
this.ws.onmessage = (event) => {
|
|
const payload = JSON.parse(event.data);
|
|
|
|
switch (payload.t) {
|
|
case GatewayPayloadType.Hello: {
|
|
this.send({
|
|
t: GatewayPayloadType.Authenticate,
|
|
d: token
|
|
});
|
|
|
|
this.heartbeatInterval = setInterval(() => {
|
|
this.send({
|
|
t: GatewayPayloadType.Ping,
|
|
d: 0
|
|
});
|
|
}, payload.d.pingInterval);
|
|
break;
|
|
}
|
|
case GatewayPayloadType.Ready: {
|
|
this.user = payload.d.user;
|
|
this.channels = payload.d.channels;
|
|
break;
|
|
}
|
|
}
|
|
};
|
|
this.ws.onclose = () => {
|
|
this.reconnectDelay *= 2;
|
|
this.authenticated = false;
|
|
this.user = null;
|
|
this.channels = null;
|
|
if (this.heartbeatInterval) {
|
|
clearInterval(this.heartbeatInterval);
|
|
}
|
|
this.reconnectTimeout = setTimeout(() => {
|
|
this.init();
|
|
}, this.reconnectDelay);
|
|
};
|
|
|
|
return true;
|
|
},
|
|
send(data) {
|
|
return this.ws.send(JSON.stringify(data));
|
|
}
|
|
};
|