Free javascript Hosting


twitchpubsub.js

Uploaded on Oct 09 2021 00:52 by vaverix2

class TwitchWebSocket {
constructor(oAuth, topics, callback) {
this.oAuth = oAuth;
this.topics = topics;
this.callback = callback;
this.lastPingTimestamp = null;
this.lastPongTimestamp = null;
this.pingInterval = null;
this.pongTimeout = null;
this.init();
}

init() {
this._ws = new WebSocket('wss://pubsub-edge.twitch.tv');
this._ws.onopen = this.onOpen.bind(this);
this._ws.onmessage = this.onMessage.bind(this);
this._ws.onerror = this.onError.bind(this);
this._ws.onclose = this.onClose.bind(this);
}

reconnect() {
console.warn('Reconnecting to server...');
clearInterval(this.pingInterval);
clearTimeout(this.pongTimeout);
this.init();
}

onOpen() {
this.sendPing();
this.pingInterval = setInterval(() => this.sendPing(), 5000 * 60);
this.sendJson({
type: 'LISTEN',
nonce: 'fds765fds56fd6s',
data: {
auth_token: this.oAuth,
topics: this.topics,
},
});
}

onMessage(message) {
const data = JSON.parse(message.data);
switch (data.type) {
case 'PONG':
this._handleMessagePong();
break;
case 'RECONNECT':
this._handleMessageReconnect();
break;
default:
//console.log(data);
this.callback(data);
}
}

onError(error) {
console.error(error);
}

onClose(msg) {
console.info('Connection closed', msg);
}

send(message) {
this._ws.send(message);
}

sendJson(data) {
this.send(JSON.stringify(data));
}

sendPing() {
console.info('Sending PING...');
this.lastPingTimestamp = +new Date();
this._reconnectIfPongNotReceived();
this.sendJson({
type: 'PING',
});
}

_reconnectIfPongNotReceived() {
this.pongTimeout = setTimeout(() => {
console.error('PONG has not been received!');
this.reconnect();
}, 10 * 1000);
}

_handleMessagePong(data) {
this.lastPongTimestamp = +new Date();
console.info('Received PONG in %fms', this.lastPongTimestamp - this.lastPingTimestamp);
clearTimeout(this.pongTimeout);
}

_handleMessageReconnect() {
const secondsBeforeReboot = 30;
console.warn(`Server is about to restart in ~${secondsBeforeReboot} seconds...`);
setTimeout(() => {
this.reconnect();
}, secondsBeforeReboot * 1000);
}
}

Back to list