@zervonexx/baileys 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -22
- package/README.md +4112 -4112
- package/WAProto/WAProtoCompile.js +322 -322
- package/WAProto/fetcher.js +67 -67
- package/WAProto/index.js +95 -95
- package/WAProto/parser.js +333 -333
- package/lib/Builders/AIRich.js +673 -673
- package/lib/Builders/auto.js +49 -49
- package/lib/Builders/base.js +144 -144
- package/lib/Builders/builders.js +588 -588
- package/lib/Builders/index.js +3 -3
- package/lib/Defaults/index.js +248 -248
- package/lib/Signal/index.js +2 -2
- package/lib/Signal/libsignal.js +526 -526
- package/lib/Signal/lid-mapping.js +282 -282
- package/lib/Socket/Client/index.js +1 -1
- package/lib/Socket/Client/types.js +9 -9
- package/lib/Socket/Client/websocket.js +83 -83
- package/lib/Socket/business.js +151 -151
- package/lib/Socket/chats.js +854 -854
- package/lib/Socket/communities.js +146 -146
- package/lib/Socket/groups.js +293 -293
- package/lib/Socket/index.js +14 -14
- package/lib/Socket/messages-recv.js +993 -993
- package/lib/Socket/messages-send.js +722 -722
- package/lib/Socket/mex.js +33 -33
- package/lib/Socket/newsletter.js +783 -783
- package/lib/Socket/registration.js +154 -154
- package/lib/Socket/socket.js +797 -797
- package/lib/Socket/spam-report.js +143 -143
- package/lib/Socket/username.js +81 -81
- package/lib/Socket/zervonex-handler.js +57 -57
- package/lib/Store/index.js +6 -6
- package/lib/Store/make-cache-manager-store.js +80 -80
- package/lib/Store/make-in-memory-store.js +426 -426
- package/lib/Store/make-ordered-dictionary.js +81 -81
- package/lib/Store/object-repository.js +30 -30
- package/lib/Store/reporting-info-store.js +37 -37
- package/lib/Types/Auth.js +1 -1
- package/lib/Types/Bussines.js +1 -1
- package/lib/Types/Call.js +1 -1
- package/lib/Types/Chat.js +7 -7
- package/lib/Types/Contact.js +1 -1
- package/lib/Types/Events.js +1 -1
- package/lib/Types/GroupMetadata.js +1 -1
- package/lib/Types/Label.js +24 -24
- package/lib/Types/LabelAssociation.js +6 -6
- package/lib/Types/Message.js +14 -14
- package/lib/Types/Newsletter.js +99 -99
- package/lib/Types/Product.js +1 -1
- package/lib/Types/Signal.js +1 -1
- package/lib/Types/Socket.js +14 -14
- package/lib/Types/State.js +26 -26
- package/lib/Types/USync.js +1 -1
- package/lib/Types/index.js +30 -30
- package/lib/Utils/auth-utils.js +159 -159
- package/lib/Utils/baileys-event-stream.js +32 -32
- package/lib/Utils/bot-capabilities.js +40 -40
- package/lib/Utils/bot-planning-replay.js +43 -43
- package/lib/Utils/browser-utils.js +29 -29
- package/lib/Utils/business.js +74 -74
- package/lib/Utils/chat-utils.js +316 -316
- package/lib/Utils/companion-reg-client-utils.js +19 -19
- package/lib/Utils/consumer-application.js +37 -37
- package/lib/Utils/crypto.js +52 -52
- package/lib/Utils/cstoken.js +14 -14
- package/lib/Utils/decode-wa-message.js +199 -199
- package/lib/Utils/event-buffer.js +272 -272
- package/lib/Utils/extras.js +186 -186
- package/lib/Utils/generics.js +194 -194
- package/lib/Utils/history.js +50 -50
- package/lib/Utils/identity-change-handler.js +18 -18
- package/lib/Utils/index.js +40 -40
- package/lib/Utils/link-preview.js +50 -50
- package/lib/Utils/logger.js +2 -2
- package/lib/Utils/lt-hash.js +3 -3
- package/lib/Utils/make-mutex.js +15 -15
- package/lib/Utils/message-composer.js +61 -61
- package/lib/Utils/message-retry-manager.js +47 -47
- package/lib/Utils/messages-media.js +501 -501
- package/lib/Utils/messages.js +942 -942
- package/lib/Utils/meta-ai-msmsg.js +121 -121
- package/lib/Utils/meta-compositing.js +74 -74
- package/lib/Utils/modern-messages.js +234 -234
- package/lib/Utils/native-flow.js +80 -80
- package/lib/Utils/noise-handler.js +160 -160
- package/lib/Utils/pre-key-manager.js +75 -75
- package/lib/Utils/process-message.js +400 -400
- package/lib/Utils/reporting-utils.js +170 -170
- package/lib/Utils/signal.js +166 -166
- package/lib/Utils/spam-report-utils.js +165 -165
- package/lib/Utils/sync-action-utils.js +33 -33
- package/lib/Utils/tc-token-utils.js +153 -153
- package/lib/Utils/use-keyv-auth-state.js +199 -199
- package/lib/Utils/use-multi-file-auth-state.js +83 -83
- package/lib/Utils/validate-connection.js +171 -171
- package/lib/WABinary/constants.js +1320 -1320
- package/lib/WABinary/decode.js +151 -151
- package/lib/WABinary/encode.js +139 -139
- package/lib/WABinary/generic-utils.js +202 -202
- package/lib/WABinary/index.js +6 -6
- package/lib/WABinary/jid-utils.js +235 -235
- package/lib/WABinary/types.js +4 -4
- package/lib/WAM/BinaryInfo.js +9 -9
- package/lib/WAM/constants.js +22852 -22852
- package/lib/WAM/encode.js +149 -149
- package/lib/WAM/index.js +3 -3
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
- package/lib/WAUSync/Protocols/index.js +12 -12
- package/lib/WAUSync/USyncQuery.js +88 -88
- package/lib/WAUSync/USyncUser.js +20 -20
- package/lib/WAUSync/index.js +3 -3
- package/lib/index.js +66 -66
- package/package.json +191 -192
|
@@ -1,273 +1,273 @@
|
|
|
1
|
-
import EventEmitter from 'events'
|
|
2
|
-
import { WAMessageStatus } from '../Types/index.js'
|
|
3
|
-
import { trimUndefined } from './generics.js'
|
|
4
|
-
import { updateMessageWithReaction, updateMessageWithReceipt } from './messages.js'
|
|
5
|
-
import { isRealMessage, shouldIncrementChatUnread } from './process-message.js'
|
|
6
|
-
|
|
7
|
-
const BUFFERABLE_EVENT = ['messaging-history.set', 'chats.upsert', 'chats.update', 'chats.delete', 'contacts.upsert', 'contacts.update', 'messages.upsert', 'messages.update', 'messages.delete', 'messages.reaction', 'message-receipt.update', 'groups.update']
|
|
8
|
-
const BUFFERABLE_EVENT_SET = new Set(BUFFERABLE_EVENT)
|
|
9
|
-
|
|
10
|
-
const BUFFER_TIMEOUT_MS = 30000
|
|
11
|
-
const MAX_HISTORY_CACHE_SIZE = 10000
|
|
12
|
-
|
|
13
|
-
const makeBufferData = () => ({
|
|
14
|
-
historySets: { chats: {}, messages: {}, contacts: {}, isLatest: false, empty: true },
|
|
15
|
-
chatUpserts: {}, chatUpdates: {}, chatDeletes: new Set(),
|
|
16
|
-
contactUpserts: {}, contactUpdates: {},
|
|
17
|
-
messageUpserts: {}, messageUpdates: {}, messageReactions: {}, messageDeletes: {}, messageReceipts: {},
|
|
18
|
-
groupUpdates: {}
|
|
19
|
-
})
|
|
20
|
-
|
|
21
|
-
const stringifyMessageKey = key => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`
|
|
22
|
-
|
|
23
|
-
export const makeEventBuffer = logger => {
|
|
24
|
-
const ev = new EventEmitter()
|
|
25
|
-
const historyCache = new Set()
|
|
26
|
-
let data = makeBufferData()
|
|
27
|
-
let isBuffering = false
|
|
28
|
-
let bufferTimeout = null
|
|
29
|
-
let bufferCount = 0
|
|
30
|
-
|
|
31
|
-
ev.on('event', map => { for (const event in map) ev.emit(event, map[event]) })
|
|
32
|
-
|
|
33
|
-
function buffer() {
|
|
34
|
-
bufferCount++
|
|
35
|
-
if (isBuffering) return
|
|
36
|
-
logger.debug('Event buffer activated')
|
|
37
|
-
isBuffering = true
|
|
38
|
-
if (bufferTimeout) clearTimeout(bufferTimeout)
|
|
39
|
-
bufferTimeout = setTimeout(() => { if (isBuffering) { logger.warn('Buffer timeout reached, auto-flushing'); flush() } }, BUFFER_TIMEOUT_MS)
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function flush() {
|
|
43
|
-
if (!isBuffering) return false
|
|
44
|
-
logger.debug({ bufferCount }, 'Flushing event buffer')
|
|
45
|
-
isBuffering = false
|
|
46
|
-
bufferCount = 0
|
|
47
|
-
if (bufferTimeout) { clearTimeout(bufferTimeout); bufferTimeout = null }
|
|
48
|
-
if (historyCache.size > MAX_HISTORY_CACHE_SIZE) { logger.debug({ cacheSize: historyCache.size }, 'Clearing history cache'); historyCache.clear() }
|
|
49
|
-
const newData = makeBufferData()
|
|
50
|
-
for (const update of Object.values(data.chatUpdates)) {
|
|
51
|
-
if (update.conditional) { newData.chatUpdates[update.id] = update; delete data.chatUpdates[update.id] }
|
|
52
|
-
}
|
|
53
|
-
const consolidated = consolidateEvents(data)
|
|
54
|
-
if (Object.keys(consolidated).length) ev.emit('event', consolidated)
|
|
55
|
-
data = newData
|
|
56
|
-
logger.trace({ conditionalChatUpdatesLeft: Object.keys(newData.chatUpdates).length }, 'released buffered events')
|
|
57
|
-
return true
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
return {
|
|
61
|
-
process(handler) {
|
|
62
|
-
ev.on('event', handler)
|
|
63
|
-
return () => ev.off('event', handler)
|
|
64
|
-
},
|
|
65
|
-
emit(event, evData) {
|
|
66
|
-
if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) { append(data, historyCache, event, evData, logger); return true }
|
|
67
|
-
return ev.emit('event', { [event]: evData })
|
|
68
|
-
},
|
|
69
|
-
isBuffering: () => isBuffering,
|
|
70
|
-
buffer,
|
|
71
|
-
flush,
|
|
72
|
-
createBufferedFunction(work) {
|
|
73
|
-
return async (...args) => {
|
|
74
|
-
buffer()
|
|
75
|
-
try {
|
|
76
|
-
const result = await work(...args)
|
|
77
|
-
if (bufferCount === 1) setTimeout(() => { if (isBuffering && bufferCount === 1) flush() }, 100)
|
|
78
|
-
return result
|
|
79
|
-
} finally {
|
|
80
|
-
bufferCount = Math.max(0, bufferCount - 1)
|
|
81
|
-
if (bufferCount === 0) setTimeout(flush, 100)
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
},
|
|
85
|
-
on: (...args) => ev.on(...args),
|
|
86
|
-
off: (...args) => ev.off(...args),
|
|
87
|
-
listener: eventName => ev.listenerCount(eventName),
|
|
88
|
-
removeAllListeners: (...args) => ev.removeAllListeners(...args)
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function append(data, historyCache, event, eventData, logger) {
|
|
93
|
-
function absorbingChatUpdate(existing) {
|
|
94
|
-
const chatId = existing.id || ''
|
|
95
|
-
const update = data.chatUpdates[chatId]
|
|
96
|
-
if (!update) return
|
|
97
|
-
const conditionMatches = update.conditional ? update.conditional(data) : true
|
|
98
|
-
if (conditionMatches) { delete update.conditional; logger.debug({ chatId }, 'absorbed chat update in existing chat'); Object.assign(existing, concatChats(update, existing)); delete data.chatUpdates[chatId] }
|
|
99
|
-
else if (conditionMatches === false) { logger.debug({ chatId }, 'chat update condition fail, removing'); delete data.chatUpdates[chatId] }
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function decrementChatReadCounterIfMsgDidUnread(message) {
|
|
103
|
-
const chatId = message.key.remoteJid
|
|
104
|
-
const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId]
|
|
105
|
-
if (isRealMessage(message) && shouldIncrementChatUnread(message) && typeof chat?.unreadCount === 'number' && chat.unreadCount > 0) {
|
|
106
|
-
logger.debug({ chatId: chat.id }, 'decrementing chat counter')
|
|
107
|
-
chat.unreadCount -= 1
|
|
108
|
-
if (chat.unreadCount === 0) delete chat.unreadCount
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
switch (event) {
|
|
113
|
-
case 'messaging-history.set':
|
|
114
|
-
for (const chat of eventData.chats) {
|
|
115
|
-
const id = chat.id || ''
|
|
116
|
-
const existing = data.historySets.chats[id]
|
|
117
|
-
if (existing) existing.endOfHistoryTransferType = chat.endOfHistoryTransferType
|
|
118
|
-
else if (!historyCache.has(id)) { data.historySets.chats[id] = chat; historyCache.add(id); absorbingChatUpdate(chat) }
|
|
119
|
-
}
|
|
120
|
-
for (const contact of eventData.contacts) {
|
|
121
|
-
const existing = data.historySets.contacts[contact.id]
|
|
122
|
-
if (existing) Object.assign(existing, trimUndefined(contact))
|
|
123
|
-
else {
|
|
124
|
-
const hid = `c:${contact.id}`
|
|
125
|
-
if (!historyCache.has(hid) || contact.notify || contact.name || contact.verifiedName) { data.historySets.contacts[contact.id] = contact; historyCache.add(hid) }
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
for (const message of eventData.messages) {
|
|
129
|
-
const key = stringifyMessageKey(message.key)
|
|
130
|
-
if (!data.historySets.messages[key] && !historyCache.has(key)) { data.historySets.messages[key] = message; historyCache.add(key) }
|
|
131
|
-
}
|
|
132
|
-
data.historySets.empty = false
|
|
133
|
-
data.historySets.syncType = eventData.syncType
|
|
134
|
-
data.historySets.progress = eventData.progress
|
|
135
|
-
data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId
|
|
136
|
-
data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest
|
|
137
|
-
break
|
|
138
|
-
case 'chats.upsert':
|
|
139
|
-
for (const chat of eventData) {
|
|
140
|
-
const id = chat.id || ''
|
|
141
|
-
let upsert = data.chatUpserts[id]
|
|
142
|
-
if (id && !upsert) { upsert = data.historySets.chats[id]; if (upsert) logger.debug({ chatId: id }, 'absorbed chat upsert in chat set') }
|
|
143
|
-
upsert = upsert ? concatChats(upsert, chat) : chat
|
|
144
|
-
data.chatUpserts[id] = upsert
|
|
145
|
-
absorbingChatUpdate(upsert)
|
|
146
|
-
data.chatDeletes.delete(id)
|
|
147
|
-
}
|
|
148
|
-
break
|
|
149
|
-
case 'chats.update':
|
|
150
|
-
for (const update of eventData) {
|
|
151
|
-
const chatId = update.id
|
|
152
|
-
const conditionMatches = update.conditional ? update.conditional(data) : true
|
|
153
|
-
if (conditionMatches) {
|
|
154
|
-
delete update.conditional
|
|
155
|
-
const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId]
|
|
156
|
-
if (upsert) concatChats(upsert, update)
|
|
157
|
-
else data.chatUpdates[chatId] = concatChats(data.chatUpdates[chatId] || {}, update)
|
|
158
|
-
} else if (conditionMatches === undefined) data.chatUpdates[chatId] = update
|
|
159
|
-
data.chatDeletes.delete(chatId)
|
|
160
|
-
}
|
|
161
|
-
break
|
|
162
|
-
case 'chats.delete':
|
|
163
|
-
for (const chatId of eventData) {
|
|
164
|
-
data.chatDeletes.add(chatId)
|
|
165
|
-
delete data.chatUpdates[chatId]
|
|
166
|
-
delete data.chatUpserts[chatId]
|
|
167
|
-
delete data.historySets.chats[chatId]
|
|
168
|
-
}
|
|
169
|
-
break
|
|
170
|
-
case 'contacts.upsert':
|
|
171
|
-
for (const contact of eventData) {
|
|
172
|
-
let upsert = data.contactUpserts[contact.id]
|
|
173
|
-
if (!upsert) { upsert = data.historySets.contacts[contact.id]; if (upsert) logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set') }
|
|
174
|
-
upsert = upsert ? Object.assign(upsert, trimUndefined(contact)) : contact
|
|
175
|
-
data.contactUpserts[contact.id] = upsert
|
|
176
|
-
if (data.contactUpdates[contact.id]) { Object.assign(data.contactUpdates[contact.id], trimUndefined(contact)); delete data.contactUpdates[contact.id] }
|
|
177
|
-
}
|
|
178
|
-
break
|
|
179
|
-
case 'contacts.update':
|
|
180
|
-
for (const update of eventData) {
|
|
181
|
-
const upsert = data.historySets.contacts[update.id] || data.contactUpserts[update.id]
|
|
182
|
-
if (upsert) Object.assign(upsert, update)
|
|
183
|
-
else data.contactUpdates[update.id] = Object.assign(data.contactUpdates[update.id] || {}, update)
|
|
184
|
-
}
|
|
185
|
-
break
|
|
186
|
-
case 'messages.upsert': {
|
|
187
|
-
const { messages, type } = eventData
|
|
188
|
-
for (const message of messages) {
|
|
189
|
-
const key = stringifyMessageKey(message.key)
|
|
190
|
-
let existing = data.messageUpserts[key]?.message
|
|
191
|
-
if (!existing) { existing = data.historySets.messages[key]; if (existing) logger.debug({ messageId: key }, 'absorbed message upsert in message set') }
|
|
192
|
-
if (existing) message.messageTimestamp = existing.messageTimestamp
|
|
193
|
-
if (data.messageUpdates[key]) { logger.debug('absorbed prior message update in message upsert'); Object.assign(message, data.messageUpdates[key].update); delete data.messageUpdates[key] }
|
|
194
|
-
if (data.historySets.messages[key]) data.historySets.messages[key] = message
|
|
195
|
-
else data.messageUpserts[key] = { message, type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type }
|
|
196
|
-
}
|
|
197
|
-
break
|
|
198
|
-
}
|
|
199
|
-
case 'messages.update':
|
|
200
|
-
for (const { key, update } of eventData) {
|
|
201
|
-
const keyStr = stringifyMessageKey(key)
|
|
202
|
-
const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message
|
|
203
|
-
if (existing) {
|
|
204
|
-
Object.assign(existing, update)
|
|
205
|
-
if (update.status === WAMessageStatus.READ && !key.fromMe) decrementChatReadCounterIfMsgDidUnread(existing)
|
|
206
|
-
} else {
|
|
207
|
-
const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} }
|
|
208
|
-
Object.assign(msgUpdate.update, update)
|
|
209
|
-
data.messageUpdates[keyStr] = msgUpdate
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
break
|
|
213
|
-
case 'messages.delete':
|
|
214
|
-
if ('keys' in eventData) {
|
|
215
|
-
for (const key of eventData.keys) {
|
|
216
|
-
const keyStr = stringifyMessageKey(key)
|
|
217
|
-
if (!data.messageDeletes[keyStr]) data.messageDeletes[keyStr] = key
|
|
218
|
-
delete data.messageUpserts[keyStr]
|
|
219
|
-
delete data.messageUpdates[keyStr]
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
break
|
|
223
|
-
case 'messages.reaction':
|
|
224
|
-
for (const { key, reaction } of eventData) {
|
|
225
|
-
const keyStr = stringifyMessageKey(key)
|
|
226
|
-
const existing = data.messageUpserts[keyStr]
|
|
227
|
-
if (existing) updateMessageWithReaction(existing.message, reaction)
|
|
228
|
-
else { data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] }; updateMessageWithReaction(data.messageReactions[keyStr], reaction) }
|
|
229
|
-
}
|
|
230
|
-
break
|
|
231
|
-
case 'message-receipt.update':
|
|
232
|
-
for (const { key, receipt } of eventData) {
|
|
233
|
-
const keyStr = stringifyMessageKey(key)
|
|
234
|
-
const existing = data.messageUpserts[keyStr]
|
|
235
|
-
if (existing) updateMessageWithReceipt(existing.message, receipt)
|
|
236
|
-
else { data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] }; updateMessageWithReceipt(data.messageReceipts[keyStr], receipt) }
|
|
237
|
-
}
|
|
238
|
-
break
|
|
239
|
-
case 'groups.update':
|
|
240
|
-
for (const update of eventData) {
|
|
241
|
-
if (!data.groupUpdates[update.id]) data.groupUpdates[update.id] = Object.assign(data.groupUpdates[update.id] || {}, update)
|
|
242
|
-
}
|
|
243
|
-
break
|
|
244
|
-
default:
|
|
245
|
-
throw new Error(`"${event}" cannot be buffered`)
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
function consolidateEvents(data) {
|
|
250
|
-
const map = {}
|
|
251
|
-
const add = (key, list) => { if (list.length) map[key] = list }
|
|
252
|
-
if (!data.historySets.empty) map['messaging-history.set'] = { chats: Object.values(data.historySets.chats), messages: Object.values(data.historySets.messages), contacts: Object.values(data.historySets.contacts), syncType: data.historySets.syncType, progress: data.historySets.progress, isLatest: data.historySets.isLatest, peerDataRequestSessionId: data.historySets.peerDataRequestSessionId }
|
|
253
|
-
add('chats.upsert', Object.values(data.chatUpserts))
|
|
254
|
-
add('chats.update', Object.values(data.chatUpdates))
|
|
255
|
-
add('chats.delete', Array.from(data.chatDeletes))
|
|
256
|
-
const messageUpsertList = Object.values(data.messageUpserts)
|
|
257
|
-
if (messageUpsertList.length) map['messages.upsert'] = { messages: messageUpsertList.map(m => m.message), type: messageUpsertList[0].type }
|
|
258
|
-
add('messages.update', Object.values(data.messageUpdates))
|
|
259
|
-
const messageDeleteList = Object.values(data.messageDeletes)
|
|
260
|
-
if (messageDeleteList.length) map['messages.delete'] = { keys: messageDeleteList }
|
|
261
|
-
add('messages.reaction', Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.map(reaction => ({ key, reaction }))))
|
|
262
|
-
add('message-receipt.update', Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.map(receipt => ({ key, receipt }))))
|
|
263
|
-
add('contacts.upsert', Object.values(data.contactUpserts))
|
|
264
|
-
add('contacts.update', Object.values(data.contactUpdates))
|
|
265
|
-
add('groups.update', Object.values(data.groupUpdates))
|
|
266
|
-
return map
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
function concatChats(a, b) {
|
|
270
|
-
if (b.unreadCount === null && a.unreadCount < 0) { a.unreadCount = undefined; b.unreadCount = undefined }
|
|
271
|
-
if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') { b = { ...b }; if (b.unreadCount >= 0) b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0) }
|
|
272
|
-
return Object.assign(a, b)
|
|
1
|
+
import EventEmitter from 'events'
|
|
2
|
+
import { WAMessageStatus } from '../Types/index.js'
|
|
3
|
+
import { trimUndefined } from './generics.js'
|
|
4
|
+
import { updateMessageWithReaction, updateMessageWithReceipt } from './messages.js'
|
|
5
|
+
import { isRealMessage, shouldIncrementChatUnread } from './process-message.js'
|
|
6
|
+
|
|
7
|
+
const BUFFERABLE_EVENT = ['messaging-history.set', 'chats.upsert', 'chats.update', 'chats.delete', 'contacts.upsert', 'contacts.update', 'messages.upsert', 'messages.update', 'messages.delete', 'messages.reaction', 'message-receipt.update', 'groups.update']
|
|
8
|
+
const BUFFERABLE_EVENT_SET = new Set(BUFFERABLE_EVENT)
|
|
9
|
+
|
|
10
|
+
const BUFFER_TIMEOUT_MS = 30000
|
|
11
|
+
const MAX_HISTORY_CACHE_SIZE = 10000
|
|
12
|
+
|
|
13
|
+
const makeBufferData = () => ({
|
|
14
|
+
historySets: { chats: {}, messages: {}, contacts: {}, isLatest: false, empty: true },
|
|
15
|
+
chatUpserts: {}, chatUpdates: {}, chatDeletes: new Set(),
|
|
16
|
+
contactUpserts: {}, contactUpdates: {},
|
|
17
|
+
messageUpserts: {}, messageUpdates: {}, messageReactions: {}, messageDeletes: {}, messageReceipts: {},
|
|
18
|
+
groupUpdates: {}
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
const stringifyMessageKey = key => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`
|
|
22
|
+
|
|
23
|
+
export const makeEventBuffer = logger => {
|
|
24
|
+
const ev = new EventEmitter()
|
|
25
|
+
const historyCache = new Set()
|
|
26
|
+
let data = makeBufferData()
|
|
27
|
+
let isBuffering = false
|
|
28
|
+
let bufferTimeout = null
|
|
29
|
+
let bufferCount = 0
|
|
30
|
+
|
|
31
|
+
ev.on('event', map => { for (const event in map) ev.emit(event, map[event]) })
|
|
32
|
+
|
|
33
|
+
function buffer() {
|
|
34
|
+
bufferCount++
|
|
35
|
+
if (isBuffering) return
|
|
36
|
+
logger.debug('Event buffer activated')
|
|
37
|
+
isBuffering = true
|
|
38
|
+
if (bufferTimeout) clearTimeout(bufferTimeout)
|
|
39
|
+
bufferTimeout = setTimeout(() => { if (isBuffering) { logger.warn('Buffer timeout reached, auto-flushing'); flush() } }, BUFFER_TIMEOUT_MS)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function flush() {
|
|
43
|
+
if (!isBuffering) return false
|
|
44
|
+
logger.debug({ bufferCount }, 'Flushing event buffer')
|
|
45
|
+
isBuffering = false
|
|
46
|
+
bufferCount = 0
|
|
47
|
+
if (bufferTimeout) { clearTimeout(bufferTimeout); bufferTimeout = null }
|
|
48
|
+
if (historyCache.size > MAX_HISTORY_CACHE_SIZE) { logger.debug({ cacheSize: historyCache.size }, 'Clearing history cache'); historyCache.clear() }
|
|
49
|
+
const newData = makeBufferData()
|
|
50
|
+
for (const update of Object.values(data.chatUpdates)) {
|
|
51
|
+
if (update.conditional) { newData.chatUpdates[update.id] = update; delete data.chatUpdates[update.id] }
|
|
52
|
+
}
|
|
53
|
+
const consolidated = consolidateEvents(data)
|
|
54
|
+
if (Object.keys(consolidated).length) ev.emit('event', consolidated)
|
|
55
|
+
data = newData
|
|
56
|
+
logger.trace({ conditionalChatUpdatesLeft: Object.keys(newData.chatUpdates).length }, 'released buffered events')
|
|
57
|
+
return true
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
process(handler) {
|
|
62
|
+
ev.on('event', handler)
|
|
63
|
+
return () => ev.off('event', handler)
|
|
64
|
+
},
|
|
65
|
+
emit(event, evData) {
|
|
66
|
+
if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) { append(data, historyCache, event, evData, logger); return true }
|
|
67
|
+
return ev.emit('event', { [event]: evData })
|
|
68
|
+
},
|
|
69
|
+
isBuffering: () => isBuffering,
|
|
70
|
+
buffer,
|
|
71
|
+
flush,
|
|
72
|
+
createBufferedFunction(work) {
|
|
73
|
+
return async (...args) => {
|
|
74
|
+
buffer()
|
|
75
|
+
try {
|
|
76
|
+
const result = await work(...args)
|
|
77
|
+
if (bufferCount === 1) setTimeout(() => { if (isBuffering && bufferCount === 1) flush() }, 100)
|
|
78
|
+
return result
|
|
79
|
+
} finally {
|
|
80
|
+
bufferCount = Math.max(0, bufferCount - 1)
|
|
81
|
+
if (bufferCount === 0) setTimeout(flush, 100)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
on: (...args) => ev.on(...args),
|
|
86
|
+
off: (...args) => ev.off(...args),
|
|
87
|
+
listener: eventName => ev.listenerCount(eventName),
|
|
88
|
+
removeAllListeners: (...args) => ev.removeAllListeners(...args)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function append(data, historyCache, event, eventData, logger) {
|
|
93
|
+
function absorbingChatUpdate(existing) {
|
|
94
|
+
const chatId = existing.id || ''
|
|
95
|
+
const update = data.chatUpdates[chatId]
|
|
96
|
+
if (!update) return
|
|
97
|
+
const conditionMatches = update.conditional ? update.conditional(data) : true
|
|
98
|
+
if (conditionMatches) { delete update.conditional; logger.debug({ chatId }, 'absorbed chat update in existing chat'); Object.assign(existing, concatChats(update, existing)); delete data.chatUpdates[chatId] }
|
|
99
|
+
else if (conditionMatches === false) { logger.debug({ chatId }, 'chat update condition fail, removing'); delete data.chatUpdates[chatId] }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function decrementChatReadCounterIfMsgDidUnread(message) {
|
|
103
|
+
const chatId = message.key.remoteJid
|
|
104
|
+
const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId]
|
|
105
|
+
if (isRealMessage(message) && shouldIncrementChatUnread(message) && typeof chat?.unreadCount === 'number' && chat.unreadCount > 0) {
|
|
106
|
+
logger.debug({ chatId: chat.id }, 'decrementing chat counter')
|
|
107
|
+
chat.unreadCount -= 1
|
|
108
|
+
if (chat.unreadCount === 0) delete chat.unreadCount
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
switch (event) {
|
|
113
|
+
case 'messaging-history.set':
|
|
114
|
+
for (const chat of eventData.chats) {
|
|
115
|
+
const id = chat.id || ''
|
|
116
|
+
const existing = data.historySets.chats[id]
|
|
117
|
+
if (existing) existing.endOfHistoryTransferType = chat.endOfHistoryTransferType
|
|
118
|
+
else if (!historyCache.has(id)) { data.historySets.chats[id] = chat; historyCache.add(id); absorbingChatUpdate(chat) }
|
|
119
|
+
}
|
|
120
|
+
for (const contact of eventData.contacts) {
|
|
121
|
+
const existing = data.historySets.contacts[contact.id]
|
|
122
|
+
if (existing) Object.assign(existing, trimUndefined(contact))
|
|
123
|
+
else {
|
|
124
|
+
const hid = `c:${contact.id}`
|
|
125
|
+
if (!historyCache.has(hid) || contact.notify || contact.name || contact.verifiedName) { data.historySets.contacts[contact.id] = contact; historyCache.add(hid) }
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
for (const message of eventData.messages) {
|
|
129
|
+
const key = stringifyMessageKey(message.key)
|
|
130
|
+
if (!data.historySets.messages[key] && !historyCache.has(key)) { data.historySets.messages[key] = message; historyCache.add(key) }
|
|
131
|
+
}
|
|
132
|
+
data.historySets.empty = false
|
|
133
|
+
data.historySets.syncType = eventData.syncType
|
|
134
|
+
data.historySets.progress = eventData.progress
|
|
135
|
+
data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId
|
|
136
|
+
data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest
|
|
137
|
+
break
|
|
138
|
+
case 'chats.upsert':
|
|
139
|
+
for (const chat of eventData) {
|
|
140
|
+
const id = chat.id || ''
|
|
141
|
+
let upsert = data.chatUpserts[id]
|
|
142
|
+
if (id && !upsert) { upsert = data.historySets.chats[id]; if (upsert) logger.debug({ chatId: id }, 'absorbed chat upsert in chat set') }
|
|
143
|
+
upsert = upsert ? concatChats(upsert, chat) : chat
|
|
144
|
+
data.chatUpserts[id] = upsert
|
|
145
|
+
absorbingChatUpdate(upsert)
|
|
146
|
+
data.chatDeletes.delete(id)
|
|
147
|
+
}
|
|
148
|
+
break
|
|
149
|
+
case 'chats.update':
|
|
150
|
+
for (const update of eventData) {
|
|
151
|
+
const chatId = update.id
|
|
152
|
+
const conditionMatches = update.conditional ? update.conditional(data) : true
|
|
153
|
+
if (conditionMatches) {
|
|
154
|
+
delete update.conditional
|
|
155
|
+
const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId]
|
|
156
|
+
if (upsert) concatChats(upsert, update)
|
|
157
|
+
else data.chatUpdates[chatId] = concatChats(data.chatUpdates[chatId] || {}, update)
|
|
158
|
+
} else if (conditionMatches === undefined) data.chatUpdates[chatId] = update
|
|
159
|
+
data.chatDeletes.delete(chatId)
|
|
160
|
+
}
|
|
161
|
+
break
|
|
162
|
+
case 'chats.delete':
|
|
163
|
+
for (const chatId of eventData) {
|
|
164
|
+
data.chatDeletes.add(chatId)
|
|
165
|
+
delete data.chatUpdates[chatId]
|
|
166
|
+
delete data.chatUpserts[chatId]
|
|
167
|
+
delete data.historySets.chats[chatId]
|
|
168
|
+
}
|
|
169
|
+
break
|
|
170
|
+
case 'contacts.upsert':
|
|
171
|
+
for (const contact of eventData) {
|
|
172
|
+
let upsert = data.contactUpserts[contact.id]
|
|
173
|
+
if (!upsert) { upsert = data.historySets.contacts[contact.id]; if (upsert) logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set') }
|
|
174
|
+
upsert = upsert ? Object.assign(upsert, trimUndefined(contact)) : contact
|
|
175
|
+
data.contactUpserts[contact.id] = upsert
|
|
176
|
+
if (data.contactUpdates[contact.id]) { Object.assign(data.contactUpdates[contact.id], trimUndefined(contact)); delete data.contactUpdates[contact.id] }
|
|
177
|
+
}
|
|
178
|
+
break
|
|
179
|
+
case 'contacts.update':
|
|
180
|
+
for (const update of eventData) {
|
|
181
|
+
const upsert = data.historySets.contacts[update.id] || data.contactUpserts[update.id]
|
|
182
|
+
if (upsert) Object.assign(upsert, update)
|
|
183
|
+
else data.contactUpdates[update.id] = Object.assign(data.contactUpdates[update.id] || {}, update)
|
|
184
|
+
}
|
|
185
|
+
break
|
|
186
|
+
case 'messages.upsert': {
|
|
187
|
+
const { messages, type } = eventData
|
|
188
|
+
for (const message of messages) {
|
|
189
|
+
const key = stringifyMessageKey(message.key)
|
|
190
|
+
let existing = data.messageUpserts[key]?.message
|
|
191
|
+
if (!existing) { existing = data.historySets.messages[key]; if (existing) logger.debug({ messageId: key }, 'absorbed message upsert in message set') }
|
|
192
|
+
if (existing) message.messageTimestamp = existing.messageTimestamp
|
|
193
|
+
if (data.messageUpdates[key]) { logger.debug('absorbed prior message update in message upsert'); Object.assign(message, data.messageUpdates[key].update); delete data.messageUpdates[key] }
|
|
194
|
+
if (data.historySets.messages[key]) data.historySets.messages[key] = message
|
|
195
|
+
else data.messageUpserts[key] = { message, type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type }
|
|
196
|
+
}
|
|
197
|
+
break
|
|
198
|
+
}
|
|
199
|
+
case 'messages.update':
|
|
200
|
+
for (const { key, update } of eventData) {
|
|
201
|
+
const keyStr = stringifyMessageKey(key)
|
|
202
|
+
const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message
|
|
203
|
+
if (existing) {
|
|
204
|
+
Object.assign(existing, update)
|
|
205
|
+
if (update.status === WAMessageStatus.READ && !key.fromMe) decrementChatReadCounterIfMsgDidUnread(existing)
|
|
206
|
+
} else {
|
|
207
|
+
const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} }
|
|
208
|
+
Object.assign(msgUpdate.update, update)
|
|
209
|
+
data.messageUpdates[keyStr] = msgUpdate
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
break
|
|
213
|
+
case 'messages.delete':
|
|
214
|
+
if ('keys' in eventData) {
|
|
215
|
+
for (const key of eventData.keys) {
|
|
216
|
+
const keyStr = stringifyMessageKey(key)
|
|
217
|
+
if (!data.messageDeletes[keyStr]) data.messageDeletes[keyStr] = key
|
|
218
|
+
delete data.messageUpserts[keyStr]
|
|
219
|
+
delete data.messageUpdates[keyStr]
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
break
|
|
223
|
+
case 'messages.reaction':
|
|
224
|
+
for (const { key, reaction } of eventData) {
|
|
225
|
+
const keyStr = stringifyMessageKey(key)
|
|
226
|
+
const existing = data.messageUpserts[keyStr]
|
|
227
|
+
if (existing) updateMessageWithReaction(existing.message, reaction)
|
|
228
|
+
else { data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] }; updateMessageWithReaction(data.messageReactions[keyStr], reaction) }
|
|
229
|
+
}
|
|
230
|
+
break
|
|
231
|
+
case 'message-receipt.update':
|
|
232
|
+
for (const { key, receipt } of eventData) {
|
|
233
|
+
const keyStr = stringifyMessageKey(key)
|
|
234
|
+
const existing = data.messageUpserts[keyStr]
|
|
235
|
+
if (existing) updateMessageWithReceipt(existing.message, receipt)
|
|
236
|
+
else { data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] }; updateMessageWithReceipt(data.messageReceipts[keyStr], receipt) }
|
|
237
|
+
}
|
|
238
|
+
break
|
|
239
|
+
case 'groups.update':
|
|
240
|
+
for (const update of eventData) {
|
|
241
|
+
if (!data.groupUpdates[update.id]) data.groupUpdates[update.id] = Object.assign(data.groupUpdates[update.id] || {}, update)
|
|
242
|
+
}
|
|
243
|
+
break
|
|
244
|
+
default:
|
|
245
|
+
throw new Error(`"${event}" cannot be buffered`)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function consolidateEvents(data) {
|
|
250
|
+
const map = {}
|
|
251
|
+
const add = (key, list) => { if (list.length) map[key] = list }
|
|
252
|
+
if (!data.historySets.empty) map['messaging-history.set'] = { chats: Object.values(data.historySets.chats), messages: Object.values(data.historySets.messages), contacts: Object.values(data.historySets.contacts), syncType: data.historySets.syncType, progress: data.historySets.progress, isLatest: data.historySets.isLatest, peerDataRequestSessionId: data.historySets.peerDataRequestSessionId }
|
|
253
|
+
add('chats.upsert', Object.values(data.chatUpserts))
|
|
254
|
+
add('chats.update', Object.values(data.chatUpdates))
|
|
255
|
+
add('chats.delete', Array.from(data.chatDeletes))
|
|
256
|
+
const messageUpsertList = Object.values(data.messageUpserts)
|
|
257
|
+
if (messageUpsertList.length) map['messages.upsert'] = { messages: messageUpsertList.map(m => m.message), type: messageUpsertList[0].type }
|
|
258
|
+
add('messages.update', Object.values(data.messageUpdates))
|
|
259
|
+
const messageDeleteList = Object.values(data.messageDeletes)
|
|
260
|
+
if (messageDeleteList.length) map['messages.delete'] = { keys: messageDeleteList }
|
|
261
|
+
add('messages.reaction', Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.map(reaction => ({ key, reaction }))))
|
|
262
|
+
add('message-receipt.update', Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.map(receipt => ({ key, receipt }))))
|
|
263
|
+
add('contacts.upsert', Object.values(data.contactUpserts))
|
|
264
|
+
add('contacts.update', Object.values(data.contactUpdates))
|
|
265
|
+
add('groups.update', Object.values(data.groupUpdates))
|
|
266
|
+
return map
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function concatChats(a, b) {
|
|
270
|
+
if (b.unreadCount === null && a.unreadCount < 0) { a.unreadCount = undefined; b.unreadCount = undefined }
|
|
271
|
+
if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') { b = { ...b }; if (b.unreadCount >= 0) b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0) }
|
|
272
|
+
return Object.assign(a, b)
|
|
273
273
|
}
|