Log level update

This commit is contained in:
Adhiraj
2020-07-16 12:52:19 +05:30
parent 92cb5023a6
commit a04a908b94
6 changed files with 22 additions and 19 deletions

View File

@@ -14,7 +14,7 @@ import * as fs from 'fs'
async function example() { async function example() {
const client = new WAClient() // instantiate const client = new WAClient() // instantiate
client.autoReconnect = true // auto reconnect on disconnect client.autoReconnect = true // auto reconnect on disconnect
client.logLevel = MessageLogLevel.none // set to unhandled to see what kind of stuff you can implement client.logLevel = MessageLogLevel.info // set to unhandled to see what kind of stuff you can implement
// connect or timeout in 20 seconds (loads the auth file credentials if present) // connect or timeout in 20 seconds (loads the auth file credentials if present)
const [user, chats, contacts, unread] = await client.connect('./auth_info.json', 20 * 1000) const [user, chats, contacts, unread] = await client.connect('./auth_info.json', 20 * 1000)

View File

@@ -41,8 +41,8 @@ export default class WhatsAppWebBase extends WAConnection {
if (!message.key.fromMe || callbackOnMyMessages) { if (!message.key.fromMe || callbackOnMyMessages) {
// if this message was sent to us, notify // if this message was sent to us, notify
callback(message as WAMessage) callback(message as WAMessage)
} else if (this.logLevel >= MessageLogLevel.unhandled) { } else {
this.log(`[Unhandled] message - ${JSON.stringify(message)}`) this.log(`[Unhandled] message - ${JSON.stringify(message)}`, MessageLogLevel.unhandled)
} }
}) })
} }

View File

@@ -30,8 +30,8 @@ export default class WAConnectionBase {
/** Should reconnect automatically after an unexpected disconnect */ /** Should reconnect automatically after an unexpected disconnect */
autoReconnect = true autoReconnect = true
lastSeen: Date = null lastSeen: Date = null
/** Log messages that are not handled, so you can debug & see what custom stuff you can implement */ /** What level of messages to log to the console */
logLevel: MessageLogLevel = MessageLogLevel.none logLevel: MessageLogLevel = MessageLogLevel.info
/** Should requests be queued when the connection breaks in between; if false, then an error will be thrown */ /** Should requests be queued when the connection breaks in between; if false, then an error will be thrown */
pendingRequestTimeoutMs: number = null pendingRequestTimeoutMs: number = null
/** What to do when you need the phone to authenticate the connection (generate QR code by default) */ /** What to do when you need the phone to authenticate the connection (generate QR code by default) */
@@ -95,7 +95,7 @@ export default class WAConnectionBase {
throw new Error('given authInfo is null') throw new Error('given authInfo is null')
} }
if (typeof authInfo === 'string') { if (typeof authInfo === 'string') {
this.log(`loading authentication credentials from ${authInfo}`) this.log(`loading authentication credentials from ${authInfo}`, MessageLogLevel.info)
const file = fs.readFileSync(authInfo, { encoding: 'utf-8' }) // load a closed session back if it exists const file = fs.readFileSync(authInfo, { encoding: 'utf-8' }) // load a closed session back if it exists
authInfo = JSON.parse(file) as AuthenticationCredentialsBase64 authInfo = JSON.parse(file) as AuthenticationCredentialsBase64
} }
@@ -115,7 +115,7 @@ export default class WAConnectionBase {
if (!authInfo) throw new Error('given authInfo is null') if (!authInfo) throw new Error('given authInfo is null')
if (typeof authInfo === 'string') { if (typeof authInfo === 'string') {
this.log(`loading authentication credentials from ${authInfo}`) this.log(`loading authentication credentials from ${authInfo}`, MessageLogLevel.info)
const file = fs.readFileSync(authInfo, { encoding: 'utf-8' }) // load a closed session back if it exists const file = fs.readFileSync(authInfo, { encoding: 'utf-8' }) // load a closed session back if it exists
authInfo = JSON.parse(file) as AuthenticationCredentialsBrowser authInfo = JSON.parse(file) as AuthenticationCredentialsBrowser
} }
@@ -177,7 +177,7 @@ export default class WAConnectionBase {
delete this.callbacks[func][key][key2] delete this.callbacks[func][key][key2]
return return
} }
this.log('WARNING: could not find ' + JSON.stringify(parameters) + ' to deregister') this.log('WARNING: could not find ' + JSON.stringify(parameters) + ' to deregister', MessageLogLevel.info)
} }
/** /**
* Wait for a message with a certain tag to be received * Wait for a message with a certain tag to be received
@@ -309,7 +309,8 @@ export default class WAConnectionBase {
clearInterval(this.keepAliveReq) clearInterval(this.keepAliveReq)
} }
} }
protected log(text) { protected log(text, level: MessageLogLevel) {
console.log(`[Baileys][${new Date().toLocaleString()}] ${text}`) if (this.logLevel >= level)
console.log(`[Baileys][${new Date().toLocaleString()}] ${text}`)
} }
} }

View File

@@ -34,7 +34,7 @@ export default class WAConnectionConnector extends WAConnectionValidator {
const promise: Promise<UserMetaData> = new Promise((resolve, reject) => { const promise: Promise<UserMetaData> = new Promise((resolve, reject) => {
this.conn.on('open', () => { this.conn.on('open', () => {
this.log('connected to WhatsApp Web, authenticating...') this.log('connected to WhatsApp Web, authenticating...', MessageLogLevel.info)
// start sending keep alive requests (keeps the WebSocket alive & updates our last seen) // start sending keep alive requests (keeps the WebSocket alive & updates our last seen)
this.authenticate() this.authenticate()
.then(user => { .then(user => {
@@ -73,7 +73,7 @@ export default class WAConnectionConnector extends WAConnectionValidator {
let receivedMessages = false let receivedMessages = false
let convoResolve let convoResolve
this.log('waiting for chats & contacts') // wait for the message with chats this.log('waiting for chats & contacts', MessageLogLevel.info) // wait for the message with chats
const waitForConvos = () => const waitForConvos = () =>
new Promise(resolve => { new Promise(resolve => {
convoResolve = () => { convoResolve = () => {
@@ -148,7 +148,7 @@ export default class WAConnectionConnector extends WAConnectionValidator {
const [messageTag, json] = decrypted const [messageTag, json] = decrypted
if (this.logLevel === MessageLogLevel.all) { if (this.logLevel === MessageLogLevel.all) {
this.log(messageTag + ', ' + JSON.stringify(json)) this.log(messageTag + ', ' + JSON.stringify(json), MessageLogLevel.all)
} }
/* /*
Check if this is a response to a message we sent Check if this is a response to a message we sent
@@ -195,7 +195,7 @@ export default class WAConnectionConnector extends WAConnectionValidator {
} }
} }
if (this.logLevel === MessageLogLevel.unhandled) { if (this.logLevel === MessageLogLevel.unhandled) {
this.log('[Unhandled] ' + messageTag + ', ' + JSON.stringify(json)) this.log('[Unhandled] ' + messageTag + ', ' + JSON.stringify(json), MessageLogLevel.unhandled)
} }
} }
} }
@@ -215,7 +215,7 @@ export default class WAConnectionConnector extends WAConnectionValidator {
reconnectLoop = async () => { reconnectLoop = async () => {
// attempt reconnecting if the user wants us to // attempt reconnecting if the user wants us to
this.log('network is down, reconnecting...') this.log('network is down, reconnecting...', MessageLogLevel.info)
return this.connectSlim(null, 25*1000).catch(this.reconnectLoop) return this.connectSlim(null, 25*1000).catch(this.reconnectLoop)
} }
} }

View File

@@ -3,8 +3,9 @@ import { proto } from '../../WAMessage/WAMessage'
export enum MessageLogLevel { export enum MessageLogLevel {
none=0, none=0,
unhandled=1, info=1,
all=2 unhandled=2,
all=3
} }
export interface AuthenticationCredentials { export interface AuthenticationCredentials {
clientID: string clientID: string

View File

@@ -1,6 +1,7 @@
import * as Curve from 'curve25519-js' import * as Curve from 'curve25519-js'
import * as Utils from './Utils' import * as Utils from './Utils'
import WAConnectionBase from './Base' import WAConnectionBase from './Base'
import { MessageLogLevel } from './Constants'
const StatusError = (message: any, description: string='unknown error') => new Error (`unexpected status: ${message.status} on JSON: ${JSON.stringify(message)}`) const StatusError = (message: any, description: string='unknown error') => new Error (`unexpected status: ${message.status} on JSON: ${JSON.stringify(message)}`)
@@ -70,7 +71,7 @@ export default class WAConnectionValidator extends WAConnectionBase {
}) })
.then((json) => { .then((json) => {
this.validateNewConnection(json[1]) // validate the connection this.validateNewConnection(json[1]) // validate the connection
this.log('validated connection successfully') this.log('validated connection successfully', MessageLogLevel.info)
this.lastSeen = new Date() // set last seen to right now this.lastSeen = new Date() // set last seen to right now
return this.userMetaData return this.userMetaData
}) })
@@ -156,7 +157,7 @@ export default class WAConnectionValidator extends WAConnectionBase {
const bytes = Buffer.from(challenge, 'base64') // decode the base64 encoded challenge string const bytes = Buffer.from(challenge, 'base64') // decode the base64 encoded challenge string
const signed = Utils.hmacSign(bytes, this.authInfo.macKey).toString('base64') // sign the challenge string with our macKey const signed = Utils.hmacSign(bytes, this.authInfo.macKey).toString('base64') // sign the challenge string with our macKey
const data = ['admin', 'challenge', signed, this.authInfo.serverToken, this.authInfo.clientID] // prepare to send this signed string with the serverToken & clientID const data = ['admin', 'challenge', signed, this.authInfo.serverToken, this.authInfo.clientID] // prepare to send this signed string with the serverToken & clientID
this.log('resolving login challenge') this.log('resolving login challenge', MessageLogLevel.info)
return this.query(data) return this.query(data)
} }
/** When starting a new session, generate a QR code by generating a private/public key pair & the keys the server sends */ /** When starting a new session, generate a QR code by generating a private/public key pair & the keys the server sends */