From a04a908b9447cad12d590210d7a18bd7441a7161 Mon Sep 17 00:00:00 2001 From: Adhiraj Date: Thu, 16 Jul 2020 12:52:19 +0530 Subject: [PATCH] Log level update --- Example/example.ts | 2 +- src/WAClient/Base.ts | 4 ++-- src/WAConnection/Base.ts | 15 ++++++++------- src/WAConnection/Connect.ts | 10 +++++----- src/WAConnection/Constants.ts | 5 +++-- src/WAConnection/Validation.ts | 5 +++-- 6 files changed, 22 insertions(+), 19 deletions(-) diff --git a/Example/example.ts b/Example/example.ts index 47dda44..a6a9c10 100644 --- a/Example/example.ts +++ b/Example/example.ts @@ -14,7 +14,7 @@ import * as fs from 'fs' async function example() { const client = new WAClient() // instantiate 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) const [user, chats, contacts, unread] = await client.connect('./auth_info.json', 20 * 1000) diff --git a/src/WAClient/Base.ts b/src/WAClient/Base.ts index 5a38979..7bbfeb8 100644 --- a/src/WAClient/Base.ts +++ b/src/WAClient/Base.ts @@ -41,8 +41,8 @@ export default class WhatsAppWebBase extends WAConnection { if (!message.key.fromMe || callbackOnMyMessages) { // if this message was sent to us, notify callback(message as WAMessage) - } else if (this.logLevel >= MessageLogLevel.unhandled) { - this.log(`[Unhandled] message - ${JSON.stringify(message)}`) + } else { + this.log(`[Unhandled] message - ${JSON.stringify(message)}`, MessageLogLevel.unhandled) } }) } diff --git a/src/WAConnection/Base.ts b/src/WAConnection/Base.ts index ac817f8..50b0a25 100644 --- a/src/WAConnection/Base.ts +++ b/src/WAConnection/Base.ts @@ -30,8 +30,8 @@ export default class WAConnectionBase { /** Should reconnect automatically after an unexpected disconnect */ autoReconnect = true lastSeen: Date = null - /** Log messages that are not handled, so you can debug & see what custom stuff you can implement */ - logLevel: MessageLogLevel = MessageLogLevel.none + /** What level of messages to log to the console */ + logLevel: MessageLogLevel = MessageLogLevel.info /** Should requests be queued when the connection breaks in between; if false, then an error will be thrown */ pendingRequestTimeoutMs: number = null /** 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') } 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 authInfo = JSON.parse(file) as AuthenticationCredentialsBase64 } @@ -115,7 +115,7 @@ export default class WAConnectionBase { if (!authInfo) throw new Error('given authInfo is null') 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 authInfo = JSON.parse(file) as AuthenticationCredentialsBrowser } @@ -177,7 +177,7 @@ export default class WAConnectionBase { delete this.callbacks[func][key][key2] 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 @@ -309,7 +309,8 @@ export default class WAConnectionBase { clearInterval(this.keepAliveReq) } } - protected log(text) { - console.log(`[Baileys][${new Date().toLocaleString()}] ${text}`) + protected log(text, level: MessageLogLevel) { + if (this.logLevel >= level) + console.log(`[Baileys][${new Date().toLocaleString()}] ${text}`) } } diff --git a/src/WAConnection/Connect.ts b/src/WAConnection/Connect.ts index d2be8c3..08783fe 100644 --- a/src/WAConnection/Connect.ts +++ b/src/WAConnection/Connect.ts @@ -34,7 +34,7 @@ export default class WAConnectionConnector extends WAConnectionValidator { const promise: Promise = new Promise((resolve, reject) => { 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) this.authenticate() .then(user => { @@ -73,7 +73,7 @@ export default class WAConnectionConnector extends WAConnectionValidator { let receivedMessages = false 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 = () => new Promise(resolve => { convoResolve = () => { @@ -148,7 +148,7 @@ export default class WAConnectionConnector extends WAConnectionValidator { const [messageTag, json] = decrypted 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 @@ -195,7 +195,7 @@ export default class WAConnectionConnector extends WAConnectionValidator { } } 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 () => { // 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) } } diff --git a/src/WAConnection/Constants.ts b/src/WAConnection/Constants.ts index 310ceff..93fb52e 100644 --- a/src/WAConnection/Constants.ts +++ b/src/WAConnection/Constants.ts @@ -3,8 +3,9 @@ import { proto } from '../../WAMessage/WAMessage' export enum MessageLogLevel { none=0, - unhandled=1, - all=2 + info=1, + unhandled=2, + all=3 } export interface AuthenticationCredentials { clientID: string diff --git a/src/WAConnection/Validation.ts b/src/WAConnection/Validation.ts index 614bd76..4bc92fd 100644 --- a/src/WAConnection/Validation.ts +++ b/src/WAConnection/Validation.ts @@ -1,6 +1,7 @@ import * as Curve from 'curve25519-js' import * as Utils from './Utils' 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)}`) @@ -70,7 +71,7 @@ export default class WAConnectionValidator extends WAConnectionBase { }) .then((json) => { 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 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 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 - this.log('resolving login challenge') + this.log('resolving login challenge', MessageLogLevel.info) 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 */