@itznomo/baileys 0.0.0-stage → 0.0.3

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.
Files changed (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,912 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { createWriteStream, promises as fs } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { pipeline } from 'node:stream/promises'
6
+ import { promisify } from 'node:util'
7
+ import { createInflate, inflate } from 'node:zlib'
8
+ import { proto } from '../../WAProto/index.js'
9
+ import { Boom } from '../foundation/boom.js'
10
+ import { Cache } from '../foundation/cache.js'
11
+ import { WAMessageStubType } from '../constants.js'
12
+ import {
13
+ areJidsSameUser,
14
+ getBinaryNodeChild,
15
+ getBinaryNodeChildren,
16
+ getBinaryNodeChildString,
17
+ isHostedLidUser,
18
+ isHostedPnUser,
19
+ isJidBroadcast,
20
+ isJidStatusBroadcast,
21
+ isLidUser,
22
+ isPnUser,
23
+ jidDecode,
24
+ jidEncode,
25
+ jidNormalizedUser
26
+ } from '../binary/wa-binary.js'
27
+ import { aesDecryptGCM, hmacSign, getKeyAuthor, toNumber, generateMessageIDV2 } from './wa-protocol-core.js'
28
+ import { getContentType, normalizeMessageContent } from './message-compose.js'
29
+ import { downloadContentFromMessage, getStream, getUrlFromDirectPath } from './media.js'
30
+ import { buildMergedTcTokenIndexWrite, resolveTcTokenJid } from './auth-state-core.js'
31
+
32
+ const inflatePromise = promisify(inflate)
33
+
34
+ const REAL_MSG_STUB_TYPES = new Set([
35
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
36
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
37
+ WAMessageStubType.CALL_MISSED_VIDEO,
38
+ WAMessageStubType.CALL_MISSED_VOICE
39
+ ])
40
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
41
+
42
+ async function storeTcTokensFromHistorySync(chats, signalRepository, keyStore, logger) {
43
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
44
+ const candidates = []
45
+ for (const chat of chats) {
46
+ const ts = chat.tcTokenTimestamp ? toNumber(chat.tcTokenTimestamp) : 0
47
+ if (chat.tcToken?.length && ts > 0) {
48
+ const jid = jidNormalizedUser(chat.id)
49
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
50
+ candidates.push({ storageJid, token: Buffer.from(chat.tcToken), ts, senderTs: chat.tcTokenSenderTimestamp ? toNumber(chat.tcTokenSenderTimestamp) : undefined })
51
+ }
52
+ }
53
+ if (!candidates.length) return
54
+ const jids = candidates.map(c => c.storageJid)
55
+ const existing = await keyStore.get('tctoken', jids)
56
+ const entries = {}
57
+ for (const c of candidates) {
58
+ const existingEntry = existing[c.storageJid]
59
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
60
+ if (existingTs > 0 && existingTs >= c.ts) continue
61
+ entries[c.storageJid] = { ...existingEntry, token: c.token, timestamp: String(c.ts), ...(c.senderTs !== undefined ? { senderTimestamp: c.senderTs } : {}) }
62
+ }
63
+ if (Object.keys(entries).length) {
64
+ logger?.debug({ count: Object.keys(entries).length }, 'storing tctokens from history sync')
65
+ try {
66
+ const indexWrite = await buildMergedTcTokenIndexWrite(keyStore, Object.keys(entries))
67
+ await keyStore.set({ tctoken: { ...entries, ...indexWrite } })
68
+ } catch (err) {
69
+ logger?.warn({ err }, 'failed to store tctokens from history sync')
70
+ }
71
+ }
72
+ }
73
+
74
+ export const cleanMessage = (message, meId, meLid) => {
75
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
76
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid')
77
+ } else {
78
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid)
79
+ }
80
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
81
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid')
82
+ } else {
83
+ message.key.participant = jidNormalizedUser(message.key.participant)
84
+ }
85
+ const content = normalizeMessageContent(message.message)
86
+ if (content?.reactionMessage) normaliseKey(content.reactionMessage.key)
87
+ if (content?.pollUpdateMessage) normaliseKey(content.pollUpdateMessage.pollCreationMessageKey)
88
+
89
+ function normaliseKey(msgKey) {
90
+ if (!message.key.fromMe) {
91
+ msgKey.fromMe = !msgKey.fromMe
92
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) || areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
93
+ : false
94
+ msgKey.remoteJid = message.key.remoteJid
95
+ msgKey.participant = msgKey.participant || message.key.participant
96
+ }
97
+ }
98
+ }
99
+
100
+ export const isRealMessage = message => {
101
+ const normalizedContent = normalizeMessageContent(message.message)
102
+ const hasSomeContent = !!getContentType(normalizedContent)
103
+ return (
104
+ (!!normalizedContent || REAL_MSG_STUB_TYPES.has(message.messageStubType) || REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
105
+ hasSomeContent &&
106
+ !normalizedContent?.protocolMessage &&
107
+ !normalizedContent?.reactionMessage &&
108
+ !normalizedContent?.pollUpdateMessage
109
+ )
110
+ }
111
+
112
+ export const shouldIncrementChatUnread = message => !message.key.fromMe && !message.messageStubType
113
+
114
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
115
+ if (!remoteJid) throw new Boom('Cannot derive chat id: message key is missing remoteJid', { data: { remoteJid, participant, fromMe } })
116
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
117
+ if (!participant) throw new Boom('Cannot derive chat id: broadcast message key is missing participant', { data: { remoteJid, fromMe } })
118
+ return participant
119
+ }
120
+ return remoteJid
121
+ }
122
+
123
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
124
+ const toBinary = txt => Buffer.from(txt)
125
+ const sign = Buffer.concat([toBinary(pollMsgId), toBinary(pollCreatorJid), toBinary(voterJid), toBinary('Poll Vote'), new Uint8Array([1])])
126
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
127
+ const decKey = hmacSign(sign, key0, 'sha256')
128
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`)
129
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
130
+ return proto.Message.PollVoteMessage.decode(decrypted)
131
+ }
132
+
133
+ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
134
+ const toBinary = txt => Buffer.from(txt)
135
+ const sign = Buffer.concat([toBinary(eventMsgId), toBinary(eventCreatorJid), toBinary(responderJid), toBinary('Event Response'), new Uint8Array([1])])
136
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256')
137
+ const decKey = hmacSign(sign, key0, 'sha256')
138
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`)
139
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
140
+ return proto.Message.EventResponseMessage.decode(decrypted)
141
+ }
142
+
143
+ export function decryptMessageEdit({ encPayload, encIv }, { originalSenderJid, originalMsgId, editEncKey, editorJid }) {
144
+ const toBinary = txt => Buffer.from(txt)
145
+ const sign = Buffer.concat([toBinary(originalMsgId), toBinary(originalSenderJid), toBinary(editorJid), toBinary('Message Edit'), new Uint8Array([1])])
146
+ const key0 = hmacSign(editEncKey, new Uint8Array(32), 'sha256')
147
+ const decKey = hmacSign(sign, key0, 'sha256')
148
+ const aad = Buffer.alloc(0)
149
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
150
+ return proto.Message.decode(decrypted)
151
+ }
152
+
153
+ const buildEditUpdate = args => {
154
+ const editedInner = decryptMessageEdit(
155
+ { encPayload: args.encPayload, encIv: args.encIv },
156
+ { editEncKey: args.editEncKey, originalSenderJid: args.originalSenderJid, originalMsgId: args.originalMsgId, editorJid: args.editorJid }
157
+ )
158
+ const editProtocol = editedInner.protocolMessage
159
+ const innerEdited = editProtocol?.editedMessage
160
+ if (!innerEdited) {
161
+ args.logger?.warn({ targetKey: args.targetKey }, 'decrypted MESSAGE_EDIT plaintext had no protocolMessage.editedMessage — skipping update')
162
+ return null
163
+ }
164
+ return {
165
+ key: { ...args.messageKey, id: args.targetKeyId },
166
+ update: {
167
+ message: { editedMessage: { message: innerEdited } },
168
+ messageTimestamp: editProtocol?.timestampMs ? Math.floor(toNumber(editProtocol.timestampMs) / 1000) : args.fallbackTimestamp
169
+ }
170
+ }
171
+ }
172
+
173
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
174
+ const meId = creds.me.id
175
+ const { accountSettings } = creds
176
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) }
177
+ const isRealMsg = isRealMessage(message)
178
+ if (isRealMsg) {
179
+ chat.messages = [{ message }]
180
+ chat.conversationTimestamp = toNumber(message.messageTimestamp)
181
+ if (shouldIncrementChatUnread(message)) chat.unreadCount = (chat.unreadCount || 0) + 1
182
+ }
183
+ const content = normalizeMessageContent(message.message)
184
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
185
+ chat.archived = false
186
+ chat.readOnly = false
187
+ }
188
+ const protocolMsg = content?.protocolMessage
189
+ if (protocolMsg) {
190
+
191
+ const SELF_ONLY_TYPES = new Set([
192
+ proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
193
+ proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
194
+ proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
195
+ proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE
196
+ ])
197
+ if (protocolMsg.type !== null && protocolMsg.type !== undefined && SELF_ONLY_TYPES.has(protocolMsg.type) && !message.key.fromMe) {
198
+ logger?.warn({ msgId: message.key.id, type: protocolMsg.type, from: message.key.participant || message.key.remoteJid }, 'dropping spoofed self-only protocolMessage from non-self origin')
199
+ return
200
+ }
201
+ switch (protocolMsg.type) {
202
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION: {
203
+ const histNotification = protocolMsg.historySyncNotification
204
+ const process = shouldProcessHistoryMsg
205
+ const isLatest = !creds.processedHistoryMessages?.length
206
+ logger?.info({ histNotification, process, id: message.key.id, isLatest }, 'got history notification')
207
+ if (process) {
208
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
209
+ ev.emit('creds.update', {
210
+ processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }]
211
+ })
212
+ }
213
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger)
214
+ if (data.lidPnMappings?.length) {
215
+ logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync')
216
+ await signalRepository.lidMapping.storeLIDPNMappings(data.lidPnMappings).catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'))
217
+ }
218
+ await storeTcTokensFromHistorySync(data.chats, signalRepository, keyStore, logger)
219
+ ev.emit('messaging-history.set', {
220
+ ...data,
221
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
222
+ chunkOrder: histNotification.chunkOrder,
223
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
224
+ })
225
+ }
226
+ break
227
+ }
228
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE: {
229
+ const keys = protocolMsg.appStateSyncKeyShare.keys
230
+ if (keys?.length) {
231
+ let newAppStateSyncKeyId = ''
232
+ await keyStore.transaction(async () => {
233
+ const newKeys = []
234
+ for (const { keyData, keyId } of keys) {
235
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64')
236
+ newKeys.push(strKeyId)
237
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } })
238
+ newAppStateSyncKeyId = strKeyId
239
+ }
240
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
241
+ }, meId)
242
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
243
+ } else {
244
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys')
245
+ }
246
+ break
247
+ }
248
+ case proto.Message.ProtocolMessage.Type.REVOKE:
249
+ ev.emit('messages.update', [
250
+ { key: { ...message.key, id: protocolMsg.key.id }, update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key } }
251
+ ])
252
+ break
253
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
254
+ Object.assign(chat, { ephemeralSettingTimestamp: toNumber(message.messageTimestamp), ephemeralExpiration: protocolMsg.ephemeralExpiration || null })
255
+ break
256
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE: {
257
+ const response = protocolMsg.peerDataOperationRequestResponseMessage
258
+ if (response) {
259
+ const peerDataOperationResult = response.peerDataOperationResult || []
260
+ for (const result of peerDataOperationResult) {
261
+ const retryResponse = result?.placeholderMessageResendResponse
262
+ if (!retryResponse?.webMessageInfoBytes) continue
263
+ try {
264
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes)
265
+ const msgId = webMessageInfo.key?.id
266
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined
267
+ if (msgId) await placeholderResendCache?.del(msgId)
268
+ let finalMsg
269
+ if (cachedData && typeof cachedData === 'object') {
270
+ cachedData.message = webMessageInfo.message
271
+ if (webMessageInfo.messageTimestamp) cachedData.messageTimestamp = webMessageInfo.messageTimestamp
272
+ finalMsg = cachedData
273
+ } else {
274
+ finalMsg = webMessageInfo
275
+ }
276
+ logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend')
277
+ ev.emit('messages.upsert', { messages: [finalMsg], type: 'notify', requestId: response.stanzaId })
278
+ } catch (err) {
279
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response')
280
+ }
281
+ }
282
+ }
283
+ break
284
+ }
285
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
286
+ ev.emit('messages.update', [
287
+ {
288
+ key: { ...message.key, id: protocolMsg.key?.id },
289
+ update: {
290
+ message: { editedMessage: { message: protocolMsg.editedMessage } },
291
+ messageTimestamp: protocolMsg.timestampMs ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000) : message.messageTimestamp
292
+ }
293
+ }
294
+ ])
295
+ break
296
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE: {
297
+ const labelAssociationMsg = protocolMsg.memberLabel
298
+ if (labelAssociationMsg?.label) {
299
+ ev.emit('group.member-tag.update', {
300
+ groupId: chat.id,
301
+ label: labelAssociationMsg.label,
302
+ participant: message.key.participant,
303
+ participantAlt: message.key.participantAlt,
304
+ messageTimestamp: Number(message.messageTimestamp)
305
+ })
306
+ }
307
+ break
308
+ }
309
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC: {
310
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload
311
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload)
312
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp')
313
+ const pairs = []
314
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
315
+ const lid = latestLid || assignedLid
316
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` })
317
+ }
318
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs)
319
+ if (pairs.length) for (const { pn, lid } of pairs) await signalRepository.migrateSession(pn, lid)
320
+ }
321
+ }
322
+ } else if (content?.reactionMessage) {
323
+ const reaction = { ...content.reactionMessage, key: message.key }
324
+ ev.emit('messages.reaction', [{ reaction, key: content.reactionMessage?.key }])
325
+ } else if (content?.encEventResponseMessage) {
326
+ const encEventResponse = content.encEventResponseMessage
327
+ const creationMsgKey = encEventResponse.eventCreationMessageKey
328
+ const eventMsg = await getMessage(creationMsgKey)
329
+ if (eventMsg) {
330
+ try {
331
+ const meIdNormalised = jidNormalizedUser(meId)
332
+ const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid
333
+ const eventCreatorPn = isLidUser(eventCreatorKey) ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey) : eventCreatorKey
334
+ const eventCreatorJid = getKeyAuthor({ remoteJid: jidNormalizedUser(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised)
335
+ const responderJid = getKeyAuthor(message.key, meIdNormalised)
336
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret
337
+ if (!eventEncKey) {
338
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption')
339
+ } else {
340
+ const responseMsg = decryptEventResponse(encEventResponse, { eventEncKey, eventCreatorJid, eventMsgId: creationMsgKey.id, responderJid })
341
+ const eventResponse = { eventResponseMessageKey: message.key, senderTimestampMs: responseMsg.timestampMs, response: responseMsg }
342
+ ev.emit('messages.update', [{ key: creationMsgKey, update: { eventResponses: [eventResponse] } }])
343
+ }
344
+ } catch (err) {
345
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response')
346
+ }
347
+ } else {
348
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response')
349
+ }
350
+ } else if (content?.secretEncryptedMessage && content.secretEncryptedMessage.secretEncType === proto.Message.SecretEncryptedMessage.SecretEncType.MESSAGE_EDIT) {
351
+ const secEnc = content.secretEncryptedMessage
352
+ const targetKey = secEnc.targetMessageKey
353
+ const targetMsg = await getMessage(targetKey)
354
+ if (targetMsg) {
355
+ try {
356
+ const meIdNormalised = jidNormalizedUser(meId)
357
+ const origSenderRaw = targetKey.participant || targetKey.remoteJid
358
+ const origSenderPn = isLidUser(origSenderRaw) ? await signalRepository.lidMapping.getPNForLID(origSenderRaw) : origSenderRaw
359
+ const originalSenderJid = getKeyAuthor({ remoteJid: jidNormalizedUser(origSenderPn), fromMe: meIdNormalised === origSenderPn }, meIdNormalised)
360
+ const editorJid = getKeyAuthor(message.key, meIdNormalised)
361
+ const editEncKey = targetMsg?.messageContextInfo?.messageSecret
362
+ if (!editEncKey) {
363
+ logger?.warn({ targetKey }, 'message edit: missing messageSecret on original message — cannot decrypt')
364
+ return
365
+ }
366
+ const update = buildEditUpdate({
367
+ editEncKey,
368
+ encPayload: secEnc.encPayload,
369
+ encIv: secEnc.encIv,
370
+ originalSenderJid,
371
+ originalMsgId: targetKey.id,
372
+ editorJid,
373
+ messageKey: message.key,
374
+ targetKeyId: targetKey.id,
375
+ fallbackTimestamp: toNumber(message.messageTimestamp),
376
+ logger,
377
+ targetKey
378
+ })
379
+ if (update) ev.emit('messages.update', [update])
380
+ } catch (err) {
381
+ logger?.warn({ err, targetKey }, 'failed to decrypt secretEncryptedMessage MESSAGE_EDIT')
382
+ }
383
+ } else {
384
+ logger?.warn({ targetKey }, 'original message not found in store, cannot decrypt secretEncryptedMessage edit')
385
+ }
386
+ } else if (message.messageStubType) {
387
+ const jid = message.key?.remoteJid
388
+ let participants
389
+ const emitParticipantsUpdate = action =>
390
+ ev.emit('group-participants.update', { id: jid, author: message.key.participant, authorPn: message.key.participantAlt, authorUsername: message.key.participantUsername, participants, action })
391
+ const emitGroupUpdate = update =>
392
+ ev.emit('groups.update', [{ id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt, authorUsername: message.key.participantUsername }])
393
+ const emitGroupRequestJoin = (participant, action, method) =>
394
+ ev.emit('group.join-request', {
395
+ id: jid,
396
+ author: message.key.participant,
397
+ authorPn: message.key.participantAlt,
398
+ authorUsername: message.key.participantUsername,
399
+ participant: participant.lid,
400
+ participantPn: participant.pn,
401
+ action,
402
+ method
403
+ })
404
+ const participantsIncludesMe = () => participants.find(jid_ => areJidsSameUser(meId, jid_.phoneNumber))
405
+
406
+ switch (message.messageStubType) {
407
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
408
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
409
+ emitParticipantsUpdate('modify')
410
+ break
411
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
412
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
413
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
414
+ emitParticipantsUpdate('remove')
415
+ if (participantsIncludesMe()) chat.readOnly = true
416
+ break
417
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
418
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
419
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
420
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
421
+ if (participantsIncludesMe()) chat.readOnly = false
422
+ emitParticipantsUpdate('add')
423
+ break
424
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
425
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
426
+ emitParticipantsUpdate('demote')
427
+ break
428
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
429
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
430
+ emitParticipantsUpdate('promote')
431
+ break
432
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE: {
433
+ const announceValue = message.messageStubParameters?.[0]
434
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
435
+ break
436
+ }
437
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT: {
438
+ const restrictValue = message.messageStubParameters?.[0]
439
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
440
+ break
441
+ }
442
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT: {
443
+ const name = message.messageStubParameters?.[0]
444
+ chat.name = name
445
+ emitGroupUpdate({ subject: name })
446
+ break
447
+ }
448
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION: {
449
+ const description = message.messageStubParameters?.[0]
450
+ chat.description = description
451
+ emitGroupUpdate({ desc: description })
452
+ break
453
+ }
454
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK: {
455
+ const code = message.messageStubParameters?.[0]
456
+ emitGroupUpdate({ inviteCode: code })
457
+ break
458
+ }
459
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE: {
460
+ const memberAddValue = message.messageStubParameters?.[0]
461
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
462
+ break
463
+ }
464
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE: {
465
+ const approvalMode = message.messageStubParameters?.[0]
466
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
467
+ break
468
+ }
469
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: {
470
+ const participant = JSON.parse(message.messageStubParameters?.[0])
471
+ const action = message.messageStubParameters?.[1]
472
+ const method = message.messageStubParameters?.[2]
473
+ emitGroupRequestJoin(participant, action, method)
474
+ break
475
+ }
476
+ }
477
+ }
478
+ if (Object.keys(chat).length > 1) ev.emit('chats.update', [chat])
479
+ }
480
+
481
+ export default processMessage
482
+
483
+ const RECENT_MESSAGES_SIZE = 1024
484
+ const MESSAGE_KEY_SEPARATOR = '\u0000'
485
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
486
+ const PHONE_REQUEST_DELAY = 3000
487
+
488
+ export const RetryReason = {
489
+ UnknownError: 0,
490
+ SignalErrorNoSession: 1,
491
+ SignalErrorInvalidKey: 2,
492
+ SignalErrorInvalidKeyId: 3,
493
+ SignalErrorInvalidMessage: 4,
494
+ SignalErrorInvalidSignature: 5,
495
+ SignalErrorFutureMessage: 6,
496
+ SignalErrorBadMac: 7,
497
+ SignalErrorInvalidSession: 8,
498
+ SignalErrorInvalidMsgKey: 9,
499
+ BadBroadcastEphemeralSetting: 10,
500
+ UnknownCompanionNoPrekey: 11,
501
+ AdvFailure: 12,
502
+ StatusRevokeDelay: 13
503
+ }
504
+
505
+ for (const [name, value] of Object.entries({ ...RetryReason })) RetryReason[value] = name
506
+
507
+ const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac])
508
+
509
+ export class MessageRetryManager {
510
+ constructor(logger, maxMsgRetryCount) {
511
+ this.logger = logger
512
+ this.recentMessagesMap = new Cache({
513
+ max: RECENT_MESSAGES_SIZE,
514
+ ttl: 5 * 60 * 1000,
515
+ dispose: (_value, key) => {
516
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR)
517
+ if (separatorIndex > -1) this.messageKeyIndex.delete(key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length))
518
+ }
519
+ })
520
+ this.messageKeyIndex = new Map()
521
+
522
+ this.sessionRecreateHistory = new Cache({ max: 2048, ttl: RECREATE_SESSION_TIMEOUT * 2 })
523
+ this.retryCounters = new Cache({ max: 2048, ttl: 15 * 60 * 1000, updateAgeOnGet: true })
524
+ this.baseKeys = new Cache({ max: 1024, ttl: 15 * 60 * 1000 })
525
+ this.pendingPhoneRequests = {}
526
+ this.maxMsgRetryCount = maxMsgRetryCount
527
+ this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
528
+
529
+ this.invalidatedMessages = new Cache({ max: 512, ttl: 5 * 60 * 1000 })
530
+ }
531
+
532
+ invalidatedKey(to, id) {
533
+ return this.keyToString({ to, id })
534
+ }
535
+
536
+ invalidateMessage(to, id) {
537
+ if (!to || !id) return
538
+ this.invalidatedMessages.set(this.invalidatedKey(to, id), true)
539
+ }
540
+
541
+ isMessageInvalidated(to, id) {
542
+ if (!to || !id) return false
543
+ return this.invalidatedMessages.get(this.invalidatedKey(to, id)) === true
544
+ }
545
+
546
+ addRecentMessage(to, id, message) {
547
+ const keyStr = this.keyToString({ to, id })
548
+ this.recentMessagesMap.set(keyStr, { message, timestamp: Date.now() })
549
+ this.messageKeyIndex.set(id, keyStr)
550
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`)
551
+ }
552
+
553
+ getRecentMessage(to, id) {
554
+ return this.recentMessagesMap.get(this.keyToString({ to, id }))
555
+ }
556
+
557
+ shouldRecreateSession(jid, hasSession, errorCode) {
558
+ if (!hasSession) {
559
+ this.sessionRecreateHistory.set(jid, Date.now())
560
+ this.statistics.sessionRecreations++
561
+ return { reason: "we don't have a Signal session with them", recreate: true }
562
+ }
563
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
564
+ this.sessionRecreateHistory.set(jid, Date.now())
565
+ this.statistics.sessionRecreations++
566
+ this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation')
567
+ return { reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`, recreate: true }
568
+ }
569
+ const now = Date.now()
570
+ const prevTime = this.sessionRecreateHistory.get(jid)
571
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
572
+ this.sessionRecreateHistory.set(jid, now)
573
+ this.statistics.sessionRecreations++
574
+ return { reason: 'retry count > 1 and over an hour since last recreation', recreate: true }
575
+ }
576
+ return { reason: '', recreate: false }
577
+ }
578
+
579
+ parseRetryErrorCode(errorAttr) {
580
+ if (errorAttr === undefined || errorAttr === '') return undefined
581
+ const code = parseInt(errorAttr, 10)
582
+ if (Number.isNaN(code)) return undefined
583
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) return code
584
+ return RetryReason.UnknownError
585
+ }
586
+
587
+ isMacError(errorCode) {
588
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)
589
+ }
590
+
591
+ incrementRetryCount(messageId) {
592
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1)
593
+ this.statistics.totalRetries++
594
+ return this.retryCounters.get(messageId)
595
+ }
596
+
597
+ getRetryCount(messageId) {
598
+ return this.retryCounters.get(messageId) || 0
599
+ }
600
+
601
+ hasExceededMaxRetries(messageId) {
602
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount
603
+ }
604
+
605
+ markRetrySuccess(messageId) {
606
+ this.statistics.successfulRetries++
607
+ this.retryCounters.delete(messageId)
608
+ this.cancelPendingPhoneRequest(messageId)
609
+ this.removeRecentMessage(messageId)
610
+ }
611
+
612
+ markRetryFailed(messageId) {
613
+ this.statistics.failedRetries++
614
+ this.retryCounters.delete(messageId)
615
+ this.cancelPendingPhoneRequest(messageId)
616
+ this.removeRecentMessage(messageId)
617
+ }
618
+
619
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
620
+ this.cancelPendingPhoneRequest(messageId)
621
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
622
+ delete this.pendingPhoneRequests[messageId]
623
+ this.statistics.phoneRequests++
624
+ callback()
625
+ }, delay)
626
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`)
627
+ }
628
+
629
+ cancelPendingPhoneRequest(messageId) {
630
+ const timeout = this.pendingPhoneRequests[messageId]
631
+ if (timeout) {
632
+ clearTimeout(timeout)
633
+ delete this.pendingPhoneRequests[messageId]
634
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`)
635
+ }
636
+ }
637
+
638
+ close() {
639
+ this.clear()
640
+ this.recentMessagesMap?.close?.()
641
+ this.sessionRecreateHistory?.close?.()
642
+ this.retryCounters?.close?.()
643
+ this.baseKeys?.close?.()
644
+ this.invalidatedMessages?.close?.()
645
+ }
646
+
647
+ clear() {
648
+ this.recentMessagesMap.clear()
649
+ this.messageKeyIndex.clear()
650
+ this.sessionRecreateHistory.clear()
651
+ this.retryCounters.clear()
652
+ this.baseKeys.clear()
653
+ this.invalidatedMessages.clear()
654
+ for (const messageId of Object.keys(this.pendingPhoneRequests)) this.cancelPendingPhoneRequest(messageId)
655
+ this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
656
+ }
657
+
658
+ saveBaseKey(addr, msgId, baseKey) {
659
+ this.baseKeys.set(`${addr}:${msgId}`, baseKey)
660
+ }
661
+
662
+ hasSameBaseKey(addr, msgId, baseKey) {
663
+ const stored = this.baseKeys.get(`${addr}:${msgId}`)
664
+ if (!stored || stored.length !== baseKey.length) return false
665
+ for (let i = 0; i < stored.length; i++) if (stored[i] !== baseKey[i]) return false
666
+ return true
667
+ }
668
+
669
+ deleteBaseKey(addr, msgId) {
670
+ this.baseKeys.delete(`${addr}:${msgId}`)
671
+ }
672
+
673
+ keyToString(key) {
674
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`
675
+ }
676
+
677
+ removeRecentMessage(messageId) {
678
+ const keyStr = this.messageKeyIndex.get(messageId)
679
+ if (!keyStr) return
680
+ this.recentMessagesMap.delete(keyStr)
681
+ this.messageKeyIndex.delete(messageId)
682
+ }
683
+ }
684
+
685
+ export function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
686
+ const nodes = []
687
+ let isProcessing = false
688
+ const enqueue = (type, node) => {
689
+ nodes.push({ type, node })
690
+ if (isProcessing) return
691
+ isProcessing = true
692
+ const run = async () => {
693
+ let processedInBatch = 0
694
+ while (nodes.length && deps.isWsOpen()) {
695
+ const { type, node } = nodes.shift()
696
+ const nodeProcessor = nodeProcessorMap.get(type)
697
+ if (!nodeProcessor) {
698
+ deps.onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node')
699
+ continue
700
+ }
701
+ await nodeProcessor(node).catch(err => deps.onUnexpectedError(err, `processing offline ${type}`))
702
+ processedInBatch++
703
+ if (processedInBatch >= batchSize) {
704
+ processedInBatch = 0
705
+ await deps.yieldToEventLoop()
706
+ }
707
+ }
708
+ isProcessing = false
709
+ }
710
+ run().catch(error => deps.onUnexpectedError(error, 'processing offline nodes'))
711
+ }
712
+ return { enqueue }
713
+ }
714
+
715
+ const extractPnFromMessages = messages => {
716
+ for (const msgItem of messages) {
717
+ const message = msgItem.message
718
+ if (!message?.key?.fromMe || !message.userReceipt?.length) continue
719
+ const userJid = message.userReceipt[0]?.userJid
720
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) return userJid
721
+ }
722
+ return undefined
723
+ }
724
+
725
+ export const downloadHistory = async (msg, options) => {
726
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
727
+ const inflater = createInflate()
728
+ const chunks = []
729
+ inflater.on('data', chunk => chunks.push(chunk))
730
+ await pipeline(stream, inflater)
731
+ return proto.HistorySync.decode(Buffer.concat(chunks))
732
+ }
733
+
734
+ export const processHistoryMessage = (item, logger) => {
735
+ const messages = []
736
+ const contacts = []
737
+ const chats = []
738
+ const lidPnMappings = []
739
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString())
740
+ for (const m of item.phoneNumberToLidMappings || []) {
741
+ if (m.lidJid && m.pnJid) lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid })
742
+ }
743
+ switch (item.syncType) {
744
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
745
+ case proto.HistorySync.HistorySyncType.RECENT:
746
+ case proto.HistorySync.HistorySyncType.FULL:
747
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
748
+ for (const chat of item.conversations) {
749
+ contacts.push({ id: chat.id, name: chat.displayName || chat.name || chat.username || undefined, username: chat.username || undefined, lid: chat.lidJid || chat.accountLid || undefined, phoneNumber: chat.pnJid || undefined })
750
+ const chatId = chat.id
751
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId)
752
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId)
753
+ if (isLid && chat.pnJid) lidPnMappings.push({ lid: chatId, pn: chat.pnJid })
754
+ else if (isPn && chat.lidJid) lidPnMappings.push({ lid: chat.lidJid, pn: chatId })
755
+ else if (isLid && !chat.pnJid) {
756
+ const pnFromReceipt = extractPnFromMessages(chat.messages || [])
757
+ if (pnFromReceipt) lidPnMappings.push({ lid: chatId, pn: pnFromReceipt })
758
+ }
759
+ const msgs = chat.messages || []
760
+ delete chat.messages
761
+ for (const item_ of msgs) {
762
+ const message = item_.message
763
+ messages.push(message)
764
+ if (!chat.messages?.length) chat.messages = [{ message }]
765
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
766
+ if (
767
+ (message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP || message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
768
+ message.messageStubParameters?.[0]
769
+ ) {
770
+ contacts.push({ id: message.key.participant || message.key.remoteJid, verifiedName: message.messageStubParameters?.[0] })
771
+ }
772
+ }
773
+ chats.push(chat)
774
+ }
775
+ break
776
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
777
+ for (const c of item.pushnames) contacts.push({ id: c.id, notify: c.pushname })
778
+ break
779
+ }
780
+ return { chats, contacts, messages, lidPnMappings, pastParticipants: item.pastParticipants, syncType: item.syncType, progress: item.progress }
781
+ }
782
+
783
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
784
+ const historyMsg = msg.initialHistBootstrapInlinePayload
785
+ ? proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload))
786
+ : await downloadHistory(msg, options)
787
+ return processHistoryMessage(historyMsg, logger)
788
+ }
789
+
790
+ export const getHistoryMsg = message => {
791
+ const normalizedContent = message ? normalizeMessageContent(message) : undefined
792
+ return normalizedContent?.protocolMessage?.historySyncNotification
793
+ }
794
+
795
+ export const parseCatalogNode = node => {
796
+ const catalogNode = getBinaryNodeChild(node, 'product_catalog')
797
+ const products = getBinaryNodeChildren(catalogNode, 'product').map(parseProductNode)
798
+ const paging = getBinaryNodeChild(catalogNode, 'paging')
799
+ return { products, nextPageCursor: paging ? getBinaryNodeChildString(paging, 'after') : undefined }
800
+ }
801
+
802
+ export const parseCollectionsNode = node => {
803
+ const collectionsNode = getBinaryNodeChild(node, 'collections')
804
+ const collections = getBinaryNodeChildren(collectionsNode, 'collection').map(collectionNode => ({
805
+ id: getBinaryNodeChildString(collectionNode, 'id'),
806
+ name: getBinaryNodeChildString(collectionNode, 'name'),
807
+ products: getBinaryNodeChildren(collectionNode, 'product').map(parseProductNode),
808
+ status: parseStatusInfo(collectionNode)
809
+ }))
810
+ return { collections }
811
+ }
812
+
813
+ export const parseOrderDetailsNode = node => {
814
+ const orderNode = getBinaryNodeChild(node, 'order')
815
+ const products = getBinaryNodeChildren(orderNode, 'product').map(productNode => {
816
+ const imageNode = getBinaryNodeChild(productNode, 'image')
817
+ return {
818
+ id: getBinaryNodeChildString(productNode, 'id'),
819
+ name: getBinaryNodeChildString(productNode, 'name'),
820
+ imageUrl: getBinaryNodeChildString(imageNode, 'url'),
821
+ price: +getBinaryNodeChildString(productNode, 'price'),
822
+ currency: getBinaryNodeChildString(productNode, 'currency'),
823
+ quantity: +getBinaryNodeChildString(productNode, 'quantity')
824
+ }
825
+ })
826
+ const priceNode = getBinaryNodeChild(orderNode, 'price')
827
+ return { price: { total: +getBinaryNodeChildString(priceNode, 'total'), currency: getBinaryNodeChildString(priceNode, 'currency') }, products }
828
+ }
829
+
830
+ export const toProductNode = (productId, product) => {
831
+ const attrs = {}
832
+ const content = []
833
+ if (typeof productId !== 'undefined') content.push({ tag: 'id', attrs: {}, content: Buffer.from(productId) })
834
+ if (typeof product.name !== 'undefined') content.push({ tag: 'name', attrs: {}, content: Buffer.from(product.name) })
835
+ if (typeof product.description !== 'undefined') content.push({ tag: 'description', attrs: {}, content: Buffer.from(product.description) })
836
+ if (typeof product.retailerId !== 'undefined') content.push({ tag: 'retailer_id', attrs: {}, content: Buffer.from(product.retailerId) })
837
+ if (product.images.length) {
838
+ content.push({
839
+ tag: 'media',
840
+ attrs: {},
841
+ content: product.images.map(img => {
842
+ if (!('url' in img)) throw new Boom('Expected img for product to already be uploaded', { statusCode: 400 })
843
+ return { tag: 'image', attrs: {}, content: [{ tag: 'url', attrs: {}, content: Buffer.from(img.url.toString()) }] }
844
+ })
845
+ })
846
+ }
847
+ if (typeof product.price !== 'undefined') content.push({ tag: 'price', attrs: {}, content: Buffer.from(product.price.toString()) })
848
+ if (typeof product.currency !== 'undefined') content.push({ tag: 'currency', attrs: {}, content: Buffer.from(product.currency) })
849
+ if ('originCountryCode' in product) {
850
+ if (typeof product.originCountryCode === 'undefined') attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT'
851
+ else content.push({ tag: 'compliance_info', attrs: {}, content: [{ tag: 'country_code_origin', attrs: {}, content: Buffer.from(product.originCountryCode) }] })
852
+ }
853
+ if (typeof product.isHidden !== 'undefined') attrs['is_hidden'] = product.isHidden.toString()
854
+ return { tag: 'product', attrs, content }
855
+ }
856
+
857
+ export const parseProductNode = productNode => {
858
+ const isHidden = productNode.attrs.is_hidden === 'true'
859
+ const id = getBinaryNodeChildString(productNode, 'id')
860
+ const mediaNode = getBinaryNodeChild(productNode, 'media')
861
+ const statusInfoNode = getBinaryNodeChild(productNode, 'status_info')
862
+ return {
863
+ id,
864
+ imageUrls: parseImageUrls(mediaNode),
865
+ reviewStatus: { whatsapp: getBinaryNodeChildString(statusInfoNode, 'status') },
866
+ availability: 'in stock',
867
+ name: getBinaryNodeChildString(productNode, 'name'),
868
+ retailerId: getBinaryNodeChildString(productNode, 'retailer_id'),
869
+ url: getBinaryNodeChildString(productNode, 'url'),
870
+ description: getBinaryNodeChildString(productNode, 'description'),
871
+ price: +getBinaryNodeChildString(productNode, 'price'),
872
+ currency: getBinaryNodeChildString(productNode, 'currency'),
873
+ isHidden
874
+ }
875
+ }
876
+
877
+ export async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
878
+ return { ...product, images: product.images ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs) : product.images }
879
+ }
880
+
881
+ export const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
882
+ return Promise.all(
883
+ images.map(async img => {
884
+ if ('url' in img) {
885
+ const url = img.url.toString()
886
+ if (url.includes('.whatsapp.net')) return { url }
887
+ }
888
+ const { stream } = await getStream(img)
889
+ const hasher = createHash('sha256')
890
+ const filePath = join(tmpdir(), 'img' + generateMessageIDV2())
891
+ const encFileWriteStream = createWriteStream(filePath)
892
+ for await (const block of stream) {
893
+ hasher.update(block)
894
+ encFileWriteStream.write(block)
895
+ }
896
+ const sha = hasher.digest('base64')
897
+ const { directPath } = await waUploadToServer(filePath, { mediaType: 'product-catalog-image', fileEncSha256B64: sha, timeoutMs })
898
+ await fs.unlink(filePath).catch(err => console.log('Error deleting temp file ', err))
899
+ return { url: getUrlFromDirectPath(directPath) }
900
+ })
901
+ )
902
+ }
903
+
904
+ const parseImageUrls = mediaNode => {
905
+ const imgNode = getBinaryNodeChild(mediaNode, 'image')
906
+ return { requested: getBinaryNodeChildString(imgNode, 'request_image_url'), original: getBinaryNodeChildString(imgNode, 'original_image_url') }
907
+ }
908
+
909
+ const parseStatusInfo = mediaNode => {
910
+ const node = getBinaryNodeChild(mediaNode, 'status_info')
911
+ return { status: getBinaryNodeChildString(node, 'status'), canAppeal: getBinaryNodeChildString(node, 'can_appeal') === 'true' }
912
+ }