Unified unexpected disconnect & takeover events

This commit is contained in:
Adhiraj
2020-07-13 16:32:52 +05:30
parent 8b859b9376
commit d87e4e5897
5 changed files with 28 additions and 43 deletions

View File

@@ -51,7 +51,13 @@ export default class WAConnectionBase {
protected decoder = new Decoder()
/** What to do when you need the phone to authenticate the connection (generate QR code by default) */
onReadyForPhoneAuthentication = generateQRCode
unexpectedDisconnect = (err) => this.close()
unexpectedDisconnect = (err: string) => this.close()
/** Set the callback for unexpected disconnects including take over events, log out events etc. */
setOnUnexpectedDisconnect(callback: (error: string) => void) {
this.registerCallback (['Cmd', 'type:disconnect'], json => this.unexpectedDisconnect(json[1].kind))
this.unexpectedDisconnect = err => { this.close(); callback(err) }
}
/**
* base 64 encode the authentication credentials and return them
* these can then be used to login again by passing the object to the connect () function.

View File

@@ -39,18 +39,19 @@ export default class WAConnectionConnector extends WAConnectionValidator {
this.log('connected to WhatsApp Web, authenticating...')
// start sending keep alive requests (keeps the WebSocket alive & updates our last seen)
this.authenticate()
.then((user) => {
this.startKeepAliveRequest()
resolve(user)
})
.catch(reject)
})
this.conn.on('message', (m) => this.onMessageRecieved(m)) // in WhatsAppWeb.Recv.js
this.conn.on('error', (error) => {
// if there was an error in the WebSocket
this.close()
reject(error)
.then(user => {
this.startKeepAliveRequest()
this.conn.on ('error', null)
this.conn.on ('close', () => this.unexpectedDisconnect ('closed'))
resolve(user)
})
.catch(reject)
})
this.conn.on('message', m => this.onMessageRecieved(m))
// if there was an error in the WebSocket
this.conn.on('error', error => { this.close(); reject(error) })
})
promise = Utils.promiseTimeout(timeoutMs, promise)
return promise.catch(err => {

View File

@@ -53,9 +53,7 @@ export function randomBytes(length) {
}
export const createTimeout = (timeout) => new Promise(resolve => setTimeout(resolve, timeout))
export function promiseTimeout<T>(ms: number, promise: Promise<T>) {
if (!ms) {
return promise
}
if (!ms) return promise
// Create a promise that rejects in <ms> milliseconds
const timeout = new Promise((_, reject) => {
const id = setTimeout(() => {