mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
make deps optional + bug fixes
This commit is contained in:
@@ -37,11 +37,11 @@ const makeAuthSocket = (config: SocketConfig) => {
|
||||
}
|
||||
}
|
||||
})
|
||||
const { socketEvents } = socket
|
||||
const { ws } = socket
|
||||
let curveKeys: CurveKeyPair
|
||||
let initTimeout: NodeJS.Timeout
|
||||
// add close listener
|
||||
socketEvents.on('ws-close', (error: Boom | Error) => {
|
||||
ws.on('ws-close', (error: Boom | Error) => {
|
||||
logger.info({ error }, 'Closed connection to WhatsApp')
|
||||
initTimeout && clearTimeout(initTimeout)
|
||||
// if no reconnects occur
|
||||
@@ -239,7 +239,7 @@ const makeAuthSocket = (config: SocketConfig) => {
|
||||
})
|
||||
ev.emit('credentials.update', auth)
|
||||
}
|
||||
socketEvents.once('ws-open', async() => {
|
||||
ws.once('open', async() => {
|
||||
try {
|
||||
await onOpen()
|
||||
} catch(error) {
|
||||
|
||||
@@ -156,8 +156,6 @@ const makeChatsSocket = (config: SocketConfig) => {
|
||||
logger.error(`error in sending init queries: ${error}`)
|
||||
}
|
||||
})
|
||||
// this persists through socket connections
|
||||
// as conn & getSocket share the same eventemitter
|
||||
socketEvents.on('CB:response,type:chat', async ({ data }: BinaryNode) => {
|
||||
chatsDebounceTimeout.cancel()
|
||||
if(Array.isArray(data)) {
|
||||
@@ -171,7 +169,7 @@ const makeChatsSocket = (config: SocketConfig) => {
|
||||
})
|
||||
|
||||
logger.info(`got ${chats.length} chats`)
|
||||
ev.emit('chats.upsert', { chats, type: 'set' })
|
||||
ev.emit('chats.set', { chats })
|
||||
}
|
||||
})
|
||||
// got all contacts from phone
|
||||
@@ -184,7 +182,7 @@ const makeChatsSocket = (config: SocketConfig) => {
|
||||
})
|
||||
|
||||
logger.info(`got ${contacts.length} contacts`)
|
||||
ev.emit('contacts.upsert', { contacts, type: 'set' })
|
||||
ev.emit('contacts.set', { contacts })
|
||||
}
|
||||
})
|
||||
// status updates
|
||||
@@ -237,7 +235,7 @@ const makeChatsSocket = (config: SocketConfig) => {
|
||||
const user = node[1] as Contact
|
||||
user.jid = whatsappID(user.jid)
|
||||
|
||||
ev.emit('contacts.upsert', { contacts: [user], type: 'upsert' })
|
||||
ev.emit('contacts.upsert', [user])
|
||||
}
|
||||
})
|
||||
|
||||
@@ -251,7 +249,7 @@ const makeChatsSocket = (config: SocketConfig) => {
|
||||
socketEvents.on('CB:Blocklist', json => {
|
||||
json = json[1]
|
||||
const blocklist = json.blocklist
|
||||
ev.emit('blocklist.update', { blocklist, type: 'set' })
|
||||
ev.emit('blocklist.set', { blocklist })
|
||||
})
|
||||
|
||||
return {
|
||||
|
||||
@@ -143,17 +143,14 @@ const makeGroupsSocket = (config: SocketConfig) => {
|
||||
metadata = await groupMetadataFull(gid)
|
||||
logger.warn (`group ID switched from ${gid} to ${response.gid}`)
|
||||
}
|
||||
ev.emit('chats.upsert', {
|
||||
chats: [
|
||||
{
|
||||
jid: response.gid,
|
||||
name: title,
|
||||
t: unixTimestampSeconds(),
|
||||
count: 0
|
||||
}
|
||||
],
|
||||
type: 'upsert'
|
||||
})
|
||||
ev.emit('chats.upsert', [
|
||||
{
|
||||
jid: response.gid,
|
||||
name: title,
|
||||
t: unixTimestampSeconds(),
|
||||
count: 0
|
||||
}
|
||||
])
|
||||
return metadata
|
||||
},
|
||||
/**
|
||||
|
||||
@@ -95,6 +95,8 @@ export const makeSocket = ({
|
||||
return tag
|
||||
}
|
||||
const end = (error: Error | undefined) => {
|
||||
logger.debug({ error }, 'connection closed')
|
||||
|
||||
ws.removeAllListeners('close')
|
||||
ws.removeAllListeners('error')
|
||||
ws.removeAllListeners('open')
|
||||
@@ -105,9 +107,11 @@ export const makeSocket = ({
|
||||
clearPhoneCheckInterval()
|
||||
|
||||
if(ws.readyState !== ws.CLOSED && ws.readyState !== ws.CLOSING) {
|
||||
socketEvents.emit('ws-close', error)
|
||||
try { ws.close() } catch { }
|
||||
}
|
||||
ws.emit('ws-close', error)
|
||||
// so it cannot be re-emitted
|
||||
ws.removeAllListeners('ws-close')
|
||||
}
|
||||
const onMessageRecieved = (message: string | Buffer) => {
|
||||
if(message[0] === '!') {
|
||||
@@ -221,7 +225,8 @@ export const makeSocket = ({
|
||||
onErr = err => reject(err || new Boom('Connection Closed', { statusCode: 429 }))
|
||||
|
||||
socketEvents.on(`TAG:${tag}`, onRecv)
|
||||
socketEvents.on('ws-close', onErr) // if the socket closes, you'll never receive the message
|
||||
ws.on('close', onErr) // if the socket closes, you'll never receive the message
|
||||
ws.on('error', onErr)
|
||||
},
|
||||
)
|
||||
return result as any
|
||||
@@ -230,7 +235,8 @@ export const makeSocket = ({
|
||||
cancelPhoneChecker && cancelPhoneChecker()
|
||||
|
||||
socketEvents.off(`TAG:${tag}`, onRecv)
|
||||
socketEvents.off(`ws-close`, onErr)
|
||||
ws.off('close', onErr) // if the socket closes, you'll never receive the message
|
||||
ws.off('error', onErr)
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -290,21 +296,21 @@ export const makeSocket = ({
|
||||
await new Promise((resolve, reject) => {
|
||||
onOpen = () => resolve(undefined)
|
||||
onClose = reject
|
||||
socketEvents.on('ws-open', onOpen)
|
||||
socketEvents.on('ws-close', onClose)
|
||||
ws.on('open', onOpen)
|
||||
ws.on('close', onClose)
|
||||
ws.on('error', onClose)
|
||||
})
|
||||
.finally(() => {
|
||||
socketEvents.off('ws-open', onOpen)
|
||||
socketEvents.off('ws-close', onClose)
|
||||
socketEvents.off('open', onOpen)
|
||||
socketEvents.off('close', onClose)
|
||||
socketEvents.off('error', onClose)
|
||||
})
|
||||
}
|
||||
|
||||
ws.on('message', onMessageRecieved)
|
||||
ws.on('open', () => {
|
||||
startKeepAliveRequest()
|
||||
|
||||
logger.info('Opened WS connection to WhatsApp Web')
|
||||
socketEvents.emit('ws-open')
|
||||
})
|
||||
ws.on('error', end)
|
||||
ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionLost })))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import KeyedDB from "@adiwajshing/keyed-db"
|
||||
import { Comparable } from "@adiwajshing/keyed-db/lib/Types"
|
||||
import { Logger } from "pino"
|
||||
import type KeyedDB from "@adiwajshing/keyed-db"
|
||||
import type { Comparable } from "@adiwajshing/keyed-db/lib/Types"
|
||||
import type { Logger } from "pino"
|
||||
import type { Connection } from "../Connection"
|
||||
import type { BaileysEventEmitter, Chat, ConnectionState, Contact, GroupMetadata, WAMessage, WAMessageCursor } from "../Types"
|
||||
import { toNumber } from "../Utils"
|
||||
@@ -23,8 +23,8 @@ const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID)
|
||||
export default(
|
||||
{ logger, chatKey }: BaileysInMemoryStoreConfig
|
||||
) => {
|
||||
|
||||
const chats = new KeyedDB<Chat, string>(chatKey, c => c.jid)
|
||||
const KeyedDBConstructor = require('@adiwajshing/keyed-db').default as new (...args: any[]) => KeyedDB<Chat, string>
|
||||
const chats = new KeyedDBConstructor(chatKey, c => c.jid)
|
||||
const messages: { [_: string]: ReturnType<typeof makeMessagesDictionary> } = {}
|
||||
const contacts: { [_: string]: Contact } = {}
|
||||
const groupMetadata: { [_: string]: GroupMetadata } = {}
|
||||
@@ -39,11 +39,8 @@ export default(
|
||||
}
|
||||
|
||||
const listen = (ev: BaileysEventEmitter) => {
|
||||
|
||||
ev.on('connection.update', update => {
|
||||
Object.assign(state, update)
|
||||
})
|
||||
ev.on('contacts.upsert', ({ contacts: newContacts, type }) => {
|
||||
|
||||
const contactsUpsert = (newContacts: Contact[]) => {
|
||||
const oldContacts = new Set(Object.keys(contacts))
|
||||
for(const contact of newContacts) {
|
||||
oldContacts.delete(contact.jid)
|
||||
@@ -52,12 +49,18 @@ export default(
|
||||
contact
|
||||
)
|
||||
}
|
||||
if(type === 'set') {
|
||||
for(const jid of oldContacts) {
|
||||
delete contacts[jid]
|
||||
}
|
||||
logger.debug({ deletedContacts: oldContacts.size }, 'synced contacts')
|
||||
return oldContacts
|
||||
}
|
||||
|
||||
ev.on('connection.update', update => {
|
||||
Object.assign(state, update)
|
||||
})
|
||||
ev.on('contacts.set', ({ contacts: newContacts }) => {
|
||||
const oldContacts = contactsUpsert(newContacts)
|
||||
for(const jid of oldContacts) {
|
||||
delete contacts[jid]
|
||||
}
|
||||
logger.debug({ deletedContacts: oldContacts.size }, 'synced contacts')
|
||||
})
|
||||
ev.on('contacts.update', updates => {
|
||||
for(const update of updates) {
|
||||
@@ -68,13 +71,11 @@ export default(
|
||||
}
|
||||
}
|
||||
})
|
||||
ev.on('chats.upsert', ({ chats: newChats, type }) => {
|
||||
if(type === 'set') {
|
||||
chats.clear()
|
||||
}
|
||||
for(const chat of newChats) {
|
||||
chats.upsert(chat)
|
||||
}
|
||||
ev.on('chats.upsert', newChats => {
|
||||
chats.upsert(...newChats)
|
||||
})
|
||||
ev.on('chats.set', ({ chats: newChats }) => {
|
||||
chats.upsert(...newChats)
|
||||
})
|
||||
ev.on('chats.update', updates => {
|
||||
for(const update of updates) {
|
||||
@@ -101,10 +102,9 @@ export default(
|
||||
list.upsert(msg, 'append')
|
||||
|
||||
if(type === 'notify' && !chats.get(jid)) {
|
||||
ev.emit('chats.upsert', {
|
||||
chats: [ { jid, t: toNumber(msg.messageTimestamp), count: 1 } ],
|
||||
type: 'upsert'
|
||||
})
|
||||
ev.emit('chats.upsert', [
|
||||
{ jid, t: toNumber(msg.messageTimestamp), count: 1 }
|
||||
])
|
||||
}
|
||||
}
|
||||
break
|
||||
@@ -135,9 +135,10 @@ export default(
|
||||
const list = assertMessageList(update.key.remoteJid)
|
||||
const result = list.updateAssign(update)
|
||||
if(!result) {
|
||||
logger.debug({ update }, `got update for non-existant message`)
|
||||
logger.debug({ update }, `got update for non-existent message`)
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
ev.on('messages.delete', item => {
|
||||
const list = assertMessageList(item.jid)
|
||||
|
||||
@@ -50,6 +50,7 @@ const makeOrderedDictionary = function<T>(idGetter: (item: T) => string) {
|
||||
const item = get(idGetter(update as any))
|
||||
if(item) {
|
||||
Object.assign(item, update)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
|
||||
@@ -170,11 +170,13 @@ export type BaileysEventMap = {
|
||||
'connection.update': Partial<ConnectionState>
|
||||
'credentials.update': AuthenticationCredentials
|
||||
|
||||
'chats.upsert': { chats: Chat[], type: 'set' | 'upsert' }
|
||||
'chats.set': { chats: Chat[] }
|
||||
'chats.upsert': Chat[]
|
||||
'chats.update': Partial<Chat>[]
|
||||
'chats.delete': string[]
|
||||
|
||||
'contacts.upsert': { contacts: Contact[], type: 'set' | 'upsert' }
|
||||
'contacts.set': { contacts: Contact[] }
|
||||
'contacts.upsert': Contact[]
|
||||
'contacts.update': Partial<Contact>[]
|
||||
|
||||
'messages.delete': { jid: string, ids: string[] } | { jid: string, all: true }
|
||||
@@ -184,7 +186,8 @@ export type BaileysEventMap = {
|
||||
'groups.update': Partial<GroupMetadata>[]
|
||||
'group-participants.update': { jid: string, participants: string[], action: ParticipantAction }
|
||||
|
||||
'blocklist.update': { blocklist: string[], type: 'add' | 'remove' | 'set' }
|
||||
'blocklist.set': { blocklist: string[] }
|
||||
'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
|
||||
}
|
||||
export interface BaileysEventEmitter extends EventEmitter {
|
||||
on<T extends keyof BaileysEventMap>(event: T, listener: (arg: BaileysEventMap[T]) => void): this
|
||||
|
||||
Reference in New Issue
Block a user