Skip to content

Commit

Permalink
fix: wrong behaviour to some close codes
Browse files Browse the repository at this point in the history
This commit fixes the behaviour to some close codes, not reconnecting where it should.
  • Loading branch information
ThePedroo committed Jan 9, 2024
1 parent 0e8b96e commit 5393ca3
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 7 deletions.
26 changes: 22 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ const MAX_NONCE = 2 ** 32 - 1
const MAX_TIMESTAMP = 2 ** 32
const MAX_SEQUENCE = 2 ** 16
const ENCRYPTION_MODE = 'xsalsa20_poly1305_lite'
const DISCORD_CLOSE_CODES = {
4004: { message: 'Authentication failed.' },
4006: { message: 'Session no longer valid.' },
4009: { message: 'Session timeout.' },
4011: { message: 'Server not found.' },
4014: { message: 'Disconnected.', error: false },
4015: { message: 'Voice server crashed.', reconnect: true },
}

const ssrcs = {}

Expand Down Expand Up @@ -269,12 +277,22 @@ class Connection extends EventEmitter {
this.ws.on('close', (code) => {
if (!this.ws) return;

this._destroy({ status: 'disconnected', reason: 'websocketClose', code })
const closeCode = DISCORD_CLOSE_CODES[code]

if (closeCode.reconnect) {
this._updateState({ status: 'disconnected', reason: 'websocketClose', code })
this._updatePlayerState({ status: 'idle' })

this.emit('reconnecting', closeCode.message)

if (code == 4015) {
this.connect(null, true)
this.connect(() => this.unpause(), true)
} else {
this.emit('error', new Error(`WebSocket closed unexpectadly: ${code}`))
this._destroy({ status: 'disconnected', reason: 'websocketClose', code })

if (closeCode.error !== false)
this.emit('error', new Error(closeCode.message))

return;
}
})

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@performanc/voice",
"version": "1.0.2",
"version": "1.0.3",
"description": "Performant Discord voice API client for ES6 Node.js",
"main": "index.js",
"type": "module",
Expand Down
1 change: 1 addition & 0 deletions ws.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ class WebSocket extends EventEmitter {
const reason = headers.buffer.subarray(2).toString('utf-8')

this.emit('close', code, reason)
socket.removeAllListeners('close')
}

socket.end()
Expand Down

0 comments on commit 5393ca3

Please sign in to comment.