From f085a9078b96be2d0da641f340bcbc2c88c2e79d Mon Sep 17 00:00:00 2001 From: james58899 Date: Sat, 4 Mar 2023 05:51:16 +0000 Subject: [PATCH] feat(voice): support resuming voice connection --- lib/voice/VoiceConnection.js | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/lib/voice/VoiceConnection.js b/lib/voice/VoiceConnection.js index 678eb9410..61b7a6f5f 100644 --- a/lib/voice/VoiceConnection.js +++ b/lib/voice/VoiceConnection.js @@ -120,6 +120,7 @@ class VoiceConnection extends EventEmitter { this.connectionTimeout = null; this.connecting = false; this.reconnecting = false; + this.resuming = false; this.ready = false; this.sendBuffer = Buffer.allocUnsafe(16 + 32 + MAX_FRAME_SIZE); @@ -199,12 +200,20 @@ class VoiceConnection extends EventEmitter { clearTimeout(this.connectionTimeout); this.connectionTimeout = null; } - this.sendWS(VoiceOPCodes.IDENTIFY, { - server_id: this.id, - user_id: data.user_id, - session_id: data.session_id, - token: data.token - }); + if(this.resuming) { + this.sendWS(VoiceOPCodes.RESUME, { + server_id: this.id, + session_id: data.session_id, + token: data.token + }); + } else { + this.sendWS(VoiceOPCodes.IDENTIFY, { + server_id: this.id, + user_id: data.user_id, + session_id: data.session_id, + token: data.token + }); + } }); this.ws.on("message", (m) => { const packet = JSON.parse(m); @@ -269,6 +278,11 @@ class VoiceConnection extends EventEmitter { this.sendUDPPacket(udpMessage); break; } + case VoiceOPCodes.RESUMED: { + this.connecting = false; + this.resuming = false; + break; + } case VoiceOPCodes.SESSION_DESCRIPTION: { this.mode = packet.d.mode; this.secret = Buffer.from(packet.d.secret_key); @@ -355,6 +369,13 @@ class VoiceConnection extends EventEmitter { this.emit("warn", `Voice WS close ${code}: ${reason}`); if(this.connecting || this.ready) { let reconnecting = true; + if(code < 4000 || code === 4015) { + this.resuming = true; + setTimeout(() => { + this.connect(data); + }, 500).unref(); + return; + } if(code === 4006) { reconnecting = false; } else if(code === 4014) { @@ -383,6 +404,7 @@ class VoiceConnection extends EventEmitter { disconnect(error, reconnecting) { this.connecting = false; this.reconnecting = reconnecting; + this.resuming = false; this.ready = false; this.speaking = false; this.timestamp = 0;