@badzz88/baileys 8.4.7 → 8.4.9

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 (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +347 -6
  4. package/WAProto/fix-import.js +38 -0
  5. package/WAProto/fix-imports.js +86 -85
  6. package/WAProto/index.d.ts +4913 -25
  7. package/WAProto/index.js +14074 -98
  8. package/package.json +50 -90
  9. package/src/Defaults/index.js +201 -0
  10. package/src/Defaults/phonenumber-mcc.json +223 -0
  11. package/src/Signal/Group/ciphertext-message.js +15 -0
  12. package/src/Signal/Group/group-session-builder.js +92 -0
  13. package/src/Signal/Group/group_cipher.js +89 -0
  14. package/src/Signal/Group/index.js +136 -0
  15. package/src/Signal/Group/keyhelper.js +73 -0
  16. package/src/Signal/Group/sender-chain-key.js +32 -0
  17. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/src/Signal/Group/sender-key-message.js +69 -0
  19. package/src/Signal/Group/sender-key-name.js +50 -0
  20. package/src/Signal/Group/sender-key-record.js +44 -0
  21. package/src/Signal/Group/sender-key-state.js +97 -0
  22. package/src/Signal/Group/sender-message-key.js +30 -0
  23. package/src/Signal/libsignal.js +470 -0
  24. package/src/Signal/lid-mapping.js +262 -0
  25. package/src/Socket/Client/index.js +30 -0
  26. package/src/Socket/Client/types.js +13 -0
  27. package/src/Socket/Client/websocket.js +62 -0
  28. package/src/Socket/aigroups.js +240 -0
  29. package/src/Socket/business.js +422 -0
  30. package/src/Socket/chats.js +2374 -0
  31. package/src/Socket/communities.js +580 -0
  32. package/src/Socket/graphql.js +915 -0
  33. package/src/Socket/groups.js +812 -0
  34. package/src/Socket/index.js +37 -0
  35. package/src/Socket/interactive-handler.js +579 -0
  36. package/src/Socket/interop.js +566 -0
  37. package/src/Socket/managed-account.js +214 -0
  38. package/src/Socket/messages-recv.js +3012 -0
  39. package/src/Socket/messages-send.js +2163 -0
  40. package/{lib → src}/Socket/mex.js +11 -5
  41. package/src/Socket/newsletter.js +1057 -0
  42. package/src/Socket/privacy.js +452 -0
  43. package/src/Socket/registration.js +434 -0
  44. package/src/Socket/socket.js +1079 -0
  45. package/src/Socket/text-router.js +67 -0
  46. package/src/Socket/username.js +234 -0
  47. package/src/Store/index.js +36 -0
  48. package/src/Store/make-cache-manager-store.js +90 -0
  49. package/src/Store/make-in-memory-store.js +506 -0
  50. package/src/Store/make-ordered-dictionary.js +81 -0
  51. package/src/Store/object-repository.js +29 -0
  52. package/src/Types/Auth.js +38 -0
  53. package/src/Types/Bussines.js +2 -0
  54. package/src/Types/Call.js +2 -0
  55. package/src/Types/Chat.js +4 -0
  56. package/src/Types/Contact.js +2 -0
  57. package/src/Types/Events.js +2 -0
  58. package/src/Types/GroupMetadata.js +2 -0
  59. package/src/Types/Label.js +27 -0
  60. package/src/Types/LabelAssociation.js +9 -0
  61. package/src/Types/Message.js +95 -0
  62. package/src/Types/Newsletter.js +152 -0
  63. package/src/Types/Product.js +2 -0
  64. package/src/Types/Signal.js +2 -0
  65. package/src/Types/Socket.js +2 -0
  66. package/src/Types/State.js +70 -0
  67. package/src/Types/USync.js +2 -0
  68. package/src/Types/index.js +54 -0
  69. package/src/Utils/auth-utils.js +306 -0
  70. package/src/Utils/browser-utils.js +114 -0
  71. package/src/Utils/business.js +247 -0
  72. package/src/Utils/chat-utils.js +1272 -0
  73. package/src/Utils/consumer-application.js +107 -0
  74. package/src/Utils/crypto.js +125 -0
  75. package/src/Utils/decode-wa-message.js +808 -0
  76. package/src/Utils/event-buffer.js +586 -0
  77. package/src/Utils/generics.js +640 -0
  78. package/src/Utils/group-history.js +60 -0
  79. package/src/Utils/history.js +244 -0
  80. package/src/Utils/identity-change-handler.js +52 -0
  81. package/src/Utils/index.js +53 -0
  82. package/src/Utils/jid-display-normalization.js +218 -0
  83. package/src/Utils/link-preview.js +143 -0
  84. package/src/Utils/logger.js +9 -0
  85. package/src/Utils/lt-hash.js +10 -0
  86. package/src/Utils/make-mutex.js +36 -0
  87. package/src/Utils/message-composer.js +479 -0
  88. package/src/Utils/message-inspect.js +400 -0
  89. package/src/Utils/message-retry-manager.js +231 -0
  90. package/src/Utils/messages-media.js +943 -0
  91. package/src/Utils/messages.js +2490 -0
  92. package/src/Utils/meta-ai-msmsg.js +133 -0
  93. package/src/Utils/noise-handler.js +194 -0
  94. package/src/Utils/offline-node-processor.js +42 -0
  95. package/src/Utils/pre-key-manager.js +107 -0
  96. package/src/Utils/process-message.js +1047 -0
  97. package/src/Utils/reporting-utils.js +262 -0
  98. package/src/Utils/signal.js +192 -0
  99. package/src/Utils/stanza-ack.js +74 -0
  100. package/src/Utils/sync-action-utils.js +54 -0
  101. package/src/Utils/tc-token-utils.js +161 -0
  102. package/src/Utils/use-multi-file-auth-state.js +121 -0
  103. package/src/Utils/validate-connection.js +248 -0
  104. package/src/Utils/voip-rekey.js +22 -0
  105. package/src/WABinary/constants.js +1304 -0
  106. package/src/WABinary/decode.js +377 -0
  107. package/src/WABinary/encode.js +58 -0
  108. package/src/WABinary/generic-utils.js +148 -0
  109. package/src/WABinary/index.js +33 -0
  110. package/src/WABinary/jid-utils.js +374 -0
  111. package/src/WABinary/types.js +2 -0
  112. package/src/WAM/BinaryInfo.js +13 -0
  113. package/src/WAM/constants.js +39486 -0
  114. package/src/WAM/encode.js +142 -0
  115. package/src/WAM/index.js +31 -0
  116. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  117. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  118. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  119. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  120. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  121. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  122. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  123. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  124. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  125. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  126. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  127. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  128. package/src/WAUSync/Protocols/index.js +40 -0
  129. package/src/WAUSync/USyncBackoff.js +31 -0
  130. package/src/WAUSync/USyncQuery.js +204 -0
  131. package/src/WAUSync/USyncUser.js +58 -0
  132. package/src/WAUSync/index.js +32 -0
  133. package/src/antiban.js +4726 -0
  134. package/{lib → src}/index.js +48 -15
  135. package/lib/Defaults/index.js +0 -130
  136. package/lib/Signal/Group/ciphertext-message.js +0 -12
  137. package/lib/Signal/Group/group-session-builder.js +0 -30
  138. package/lib/Signal/Group/group_cipher.js +0 -82
  139. package/lib/Signal/Group/index.js +0 -12
  140. package/lib/Signal/Group/keyhelper.js +0 -18
  141. package/lib/Signal/Group/sender-chain-key.js +0 -26
  142. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  143. package/lib/Signal/Group/sender-key-message.js +0 -66
  144. package/lib/Signal/Group/sender-key-name.js +0 -48
  145. package/lib/Signal/Group/sender-key-record.js +0 -41
  146. package/lib/Signal/Group/sender-key-state.js +0 -84
  147. package/lib/Signal/Group/sender-message-key.js +0 -26
  148. package/lib/Signal/libsignal.js +0 -431
  149. package/lib/Signal/lid-mapping.js +0 -277
  150. package/lib/Socket/Client/index.js +0 -3
  151. package/lib/Socket/Client/types.js +0 -11
  152. package/lib/Socket/Client/websocket.js +0 -54
  153. package/lib/Socket/business.js +0 -379
  154. package/lib/Socket/chats.js +0 -1193
  155. package/lib/Socket/communities.js +0 -431
  156. package/lib/Socket/groups.js +0 -374
  157. package/lib/Socket/index.js +0 -12
  158. package/lib/Socket/luxu.js +0 -386
  159. package/lib/Socket/messages-recv.js +0 -1916
  160. package/lib/Socket/messages-send.js +0 -1453
  161. package/lib/Socket/newsletter.js +0 -251
  162. package/lib/Socket/socket.js +0 -980
  163. package/lib/Socket/username.js +0 -146
  164. package/lib/Store/index.js +0 -10
  165. package/lib/Store/keyed-db.js +0 -108
  166. package/lib/Store/make-cache-manager-store.js +0 -85
  167. package/lib/Store/make-in-memory-store.js +0 -198
  168. package/lib/Store/make-ordered-dictionary.js +0 -75
  169. package/lib/Store/object-repository.js +0 -32
  170. package/lib/Types/Auth.js +0 -2
  171. package/lib/Types/Bussines.js +0 -2
  172. package/lib/Types/Call.js +0 -2
  173. package/lib/Types/Chat.js +0 -8
  174. package/lib/Types/Contact.js +0 -2
  175. package/lib/Types/Events.js +0 -2
  176. package/lib/Types/GroupMetadata.js +0 -2
  177. package/lib/Types/Label.js +0 -25
  178. package/lib/Types/LabelAssociation.js +0 -7
  179. package/lib/Types/Message.js +0 -11
  180. package/lib/Types/Mex.js +0 -37
  181. package/lib/Types/Product.js +0 -2
  182. package/lib/Types/Signal.js +0 -2
  183. package/lib/Types/Socket.js +0 -3
  184. package/lib/Types/State.js +0 -56
  185. package/lib/Types/USync.js +0 -2
  186. package/lib/Types/index.js +0 -26
  187. package/lib/Utils/auth-utils.js +0 -302
  188. package/lib/Utils/browser-utils.js +0 -49
  189. package/lib/Utils/business.js +0 -231
  190. package/lib/Utils/chat-utils.js +0 -872
  191. package/lib/Utils/companion-reg-client-utils.js +0 -35
  192. package/lib/Utils/crypto.js +0 -118
  193. package/lib/Utils/decode-wa-message.js +0 -350
  194. package/lib/Utils/event-buffer.js +0 -622
  195. package/lib/Utils/generics.js +0 -403
  196. package/lib/Utils/history.js +0 -134
  197. package/lib/Utils/identity-change-handler.js +0 -50
  198. package/lib/Utils/index.js +0 -23
  199. package/lib/Utils/link-preview.js +0 -85
  200. package/lib/Utils/logger.js +0 -3
  201. package/lib/Utils/lt-hash.js +0 -8
  202. package/lib/Utils/make-mutex.js +0 -33
  203. package/lib/Utils/message-composer.js +0 -273
  204. package/lib/Utils/message-retry-manager.js +0 -265
  205. package/lib/Utils/messages-media.js +0 -788
  206. package/lib/Utils/messages.js +0 -1260
  207. package/lib/Utils/noise-handler.js +0 -201
  208. package/lib/Utils/offline-node-processor.js +0 -40
  209. package/lib/Utils/pre-key-manager.js +0 -106
  210. package/lib/Utils/process-message.js +0 -630
  211. package/lib/Utils/reporting-utils.js +0 -258
  212. package/lib/Utils/signal.js +0 -201
  213. package/lib/Utils/stanza-ack.js +0 -38
  214. package/lib/Utils/sync-action-utils.js +0 -49
  215. package/lib/Utils/tc-token-utils.js +0 -163
  216. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  217. package/lib/Utils/validate-connection.js +0 -203
  218. package/lib/WABinary/constants.js +0 -1301
  219. package/lib/WABinary/decode.js +0 -262
  220. package/lib/WABinary/encode.js +0 -220
  221. package/lib/WABinary/generic-utils.js +0 -204
  222. package/lib/WABinary/index.js +0 -6
  223. package/lib/WABinary/jid-utils.js +0 -98
  224. package/lib/WABinary/types.js +0 -2
  225. package/lib/WAM/BinaryInfo.js +0 -10
  226. package/lib/WAM/constants.js +0 -22853
  227. package/lib/WAM/encode.js +0 -150
  228. package/lib/WAM/index.js +0 -4
  229. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  230. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  231. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  232. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  233. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  234. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  235. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  236. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  237. package/lib/WAUSync/Protocols/index.js +0 -6
  238. package/lib/WAUSync/USyncQuery.js +0 -98
  239. package/lib/WAUSync/USyncUser.js +0 -31
  240. package/lib/WAUSync/index.js +0 -4
@@ -0,0 +1,2163 @@
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ exports.makeMessagesSocket = void 0
9
+ const node_cache_1 = __importDefault(require('@cacheable/node-cache'))
10
+ const boom_1 = require('@hapi/boom')
11
+ const index_js_1 = require('../../WAProto/index.js')
12
+ const Defaults_1 = require('../Defaults')
13
+ const Utils_1 = require('../Utils')
14
+ const link_preview_1 = require('../Utils/link-preview')
15
+ const make_mutex_1 = require('../Utils/make-mutex')
16
+ const reporting_utils_1 = require('../Utils/reporting-utils')
17
+ const tc_token_utils_1 = require('../Utils/tc-token-utils')
18
+ const jid_display_normalization_1 = require('../Utils/jid-display-normalization')
19
+ const WABinary_1 = require('../WABinary')
20
+ const WAUSync_1 = require('../WAUSync')
21
+ const message_composer_1 = require('../Utils/message-composer.js')
22
+ const interactive_handler_1 = require('./interactive-handler.js')
23
+ const username_1 = require('./username')
24
+ const { setBotMessageSecret } = require('../Utils/decode-wa-message')
25
+ const makeMessagesSocket = config => {
26
+ const {
27
+ logger,
28
+ linkPreviewImageThumbnailWidth,
29
+ generateHighQualityLinkPreview,
30
+ options: httpRequestOptions,
31
+ patchMessageBeforeSending,
32
+ cachedGroupMetadata,
33
+ enableRecentMessageCache,
34
+ maxMsgRetryCount
35
+ } = config
36
+ const sock = (0, username_1.makeUsernameSocket)(config)
37
+ const {
38
+ ev,
39
+ authState,
40
+ messageMutex,
41
+ signalRepository,
42
+ upsertMessage,
43
+ query,
44
+ fetchPrivacySettings,
45
+ sendNode,
46
+ groupMetadata,
47
+ groupToggleEphemeral,
48
+ trustInteropContact
49
+ } = sock
50
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
51
+ // Resolve all participant JIDs across the given group JIDs for status targeting.
52
+ // includeMe = false skips the bot's own JID (avoids self-send loops).
53
+ const resolveStatusAudience = async (groupJids, includeMe = false) => {
54
+ const myJid = authState.creds.me?.id
55
+ const seen = new Set()
56
+ const allUsers = []
57
+ for (const gjid of groupJids) {
58
+ let meta
59
+ try {
60
+ meta = cachedGroupMetadata ? await cachedGroupMetadata(gjid) : null
61
+ if (!meta) meta = await groupMetadata(gjid)
62
+ } catch {
63
+ continue
64
+ }
65
+ for (const p of meta?.participants || []) {
66
+ const id = p.id
67
+ if (!id || seen.has(id)) continue
68
+ if (!includeMe && id === myJid) continue
69
+ seen.add(id)
70
+ allUsers.push(id)
71
+ }
72
+ }
73
+ return { allUsers }
74
+ }
75
+ /**
76
+ * Set of tctoken storage JIDs with a fire-and-forget issuePrivacyTokens IQ in flight.
77
+ * Prevents duplicate IQs from rapid back-to-back sends before senderTimestamp persists.
78
+ */
79
+ const inFlightTcTokenIssuance = new Set()
80
+ const userDevicesCache =
81
+ config.userDevicesCache ||
82
+ new node_cache_1.default({
83
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
84
+ useClones: false
85
+ })
86
+ const peerSessionsCache = new node_cache_1.default({
87
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
88
+ useClones: false
89
+ })
90
+ // Initialize message retry manager if enabled
91
+ const messageRetryManager = enableRecentMessageCache
92
+ ? new Utils_1.MessageRetryManager(logger, maxMsgRetryCount)
93
+ : null
94
+ // Prevent race conditions in Signal session encryption by user
95
+ const encryptionMutex = (0, make_mutex_1.makeKeyedMutex)()
96
+ let mediaConn
97
+ const refreshMediaConn = async (forceGet = false) => {
98
+ const media = await mediaConn
99
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
100
+ mediaConn = (async () => {
101
+ const result = await query({
102
+ tag: 'iq',
103
+ attrs: {
104
+ type: 'set',
105
+ xmlns: 'w:m',
106
+ to: WABinary_1.S_WHATSAPP_NET
107
+ },
108
+ content: [{ tag: 'media_conn', attrs: {} }]
109
+ })
110
+ const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn')
111
+ // TODO: explore full length of data that whatsapp provides
112
+ const node = {
113
+ hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
114
+ hostname: attrs.hostname,
115
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
116
+ })),
117
+ auth: mediaConnNode.attrs.auth,
118
+ ttl: +mediaConnNode.attrs.ttl,
119
+ fetchDate: new Date()
120
+ }
121
+ logger.debug('fetched media conn')
122
+ return node
123
+ })()
124
+ }
125
+ return mediaConn
126
+ }
127
+ /**
128
+ * generic send receipt function
129
+ * used for receipts of phone call, read, delivery etc.
130
+ * */
131
+ const sendReceipt = async (jid, participant, messageIds, type, sts) => {
132
+ if (!messageIds || messageIds.length === 0) {
133
+ throw new boom_1.Boom('missing ids in receipt')
134
+ }
135
+ const isInterop = (0, WABinary_1.isInteropUser)(jid)
136
+ const node = {
137
+ tag: 'receipt',
138
+ attrs: {
139
+ id: messageIds[0]
140
+ }
141
+ }
142
+ const isReadReceipt = type === 'read' || type === 'read-self'
143
+ if (isReadReceipt) {
144
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString()
145
+ }
146
+ if (type === 'sender' && ((0, WABinary_1.isPnUser)(jid) || (0, WABinary_1.isLidUser)(jid))) {
147
+ node.attrs.recipient = jid
148
+ node.attrs.to = participant
149
+ } else if (isInterop && !type) {
150
+ // Delivery receipt to interop contact: WA sends to device-qualified JID (user:0@interop)
151
+ const { user } = (0, WABinary_1.jidDecode)(jid)
152
+ node.attrs.to = `${user}:0@interop`
153
+ } else {
154
+ node.attrs.to = jid
155
+ if (participant) {
156
+ node.attrs.participant = participant
157
+ }
158
+ }
159
+ if (type) {
160
+ node.attrs.type = type
161
+ }
162
+ // Interop bridge requires sts (microsecond stanza timestamp) from the original message
163
+ if (isInterop && sts) {
164
+ node.attrs.sts = sts
165
+ }
166
+ const remainingMessageIds = messageIds.slice(1)
167
+ if (remainingMessageIds.length) {
168
+ node.content = [
169
+ {
170
+ tag: 'list',
171
+ attrs: {},
172
+ content: remainingMessageIds.map(id => ({
173
+ tag: 'item',
174
+ attrs: { id }
175
+ }))
176
+ }
177
+ ]
178
+ }
179
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages')
180
+ await sendNode(node)
181
+ }
182
+ /** Correctly bulk send receipts to multiple chats, participants */
183
+ const sendReceipts = async (keys, type) => {
184
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys)
185
+ for (const { jid, participant, messageIds, sts } of recps) {
186
+ await sendReceipt(jid, participant, messageIds, type, sts)
187
+ }
188
+ }
189
+ /** Bulk read messages. Keys can be from different chats & participants */
190
+ const readMessages = async keys => {
191
+ const privacySettings = await fetchPrivacySettings()
192
+ // based on privacy settings, we have to change the read type
193
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
194
+ await sendReceipts(keys, readType)
195
+ }
196
+ /** Fetch all the devices we've to send a message to */
197
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
198
+ const deviceResults = []
199
+ if (!useCache) {
200
+ logger.debug('not using cache for devices')
201
+ }
202
+ const toFetch = []
203
+ const jidsWithUser = jids
204
+ .map(jid => {
205
+ const decoded = (0, WABinary_1.jidDecode)(jid)
206
+ const user = decoded?.user
207
+ const device = decoded?.device
208
+ const isExplicitDevice = typeof device === 'number' && device >= 0
209
+ if (isExplicitDevice && user) {
210
+ deviceResults.push({
211
+ user,
212
+ device,
213
+ jid
214
+ })
215
+ return null
216
+ }
217
+ jid = (0, WABinary_1.jidNormalizedUser)(jid)
218
+ return { jid, user }
219
+ })
220
+ .filter(jid => jid !== null)
221
+ let mgetDevices
222
+ if (useCache && userDevicesCache.mget) {
223
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean)
224
+ mgetDevices = await userDevicesCache.mget(usersToFetch)
225
+ }
226
+ for (const { jid, user } of jidsWithUser) {
227
+ if (useCache) {
228
+ const devices = mgetDevices?.[user] || (userDevicesCache.mget ? undefined : await userDevicesCache.get(user))
229
+ if (devices) {
230
+ const devicesWithJid = devices.map(d => ({
231
+ ...d,
232
+ jid: (0, WABinary_1.jidEncode)(d.user, d.server, d.device)
233
+ }))
234
+ deviceResults.push(...devicesWithJid)
235
+ logger.trace({ user }, 'using cache for devices')
236
+ } else {
237
+ toFetch.push(jid)
238
+ }
239
+ } else {
240
+ toFetch.push(jid)
241
+ }
242
+ }
243
+ if (!toFetch.length) {
244
+ return deviceResults
245
+ }
246
+ const requestedLidUsers = new Set()
247
+ for (const jid of toFetch) {
248
+ if ((0, WABinary_1.isLidUser)(jid) || (0, WABinary_1.isHostedLidUser)(jid)) {
249
+ const user = (0, WABinary_1.jidDecode)(jid)?.user
250
+ if (user) requestedLidUsers.add(user)
251
+ }
252
+ }
253
+ const query = new WAUSync_1.USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol()
254
+ // Attach any already-known LID inline on the <user> node for PN jids, so the
255
+ // LID/contact protocols can use it directly instead of round-tripping.
256
+ const pnJidsToFetch = toFetch.filter(jid => (0, WABinary_1.isPnUser)(jid) || (0, WABinary_1.isHostedPnUser)(jid))
257
+ const cachedLidPairs = pnJidsToFetch.length
258
+ ? (await signalRepository.lidMapping.getLIDsForPNs(pnJidsToFetch)) || []
259
+ : []
260
+ const cachedLidByPn = new Map(cachedLidPairs.map(({ pn, lid }) => [pn, lid]))
261
+ for (const jid of toFetch) {
262
+ const syncUser = new WAUSync_1.USyncUser().withId(jid)
263
+ const cachedLid = cachedLidByPn.get(jid)
264
+ if (cachedLid) syncUser.withLid(cachedLid)
265
+ query.withUser(syncUser)
266
+ }
267
+ const result = await sock.executeUSyncQuery(query)
268
+ if (result) {
269
+ const lidResults = result.list.filter(a => !!a.lid)
270
+ if (lidResults.length > 0) {
271
+ logger.trace('Storing LID maps from device call')
272
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })))
273
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
274
+ try {
275
+ const lids = lidResults.map(a => a.lid)
276
+ if (lids.length) {
277
+ await assertSessions(lids, true)
278
+ }
279
+ } catch (e) {
280
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs')
281
+ }
282
+ }
283
+ const extracted = (0, Utils_1.extractDeviceJids)(
284
+ result?.list,
285
+ authState.creds.me.id,
286
+ authState.creds.me.lid,
287
+ ignoreZeroDevices
288
+ )
289
+ const deviceMap = {}
290
+ for (const item of extracted) {
291
+ deviceMap[item.user] = deviceMap[item.user] || []
292
+ deviceMap[item.user]?.push(item)
293
+ }
294
+ // Process each user's devices as a group for bulk LID migration
295
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
296
+ const isLidUser = requestedLidUsers.has(user)
297
+ // Process all devices for this user
298
+ for (const item of userDevices) {
299
+ const finalJid = isLidUser
300
+ ? (0, WABinary_1.jidEncode)(user, item.server, item.device)
301
+ : (0, WABinary_1.jidEncode)(item.user, item.server, item.device)
302
+ deviceResults.push({
303
+ ...item,
304
+ jid: finalJid
305
+ })
306
+ logger.debug(
307
+ {
308
+ user: item.user,
309
+ device: item.device,
310
+ finalJid,
311
+ usedLid: isLidUser
312
+ },
313
+ 'Processed device with LID priority'
314
+ )
315
+ }
316
+ }
317
+ if (userDevicesCache.mset) {
318
+ // if the cache supports mset, we can set all devices in one go
319
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })))
320
+ } else {
321
+ for (const key in deviceMap) {
322
+ if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key])
323
+ }
324
+ }
325
+ const userDeviceUpdates = {}
326
+ for (const [userId, devices] of Object.entries(deviceMap)) {
327
+ if (devices && devices.length > 0) {
328
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0')
329
+ }
330
+ }
331
+ if (Object.keys(userDeviceUpdates).length > 0) {
332
+ try {
333
+ await authState.keys.set({ 'device-list': userDeviceUpdates })
334
+ logger.debug(
335
+ { userCount: Object.keys(userDeviceUpdates).length },
336
+ 'stored user device lists for bulk migration'
337
+ )
338
+ } catch (error) {
339
+ logger.warn({ error }, 'failed to store user device lists')
340
+ }
341
+ }
342
+ }
343
+ return deviceResults
344
+ }
345
+ /**
346
+ * Update Member Label
347
+ */
348
+ const updateMemberLabel = (jid, memberLabel) => {
349
+ return relayMessage(
350
+ jid,
351
+ {
352
+ protocolMessage: {
353
+ type: index_js_1.proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
354
+ memberLabel: {
355
+ label: memberLabel?.slice(0, 30),
356
+ labelTimestamp: (0, Utils_1.unixTimestampSeconds)()
357
+ }
358
+ }
359
+ },
360
+ {
361
+ additionalNodes: [
362
+ {
363
+ tag: 'meta',
364
+ attrs: {
365
+ tag_reason: 'user_update',
366
+ appdata: 'member_tag'
367
+ },
368
+ content: undefined
369
+ }
370
+ ]
371
+ }
372
+ )
373
+ }
374
+ const assertSessions = async (jids, force) => {
375
+ let didFetchNewSession = false
376
+ const uniqueJids = [...new Set(jids)] // Deduplicate JIDs
377
+ const jidsRequiringFetch = []
378
+ logger.debug({ jids }, 'assertSessions call with jids')
379
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
380
+ for (const jid of uniqueJids) {
381
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid)
382
+ const cachedSession = peerSessionsCache.get(signalId)
383
+ if (cachedSession !== undefined) {
384
+ if (cachedSession && !force) {
385
+ continue // Session exists in cache
386
+ }
387
+ } else {
388
+ const sessionValidation = await signalRepository.validateSession(jid)
389
+ const hasSession = sessionValidation.exists
390
+ peerSessionsCache.set(signalId, hasSession)
391
+ if (hasSession && !force) {
392
+ continue
393
+ }
394
+ }
395
+ jidsRequiringFetch.push(jid)
396
+ }
397
+ if (jidsRequiringFetch.length) {
398
+ // LID if mapped, otherwise original; interop JIDs pass through as-is
399
+ const wireJids = [
400
+ ...jidsRequiringFetch.filter(jid => !!(0, WABinary_1.isLidUser)(jid) || !!(0, WABinary_1.isHostedLidUser)(jid)),
401
+ ...(
402
+ (await signalRepository.lidMapping.getLIDsForPNs(
403
+ jidsRequiringFetch.filter(jid => !!(0, WABinary_1.isPnUser)(jid) || !!(0, WABinary_1.isHostedPnUser)(jid))
404
+ )) || []
405
+ ).map(a => a.lid),
406
+ ...jidsRequiringFetch.filter(jid => (0, WABinary_1.isInteropUser)(jid))
407
+ ]
408
+ const interopFetches = wireJids.filter(j => (0, WABinary_1.isInteropUser)(j))
409
+ if (interopFetches.length) {
410
+ logger.info({ interopFetches }, '[interop] fetching pre-key bundle for interop device(s)')
411
+ }
412
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions')
413
+ if (!wireJids.length) {
414
+ logger.debug({ jidsRequiringFetch }, 'assertSessions: no wire JIDs to fetch (all unsupported domain)')
415
+ return didFetchNewSession
416
+ }
417
+ const result = await query({
418
+ tag: 'iq',
419
+ attrs: {
420
+ xmlns: 'encrypt',
421
+ type: 'get',
422
+ to: WABinary_1.S_WHATSAPP_NET
423
+ },
424
+ content: [
425
+ {
426
+ tag: 'key',
427
+ attrs: {},
428
+ content: wireJids.map(jid => {
429
+ const attrs = { jid }
430
+ if (force) attrs.reason = 'identity'
431
+ return { tag: 'user', attrs }
432
+ })
433
+ }
434
+ ]
435
+ })
436
+ if (interopFetches.length) {
437
+ logger.debug({ interopFetches }, '[interop] pre-key IQ response received')
438
+ }
439
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository)
440
+ didFetchNewSession = true
441
+ // Cache fetched sessions using wire JIDs
442
+ for (const wireJid of wireJids) {
443
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid)
444
+ peerSessionsCache.set(signalId, true)
445
+ }
446
+ }
447
+ return didFetchNewSession
448
+ }
449
+ const sendPeerDataOperationMessage = async pdoMessage => {
450
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
451
+ if (!authState.creds.me?.id) {
452
+ throw new boom_1.Boom('Not authenticated')
453
+ }
454
+ const protocolMessage = {
455
+ protocolMessage: {
456
+ peerDataOperationRequestMessage: pdoMessage,
457
+ type: index_js_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
458
+ }
459
+ }
460
+ const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)
461
+ const msgId = await relayMessage(meJid, protocolMessage, {
462
+ additionalAttributes: {
463
+ category: 'peer',
464
+ push_priority: 'high_force'
465
+ },
466
+ additionalNodes: [
467
+ {
468
+ tag: 'meta',
469
+ attrs: { appdata: 'default' }
470
+ }
471
+ ]
472
+ })
473
+ return msgId
474
+ }
475
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
476
+ if (!recipientJids.length) {
477
+ return { nodes: [], shouldIncludeDeviceIdentity: false }
478
+ }
479
+ const patched = await patchMessageBeforeSending(message, recipientJids)
480
+ const patchedMessages = Array.isArray(patched)
481
+ ? patched
482
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }))
483
+ let shouldIncludeDeviceIdentity = false
484
+ const meId = authState.creds.me.id
485
+ const meLid = authState.creds.me?.lid
486
+ const meLidUser = meLid ? (0, WABinary_1.jidDecode)(meLid)?.user : null
487
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
488
+ try {
489
+ if (!jid) return null
490
+ let msgToEncrypt = patchedMessage
491
+ if (dsmMessage) {
492
+ const { user: targetUser } = (0, WABinary_1.jidDecode)(jid)
493
+ const { user: ownPnUser } = (0, WABinary_1.jidDecode)(meId)
494
+ const ownLidUser = meLidUser
495
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser)
496
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
497
+ if (isOwnUser && !isExactSenderDevice) {
498
+ msgToEncrypt = dsmMessage
499
+ logger.debug({ jid, targetUser }, 'Using DSM for own device')
500
+ }
501
+ }
502
+ const bytes = (0, Utils_1.encodeWAMessage)(msgToEncrypt)
503
+ const mutexKey = jid
504
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
505
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
506
+ if (type === 'pkmsg') {
507
+ shouldIncludeDeviceIdentity = true
508
+ }
509
+ return {
510
+ tag: 'to',
511
+ attrs: { jid },
512
+ content: [
513
+ {
514
+ tag: 'enc',
515
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
516
+ content: ciphertext
517
+ }
518
+ ]
519
+ }
520
+ })
521
+ return node
522
+ } catch (err) {
523
+ logger.error({ jid, err }, 'Failed to encrypt for recipient')
524
+ return null
525
+ }
526
+ })
527
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null)
528
+ if (recipientJids.length > 0 && nodes.length === 0) {
529
+ throw new boom_1.Boom('All encryptions failed', { statusCode: 500 })
530
+ }
531
+ return { nodes, shouldIncludeDeviceIdentity }
532
+ }
533
+ const relayMessage = async (
534
+ jid,
535
+ message,
536
+ {
537
+ messageId: msgId,
538
+ participant,
539
+ additionalAttributes,
540
+ additionalNodes,
541
+ useUserDevicesCache,
542
+ useCachedGroupMetadata,
543
+ statusJidList,
544
+ statusPrivacy,
545
+ AI = false
546
+ }
547
+ ) => {
548
+ const meId = authState.creds.me.id
549
+ const meLid = authState.creds.me?.lid
550
+ const isRetryResend = Boolean(participant?.jid)
551
+ let shouldIncludeDeviceIdentity = isRetryResend
552
+ const statusJid = 'status@broadcast'
553
+ const { user, server } = (0, WABinary_1.jidDecode)(jid)
554
+ const isGroup = server === 'g.us'
555
+ const isStatus = jid === statusJid
556
+ const isLid = server === 'lid'
557
+ const isNewsletter = server === 'newsletter'
558
+ const isInterop = (0, WABinary_1.isInteropUser)(jid)
559
+ const isGroupOrStatus = isGroup || isStatus
560
+ const finalJid = jid
561
+ msgId = msgId || (0, Utils_1.generateMessageIDV2)(meId)
562
+ useUserDevicesCache = useUserDevicesCache !== false
563
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
564
+ const participants = []
565
+ const destinationJid = !isStatus ? finalJid : statusJid
566
+ const binaryNodeContent = []
567
+ const devices = []
568
+ let reportingMessage
569
+ const meMsg = {
570
+ deviceSentMessage: {
571
+ destinationJid,
572
+ message
573
+ },
574
+ messageContextInfo: message.messageContextInfo
575
+ }
576
+ const extraAttrs = {}
577
+
578
+ const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
579
+
580
+ const messages = Utils_1.normalizeMessageContent(message)
581
+
582
+ const buttonType = getButtonType(messages)
583
+ const pollMessage = messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
584
+
585
+ if (participant) {
586
+ if (!isGroup && !isStatus) {
587
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' }
588
+ }
589
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid)
590
+ devices.push({
591
+ user,
592
+ device,
593
+ jid: participant.jid
594
+ })
595
+ }
596
+ await authState.keys.transaction(async () => {
597
+ const mediaType = getMediaType(message)
598
+ if (mediaType) {
599
+ extraAttrs['mediatype'] = mediaType
600
+ }
601
+ if (isNewsletter) {
602
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message
603
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched)
604
+ binaryNodeContent.push({
605
+ tag: 'plaintext',
606
+ attrs: {},
607
+ content: bytes
608
+ })
609
+ const stanza = {
610
+ tag: 'message',
611
+ attrs: {
612
+ to: jid,
613
+ id: msgId,
614
+ type: getTypeMessage(message),
615
+ ...(additionalAttributes || {})
616
+ },
617
+ content: binaryNodeContent
618
+ }
619
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`)
620
+ await sendNode(stanza)
621
+ return
622
+ }
623
+ if (
624
+ (0, Utils_1.normalizeMessageContent)(message)?.pinInChatMessage ||
625
+ (0, Utils_1.normalizeMessageContent)(message)?.reactionMessage
626
+ ) {
627
+ extraAttrs['decrypt-fail'] = 'hide'
628
+ }
629
+ if (isGroupOrStatus && !isRetryResend) {
630
+ const [groupData, senderKeyMap] = await Promise.all([
631
+ (async () => {
632
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
633
+ if (groupData && Array.isArray(groupData?.participants)) {
634
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
635
+ } else if (!isStatus) {
636
+ groupData = await groupMetadata(jid) // TODO: start storing group participant list + addr mode in Signal & stop relying on this
637
+ }
638
+ return groupData
639
+ })(),
640
+ (async () => {
641
+ if (!participant && !isStatus) {
642
+ // what if sender memory is less accurate than the cached metadata
643
+ // on participant change in group, we should do sender memory manipulation
644
+ const result = await authState.keys.get('sender-key-memory', [jid]) // TODO: check out what if the sender key memory doesn't include the LID stuff now?
645
+ return result[jid] || {}
646
+ }
647
+ return {}
648
+ })()
649
+ ])
650
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : []
651
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
652
+ additionalAttributes = {
653
+ ...additionalAttributes,
654
+ expiration: groupData.ephemeralDuration.toString()
655
+ }
656
+ }
657
+ if (isStatus && statusJidList) {
658
+ participantsList.push(...statusJidList)
659
+ }
660
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
661
+ devices.push(...additionalDevices)
662
+ if (isGroup) {
663
+ additionalAttributes = {
664
+ ...additionalAttributes,
665
+ addressing_mode: groupData?.addressingMode || 'lid'
666
+ }
667
+ }
668
+ if (message?.groupStatusMessageV2 && !message?.messageContextInfo?.messageSecret) {
669
+ const { randomBytes } = require('crypto')
670
+ message = {
671
+ ...message,
672
+ messageContextInfo: {
673
+ ...(message.messageContextInfo || {}),
674
+ messageSecret: randomBytes(32)
675
+ },
676
+ groupStatusMessageV2: {
677
+ ...message.groupStatusMessageV2,
678
+ message: {
679
+ ...(message.groupStatusMessageV2.message || {}),
680
+ messageContextInfo: {
681
+ ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
682
+ messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
683
+ }
684
+ }
685
+ }
686
+ }
687
+ }
688
+ if (message.listMessage) {
689
+ const list = message.listMessage
690
+ const interactiveMessage = {
691
+ nativeFlowMessage: {
692
+ buttons: [
693
+ {
694
+ name: 'single_select',
695
+ buttonParamsJson: JSON.stringify({
696
+ title: list.buttonText || 'Select',
697
+ sections: (list.sections || []).map(section => ({
698
+ title: section.title || '',
699
+ highlight_label: '',
700
+ rows: (section.rows || []).map(row => ({
701
+ header: '',
702
+ title: row.title || '',
703
+ description: row.description || '',
704
+ id: row.rowId || row.id || ''
705
+ }))
706
+ }))
707
+ })
708
+ }
709
+ ],
710
+ messageParamsJson: '',
711
+ messageVersion: 1
712
+ },
713
+ body: { text: list.description || '' },
714
+ footer: list.footerText ? { text: list.footerText } : undefined,
715
+ header: list.title ? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
716
+ contextInfo: list.contextInfo
717
+ }
718
+ message = { interactiveMessage }
719
+ } else if (message.buttonsMessage) {
720
+ const bMsg = message.buttonsMessage
721
+ const buttons = (bMsg.buttons || []).map(btn => ({
722
+ name: 'quick_reply',
723
+ buttonParamsJson: JSON.stringify({
724
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
725
+ id: btn.buttonId || btn.buttonText?.displayText || ''
726
+ })
727
+ }))
728
+ const interactiveMessage = {
729
+ nativeFlowMessage: {
730
+ buttons,
731
+ messageParamsJson: '',
732
+ messageVersion: 1
733
+ },
734
+ body: { text: bMsg.contentText || bMsg.text || '' },
735
+ footer: bMsg.footerText ? { text: bMsg.footerText } : undefined,
736
+ header: bMsg.text
737
+ ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
738
+ : bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
739
+ ? {
740
+ hasMediaAttachment: true,
741
+ ...(bMsg.imageMessage ? { imageMessage: bMsg.imageMessage } : {}),
742
+ ...(bMsg.videoMessage ? { videoMessage: bMsg.videoMessage } : {})
743
+ }
744
+ : undefined,
745
+ contextInfo: bMsg.contextInfo
746
+ }
747
+ message = { interactiveMessage }
748
+ } else if (message.templateMessage) {
749
+ const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate
750
+ if (tmpl) {
751
+ const hydratedButtons = tmpl.hydratedButtons || []
752
+ const buttons = hydratedButtons
753
+ .map(hBtn => {
754
+ if (hBtn.quickReplyButton) {
755
+ return {
756
+ name: 'quick_reply',
757
+ buttonParamsJson: JSON.stringify({
758
+ display_text: hBtn.quickReplyButton.displayText || '',
759
+ id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || ''
760
+ })
761
+ }
762
+ } else if (hBtn.urlButton) {
763
+ return {
764
+ name: 'cta_url',
765
+ buttonParamsJson: JSON.stringify({
766
+ display_text: hBtn.urlButton.displayText || '',
767
+ url: hBtn.urlButton.url || '',
768
+ merchant_url: hBtn.urlButton.url || ''
769
+ })
770
+ }
771
+ } else if (hBtn.callButton) {
772
+ return {
773
+ name: 'cta_call',
774
+ buttonParamsJson: JSON.stringify({
775
+ display_text: hBtn.callButton.displayText || '',
776
+ phone_number: hBtn.callButton.phoneNumber || ''
777
+ })
778
+ }
779
+ }
780
+ return null
781
+ })
782
+ .filter(Boolean)
783
+ const interactiveMessage = {
784
+ nativeFlowMessage: {
785
+ buttons,
786
+ messageParamsJson: '',
787
+ messageVersion: 1
788
+ },
789
+ body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
790
+ footer: tmpl.hydratedFooterText ? { text: tmpl.hydratedFooterText } : undefined,
791
+ header: tmpl.hydratedTitleText
792
+ ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
793
+ : tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
794
+ ? {
795
+ hasMediaAttachment: true,
796
+ ...(tmpl.imageMessage ? { imageMessage: tmpl.imageMessage } : {}),
797
+ ...(tmpl.videoMessage ? { videoMessage: tmpl.videoMessage } : {})
798
+ }
799
+ : undefined,
800
+ contextInfo: tmpl.contextInfo
801
+ }
802
+ message = { interactiveMessage }
803
+ }
804
+ }
805
+ const patched = await patchMessageBeforeSending(message)
806
+ if (Array.isArray(patched)) {
807
+ throw new boom_1.Boom('Per-jid patching is not supported in groups')
808
+ }
809
+ const bytes = (0, Utils_1.encodeWAMessage)(patched)
810
+ reportingMessage = patched
811
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
812
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId
813
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
814
+ group: destinationJid,
815
+ data: bytes,
816
+ meId: groupSenderIdentity
817
+ })
818
+ const senderKeyRecipients = []
819
+ for (const device of devices) {
820
+ const deviceJid = device.jid
821
+ const hasKey = !!senderKeyMap[deviceJid]
822
+ if (
823
+ (!hasKey || !!participant) &&
824
+ !(0, WABinary_1.isHostedLidUser)(deviceJid) &&
825
+ !(0, WABinary_1.isHostedPnUser)(deviceJid) &&
826
+ device.device !== 99
827
+ ) {
828
+ //todo: revamp all this logic
829
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
830
+ senderKeyRecipients.push(deviceJid)
831
+ senderKeyMap[deviceJid] = true
832
+ }
833
+ }
834
+ if (senderKeyRecipients.length) {
835
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
836
+ const senderKeyMsg = {
837
+ senderKeyDistributionMessage: {
838
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
839
+ groupId: destinationJid
840
+ }
841
+ }
842
+ const senderKeySessionTargets = senderKeyRecipients
843
+ await assertSessions(senderKeySessionTargets)
844
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
845
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
846
+ participants.push(...result.nodes)
847
+ }
848
+ binaryNodeContent.push({
849
+ tag: 'enc',
850
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
851
+ content: ciphertext
852
+ })
853
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
854
+ } else {
855
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
856
+ // TODO: investigate if this is true
857
+ let ownId = meId
858
+ if (isLid && meLid) {
859
+ ownId = meLid
860
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
861
+ } else {
862
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
863
+ }
864
+ const { user: ownUser } = (0, WABinary_1.jidDecode)(ownId)
865
+ if (!participant) {
866
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid])
867
+ reportingMessage = Array.isArray(patchedForReporting)
868
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
869
+ : patchedForReporting
870
+ }
871
+ if (!isRetryResend) {
872
+ const targetUserServer = isLid ? 'lid' : isInterop ? 'interop' : 's.whatsapp.net'
873
+ devices.push({
874
+ user,
875
+ device: 0,
876
+ jid: (0, WABinary_1.jidEncode)(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
877
+ })
878
+ // Interop contacts don't receive a copy to own devices — native WA sends only one flat <enc>
879
+ if (user !== ownUser && !isInterop) {
880
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net'
881
+ const ownUserForAddressing =
882
+ isLid && meLid ? (0, WABinary_1.jidDecode)(meLid).user : (0, WABinary_1.jidDecode)(meId).user
883
+ devices.push({
884
+ user: ownUserForAddressing,
885
+ device: 0,
886
+ jid: (0, WABinary_1.jidEncode)(ownUserForAddressing, ownUserServer, 0)
887
+ })
888
+ }
889
+ if (additionalAttributes?.['category'] !== 'peer' && !isInterop) {
890
+ // Clear placeholders and enumerate actual devices
891
+ devices.length = 0
892
+ // Use conversation-appropriate sender identity
893
+ const senderIdentity =
894
+ isLid && meLid
895
+ ? (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(meLid)?.user, 'lid', undefined)
896
+ : (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(meId)?.user, 's.whatsapp.net', undefined)
897
+ // Enumerate devices for sender and target with consistent addressing
898
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
899
+ devices.push(...sessionDevices)
900
+ logger.debug(
901
+ {
902
+ deviceCount: devices.length,
903
+ devices: devices.map(d => `${d.user}:${d.device}@${(0, WABinary_1.jidDecode)(d.jid)?.server}`)
904
+ },
905
+ 'Device enumeration complete with unified addressing'
906
+ )
907
+ }
908
+ }
909
+ const allRecipients = []
910
+ const meRecipients = []
911
+ const otherRecipients = []
912
+ const { user: mePnUser } = (0, WABinary_1.jidDecode)(meId)
913
+ const { user: meLidUser } = meLid ? (0, WABinary_1.jidDecode)(meLid) : { user: null }
914
+ for (const { user, jid } of devices) {
915
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
916
+ if (isExactSenderDevice) {
917
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
918
+ continue
919
+ }
920
+ // Check if this is our device (could match either PN or LID user)
921
+ const isMe = user === mePnUser || user === meLidUser
922
+ if (isMe) {
923
+ meRecipients.push(jid)
924
+ } else {
925
+ otherRecipients.push(jid)
926
+ }
927
+ allRecipients.push(jid)
928
+ }
929
+ await assertSessions(allRecipients)
930
+ const [
931
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
932
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
933
+ ] = await Promise.all([
934
+ // For own devices: use DSM if available (1:1 chats only)
935
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
936
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
937
+ ])
938
+ participants.push(...meNodes)
939
+ participants.push(...otherNodes)
940
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
941
+ extraAttrs['phash'] = (0, Utils_1.generateParticipantHashV2)([...meRecipients, ...otherRecipients])
942
+ }
943
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
944
+ }
945
+ if (isRetryResend) {
946
+ const isParticipantLid = (0, WABinary_1.isLidUser)(participant.jid)
947
+ const isMe = (0, WABinary_1.areJidsSameUser)(participant.jid, isParticipantLid ? meLid : meId)
948
+ const encodedMessageToSend = isMe
949
+ ? (0, Utils_1.encodeWAMessage)({
950
+ deviceSentMessage: {
951
+ destinationJid,
952
+ message
953
+ }
954
+ })
955
+ : (0, Utils_1.encodeWAMessage)(message)
956
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
957
+ data: encodedMessageToSend,
958
+ jid: participant.jid
959
+ })
960
+ binaryNodeContent.push({
961
+ tag: 'enc',
962
+ attrs: {
963
+ v: '2',
964
+ type,
965
+ count: (participant.count ?? 0).toString()
966
+ },
967
+ content: encryptedContent
968
+ })
969
+ }
970
+ if (participants.length) {
971
+ if (additionalAttributes?.['category'] === 'peer') {
972
+ const peerNode = participants[0]?.content?.[0]
973
+ if (peerNode) {
974
+ binaryNodeContent.push(peerNode) // push only enc
975
+ }
976
+ } else if (isInterop) {
977
+ // Flat <enc> directly on <message> — no <participants> wrapper (native WA behavior).
978
+ // Find the enc for the actual interop recipient, not own-device DSM copy.
979
+ const recipientNode = participants.find(p => (0, WABinary_1.isInteropUser)(p?.attrs?.jid))
980
+ const encNode = (recipientNode ?? participants[0])?.content?.[0]
981
+ if (encNode) {
982
+ binaryNodeContent.push(encNode)
983
+ }
984
+ } else {
985
+ binaryNodeContent.push({
986
+ tag: 'participants',
987
+ attrs: {},
988
+ content: participants
989
+ })
990
+ }
991
+ }
992
+ const stanza = {
993
+ tag: 'message',
994
+ attrs: {
995
+ id: msgId,
996
+ to: destinationJid,
997
+ type: getTypeMessage(message),
998
+ ...(additionalAttributes || {})
999
+ },
1000
+ content: binaryNodeContent
1001
+ }
1002
+ // if the participant to send to is explicitly specified (generally retry recp)
1003
+ // ensure the message is only sent to that person
1004
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
1005
+ if (participant) {
1006
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
1007
+ stanza.attrs.to = destinationJid
1008
+ stanza.attrs.participant = participant.jid
1009
+ } else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
1010
+ stanza.attrs.to = participant.jid
1011
+ stanza.attrs.recipient = destinationJid
1012
+ } else {
1013
+ stanza.attrs.to = participant.jid
1014
+ }
1015
+ } else {
1016
+ stanza.attrs.to = destinationJid
1017
+ }
1018
+ if (shouldIncludeDeviceIdentity) {
1019
+ stanza.content.push({
1020
+ tag: 'device-identity',
1021
+ attrs: {},
1022
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
1023
+ })
1024
+ logger.debug({ jid }, 'adding device identity')
1025
+ }
1026
+
1027
+ if (isGroup && regexGroupOld.test(jid) && !message.reactionMessage) {
1028
+ stanza.content.push({
1029
+ tag: 'multicast',
1030
+ attrs: {}
1031
+ })
1032
+ }
1033
+
1034
+ // Status audience privacy: add <meta status_setting="..."> for all non-revoke sends
1035
+ if (isStatus && statusPrivacy && !additionalAttributes?.edit) {
1036
+ stanza.content.push({
1037
+ tag: 'meta',
1038
+ attrs: { status_setting: statusPrivacy, session_scope: 'status' }
1039
+ })
1040
+ }
1041
+
1042
+ if (pollMessage || messages.eventMessage) {
1043
+ stanza.content.push({
1044
+ tag: 'meta',
1045
+ attrs: messages.eventMessage
1046
+ ? {
1047
+ event_type: 'creation'
1048
+ }
1049
+ : isNewsletter
1050
+ ? {
1051
+ polltype: 'creation',
1052
+ contenttype: pollMessage?.pollContentType === 2 ? 'image' : 'text'
1053
+ }
1054
+ : {
1055
+ polltype: 'creation'
1056
+ }
1057
+ })
1058
+ }
1059
+ if (
1060
+ !isNewsletter &&
1061
+ !isRetryResend &&
1062
+ reportingMessage?.messageContextInfo?.messageSecret &&
1063
+ (0, reporting_utils_1.shouldIncludeReportingToken)(reportingMessage)
1064
+ ) {
1065
+ try {
1066
+ const encoded = (0, Utils_1.encodeWAMessage)(reportingMessage)
1067
+ const reportingKey = {
1068
+ id: msgId,
1069
+ fromMe: true,
1070
+ remoteJid: destinationJid,
1071
+ participant: participant?.jid
1072
+ }
1073
+ const reportingNode = await (0, reporting_utils_1.getMessageReportingToken)(
1074
+ encoded,
1075
+ reportingMessage,
1076
+ reportingKey
1077
+ )
1078
+ if (reportingNode) {
1079
+ stanza.content.push(reportingNode)
1080
+ logger.trace({ jid }, 'added reporting token to message')
1081
+ }
1082
+ } catch (error) {
1083
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token')
1084
+ }
1085
+ }
1086
+
1087
+ let didPushAdditional = false
1088
+ if (!isNewsletter && buttonType) {
1089
+ const buttonsNode = getButtonArgs(messages)
1090
+ const filteredButtons = WABinary_1.getBinaryFilteredButtons(additionalNodes ? additionalNodes : [])
1091
+
1092
+ if (filteredButtons) {
1093
+ stanza.content.push(...additionalNodes)
1094
+ didPushAdditional = true
1095
+ } else {
1096
+ stanza.content.push(buttonsNode)
1097
+ }
1098
+ }
1099
+ if (!AI && (0, WABinary_1.isPnUser)(destinationJid)) {
1100
+ const alreadyHasBizBot =
1101
+ WABinary_1.getBinaryFilteredBizBot(additionalNodes || []) ||
1102
+ WABinary_1.getBinaryFilteredBizBot(stanza.content)
1103
+ if (!alreadyHasBizBot) {
1104
+ stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
1105
+ }
1106
+ } else if (AI && !isGroup && !isStatus && !isNewsletter) {
1107
+ const existingBizBot = WABinary_1.getBinaryFilteredBizBot(additionalNodes || [])
1108
+ if (!existingBizBot) {
1109
+ stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
1110
+ }
1111
+ }
1112
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
1113
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer'
1114
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage
1115
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
1116
+ const tcTokenJid = is1on1Send
1117
+ ? await (0, tc_token_utils_1.resolveTcTokenJid)(destinationJid, getLIDForPN)
1118
+ : destinationJid
1119
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {}
1120
+ const existingTokenEntry = contactTcTokenData[tcTokenJid]
1121
+ let tcTokenBuffer = existingTokenEntry?.token
1122
+ // Treat expired tokens the same as missing — clear from cache
1123
+ if (tcTokenBuffer?.length && (0, tc_token_utils_1.isTcTokenExpired)(existingTokenEntry?.timestamp)) {
1124
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing')
1125
+ tcTokenBuffer = undefined
1126
+ const cleared =
1127
+ existingTokenEntry?.senderTimestamp !== undefined
1128
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
1129
+ : null
1130
+ try {
1131
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } })
1132
+ } catch (err) {
1133
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup')
1134
+ }
1135
+ }
1136
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
1137
+ stanza.content.push({
1138
+ tag: 'tctoken',
1139
+ attrs: {},
1140
+ content: tcTokenBuffer
1141
+ })
1142
+ }
1143
+ // CSToken: HMAC-SHA256(nctSalt, utf8("<user>@lid")) — cold-contact fallback when no tctoken
1144
+ if (is1on1Send && !tcTokenBuffer?.length) {
1145
+ try {
1146
+ const saltStore = await authState.keys.get('nct-salt', ['default'])
1147
+ const nctSalt = saltStore?.['default']
1148
+ if (nctSalt?.length) {
1149
+ const recipientLid = await getLIDForPN(destinationJid)
1150
+ if (recipientLid) {
1151
+ const { createHmac } = require('crypto')
1152
+ const lidStr = (0, WABinary_1.isLidUser)(recipientLid)
1153
+ ? recipientLid
1154
+ : `${recipientLid.split('@')[0]}@lid`
1155
+ const cs = createHmac('sha256', nctSalt).update(lidStr, 'utf8').digest()
1156
+ stanza.content.push({ tag: 'cstoken', attrs: {}, content: cs })
1157
+ logger.debug({ jid: destinationJid, lid: lidStr }, 'nct: attached cstoken')
1158
+ }
1159
+ }
1160
+ } catch (err) {
1161
+ logger.debug({ jid: destinationJid, err: err?.message }, 'nct: cstoken attach failed')
1162
+ }
1163
+ }
1164
+ if (additionalNodes && additionalNodes.length > 0 && !didPushAdditional) {
1165
+ stanza.content.push(...additionalNodes)
1166
+ }
1167
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`)
1168
+ await sendNode(stanza)
1169
+ // Register messageSecret immediately at send time so msmsg replies can be
1170
+ // decrypted even if they arrive before our own message echo comes back.
1171
+ if (message.messageContextInfo?.messageSecret) {
1172
+ setBotMessageSecret(msgId, message.messageContextInfo.messageSecret, destinationJid)
1173
+ }
1174
+ // Fire-and-forget: issue our token to the contact AFTER message send.
1175
+ const isProtocolMsg = !!(0, Utils_1.normalizeMessageContent)(message)?.protocolMessage
1176
+ const isBotOrPSA =
1177
+ destinationJid === WABinary_1.PSA_WID ||
1178
+ (0, WABinary_1.isJidBot)(destinationJid) ||
1179
+ (0, WABinary_1.isJidMetaAI)(destinationJid)
1180
+ if (
1181
+ is1on1Send &&
1182
+ !isProtocolMsg &&
1183
+ !isBotOrPSA &&
1184
+ (0, tc_token_utils_1.shouldSendNewTcToken)(existingTokenEntry?.senderTimestamp) &&
1185
+ !inFlightTcTokenIssuance.has(tcTokenJid)
1186
+ ) {
1187
+ inFlightTcTokenIssuance.add(tcTokenJid)
1188
+ const issueTimestamp = (0, Utils_1.unixTimestampSeconds)()
1189
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
1190
+ ;(0, tc_token_utils_1.resolveIssuanceJid)(
1191
+ destinationJid,
1192
+ sock.serverProps.lidTrustedTokenIssueToLid,
1193
+ getLIDForPN,
1194
+ getPNForLID
1195
+ )
1196
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
1197
+ .then(async result => {
1198
+ await (0, tc_token_utils_1.storeTcTokensFromIqResult)({
1199
+ result,
1200
+ fallbackJid: tcTokenJid,
1201
+ keys: authState.keys,
1202
+ getLIDForPN
1203
+ })
1204
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid])
1205
+ const currentEntry = currentData[tcTokenJid]
1206
+ const indexWrite = await (0, tc_token_utils_1.buildMergedTcTokenIndexWrite)(authState.keys, [tcTokenJid])
1207
+ await authState.keys.set({
1208
+ tctoken: {
1209
+ [tcTokenJid]: {
1210
+ token: Buffer.alloc(0),
1211
+ ...currentEntry,
1212
+ senderTimestamp: issueTimestamp
1213
+ },
1214
+ ...indexWrite
1215
+ }
1216
+ })
1217
+ })
1218
+ .catch(err => {
1219
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed')
1220
+ })
1221
+ .finally(() => {
1222
+ inFlightTcTokenIssuance.delete(tcTokenJid)
1223
+ })
1224
+ }
1225
+ // Add message to retry cache if enabled
1226
+ if (messageRetryManager && !participant) {
1227
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message)
1228
+ }
1229
+ if (isInterop && !isRetryResend) {
1230
+ await trustInteropContact(destinationJid).catch(err => {
1231
+ logger.debug({ err, jid: destinationJid }, 'failed to trust interop contact')
1232
+ })
1233
+ }
1234
+ }, meId)
1235
+ return msgId
1236
+ }
1237
+ const getTypeMessage = msg => {
1238
+ const message = Utils_1.normalizeMessageContent(msg)
1239
+ if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
1240
+ return 'poll'
1241
+ } else if (message.reactionMessage) {
1242
+ return 'reaction'
1243
+ } else if (message.eventMessage) {
1244
+ return 'event'
1245
+ } else if (getMediaType(message)) {
1246
+ return 'media'
1247
+ } else {
1248
+ return 'text'
1249
+ }
1250
+ }
1251
+
1252
+ const getMediaType = message => {
1253
+ if (message.imageMessage) {
1254
+ return 'image'
1255
+ } else if (message.stickerMessage) {
1256
+ return message.stickerMessage.isLottie
1257
+ ? '1p_sticker'
1258
+ : message.stickerMessage.isAvatar
1259
+ ? 'avatar_sticker'
1260
+ : 'sticker'
1261
+ } else if (message.videoMessage) {
1262
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
1263
+ } else if (message.audioMessage) {
1264
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
1265
+ } else if (message.ptvMessage) {
1266
+ return 'ptv'
1267
+ } else if (message.albumMessage) {
1268
+ return 'collection'
1269
+ } else if (message.contactMessage) {
1270
+ return 'vcard'
1271
+ } else if (message.documentMessage) {
1272
+ return 'document'
1273
+ } else if (message.stickerPackMessage) {
1274
+ return 'sticker_pack'
1275
+ } else if (message.contactsArrayMessage) {
1276
+ return 'contact_array'
1277
+ } else if (message.locationMessage) {
1278
+ return 'location'
1279
+ } else if (message.liveLocationMessage) {
1280
+ return 'livelocation'
1281
+ } else if (message.listMessage) {
1282
+ return 'list'
1283
+ } else if (message.listResponseMessage) {
1284
+ return 'list_response'
1285
+ } else if (message.buttonsResponseMessage) {
1286
+ return 'buttons_response'
1287
+ } else if (message.orderMessage) {
1288
+ return 'order'
1289
+ } else if (message.productMessage) {
1290
+ return 'product'
1291
+ } else if (message.interactiveResponseMessage) {
1292
+ return 'native_flow_response'
1293
+ } else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
1294
+ return 'cataloglink'
1295
+ } else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
1296
+ return 'productlink'
1297
+ } else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1298
+ return 'url'
1299
+ }
1300
+ }
1301
+ const getButtonType = message => {
1302
+ if (message.listMessage) {
1303
+ return 'list'
1304
+ } else if (message.buttonsMessage) {
1305
+ return 'buttons'
1306
+ } else if (message.interactiveMessage?.nativeFlowMessage) {
1307
+ const firstButtonName = message.interactiveMessage.nativeFlowMessage.buttons?.[0]?.name
1308
+ if (firstButtonName === 'review_and_pay') {
1309
+ return 'review_and_pay'
1310
+ } else if (firstButtonName === 'review_order') {
1311
+ return 'review_order'
1312
+ } else if (firstButtonName === 'payment_info') {
1313
+ return 'payment_info'
1314
+ } else if (firstButtonName === 'payment_status') {
1315
+ return 'payment_status'
1316
+ } else if (firstButtonName === 'payment_method') {
1317
+ return 'payment_method'
1318
+ } else if (firstButtonName === 'pix') {
1319
+ return 'pix'
1320
+ } else if (firstButtonName === 'pay') {
1321
+ return 'pay'
1322
+ }
1323
+ return 'native_flow'
1324
+ }
1325
+ }
1326
+
1327
+ const getButtonArgs = message => {
1328
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage
1329
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name
1330
+ const nativeFlowSpecials = [
1331
+ 'mpm',
1332
+ 'cta_catalog',
1333
+ 'send_location',
1334
+ 'call_permission_request',
1335
+ 'wa_payment_transaction_details',
1336
+ 'automated_greeting_message_view_catalog'
1337
+ ]
1338
+
1339
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1340
+ return {
1341
+ tag: 'biz',
1342
+ attrs: {
1343
+ native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
1344
+ }
1345
+ }
1346
+ } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1347
+ // Only works for WhatsApp Original, not WhatsApp Business
1348
+ return {
1349
+ tag: 'biz',
1350
+ attrs: {
1351
+ actual_actors: '2',
1352
+ host_storage: '2',
1353
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1354
+ },
1355
+ content: [
1356
+ {
1357
+ tag: 'interactive',
1358
+ attrs: {
1359
+ type: 'native_flow',
1360
+ v: '1'
1361
+ },
1362
+ content: [
1363
+ {
1364
+ tag: 'native_flow',
1365
+ attrs: {
1366
+ v: '2',
1367
+ name: firstButtonName
1368
+ }
1369
+ }
1370
+ ]
1371
+ },
1372
+ {
1373
+ tag: 'quality_control',
1374
+ attrs: {
1375
+ source_type: 'third_party'
1376
+ }
1377
+ }
1378
+ ]
1379
+ }
1380
+ } else if (nativeFlow || message.buttonsMessage) {
1381
+ // It works for whatsapp original and whatsapp business
1382
+ return {
1383
+ tag: 'biz',
1384
+ attrs: {
1385
+ actual_actors: '2',
1386
+ host_storage: '2',
1387
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1388
+ },
1389
+ content: [
1390
+ {
1391
+ tag: 'interactive',
1392
+ attrs: {
1393
+ type: 'native_flow',
1394
+ v: '1'
1395
+ },
1396
+ content: [
1397
+ {
1398
+ tag: 'native_flow',
1399
+ attrs: {
1400
+ v: '9',
1401
+ name: 'mixed'
1402
+ }
1403
+ }
1404
+ ]
1405
+ },
1406
+ {
1407
+ tag: 'quality_control',
1408
+ attrs: {
1409
+ source_type: 'third_party'
1410
+ }
1411
+ }
1412
+ ]
1413
+ }
1414
+ } else if (message.listMessage) {
1415
+ return {
1416
+ tag: 'biz',
1417
+ attrs: {
1418
+ actual_actors: '2',
1419
+ host_storage: '2',
1420
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1421
+ },
1422
+ content: [
1423
+ {
1424
+ tag: 'list',
1425
+ attrs: {
1426
+ v: '2',
1427
+ type: 'product_list'
1428
+ }
1429
+ },
1430
+ {
1431
+ tag: 'quality_control',
1432
+ attrs: {
1433
+ source_type: 'third_party'
1434
+ }
1435
+ }
1436
+ ]
1437
+ }
1438
+ } else {
1439
+ return {
1440
+ tag: 'biz',
1441
+ attrs: {
1442
+ actual_actors: '2',
1443
+ host_storage: '2',
1444
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1445
+ }
1446
+ }
1447
+ }
1448
+ }
1449
+ const issuePrivacyTokens = async (jids, timestamp) => {
1450
+ const t = (timestamp ?? (0, Utils_1.unixTimestampSeconds)()).toString()
1451
+ const result = await query({
1452
+ tag: 'iq',
1453
+ attrs: {
1454
+ to: WABinary_1.S_WHATSAPP_NET,
1455
+ type: 'set',
1456
+ xmlns: 'privacy'
1457
+ },
1458
+ content: [
1459
+ {
1460
+ tag: 'tokens',
1461
+ attrs: {},
1462
+ content: jids.map(jid => ({
1463
+ tag: 'token',
1464
+ attrs: {
1465
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
1466
+ t,
1467
+ type: 'trusted_contact'
1468
+ }
1469
+ }))
1470
+ }
1471
+ ]
1472
+ })
1473
+ return result
1474
+ }
1475
+ const getPrivacyTokens = issuePrivacyTokens
1476
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn)
1477
+ const badzzne2 = new interactive_handler_1.Badzz88Handler(waUploadToServer, relayMessage, config, sock)
1478
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update')
1479
+ return {
1480
+ ...sock,
1481
+ issuePrivacyTokens,
1482
+ getPrivacyTokens,
1483
+ assertSessions,
1484
+ relayMessage,
1485
+ sendReceipt,
1486
+ sendReceipts,
1487
+ readMessages,
1488
+ refreshMediaConn,
1489
+ waUploadToServer,
1490
+ fetchPrivacySettings,
1491
+ sendPeerDataOperationMessage,
1492
+ createParticipantNodes,
1493
+ getUSyncDevices,
1494
+ messageRetryManager,
1495
+ updateMemberLabel,
1496
+ updateMediaMessage: async message => {
1497
+ const content = (0, Utils_1.assertMediaContent)(message.message)
1498
+ const mediaKey = content.mediaKey
1499
+ const meId = authState.creds.me.id
1500
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId)
1501
+ let error = undefined
1502
+ await Promise.all([
1503
+ sendNode(node),
1504
+ waitForMsgMediaUpdate(async update => {
1505
+ const result = update.find(c => c.key.id === message.key.id)
1506
+ if (result) {
1507
+ if (result.error) {
1508
+ error = result.error
1509
+ } else {
1510
+ try {
1511
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id)
1512
+ if (media.result !== index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
1513
+ const resultStr = index_js_1.proto.MediaRetryNotification.ResultType[media.result]
1514
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, {
1515
+ data: media,
1516
+ statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404
1517
+ })
1518
+ }
1519
+ content.directPath = media.directPath
1520
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath)
1521
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
1522
+ } catch (err) {
1523
+ error = err
1524
+ }
1525
+ }
1526
+ return true
1527
+ }
1528
+ })
1529
+ ])
1530
+ if (error) {
1531
+ throw error
1532
+ }
1533
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }])
1534
+ return message
1535
+ },
1536
+
1537
+ sendGroupStatus: async (groupIdsOrContent = [], contentOrGroups = {}, opts = {}) => {
1538
+ const toGroupIdArray = input => {
1539
+ if (Array.isArray(input)) {
1540
+ return input
1541
+ }
1542
+ if (typeof input === 'string') {
1543
+ return [input]
1544
+ }
1545
+ return []
1546
+ }
1547
+ const normalizeGroupJid = value => {
1548
+ if (typeof value !== 'string') {
1549
+ return ''
1550
+ }
1551
+ const trimmed = value.trim()
1552
+ if (!trimmed) {
1553
+ return ''
1554
+ }
1555
+ if (/^\d{8,}$/.test(trimmed)) {
1556
+ return `${trimmed}@g.us`
1557
+ }
1558
+ return trimmed
1559
+ }
1560
+ const useNewSignature = Array.isArray(groupIdsOrContent) || typeof groupIdsOrContent === 'string'
1561
+ const groupIds = useNewSignature ? toGroupIdArray(groupIdsOrContent) : toGroupIdArray(contentOrGroups)
1562
+ const content = useNewSignature ? contentOrGroups || {} : groupIdsOrContent || {}
1563
+ const sendOpts = opts || {}
1564
+ const groupJids = groupIds.map(normalizeGroupJid).filter(jid => (0, WABinary_1.isJidGroup)(jid))
1565
+ const nonGroupJids = groupIds.filter(jid => !(0, WABinary_1.isJidGroup)(normalizeGroupJid(jid)))
1566
+ if (nonGroupJids.length) {
1567
+ logger.warn({ nonGroupJids }, 'ignoring non-group JIDs in sendGroupStatus')
1568
+ }
1569
+ if (!groupJids.length) {
1570
+ return []
1571
+ }
1572
+ const { allUsers } = await resolveStatusAudience(groupJids, false)
1573
+ if (!allUsers.length) {
1574
+ return []
1575
+ }
1576
+ const msg = await generateStatusMessage({
1577
+ ...content,
1578
+ backgroundColor: content.backgroundColor || getRandomHexColor(),
1579
+ font: normalizeStatusFont(content.font, logger)
1580
+ })
1581
+ await relayMessage(WABinary_1.STORIES_JID, msg.message, {
1582
+ messageId: msg.key.id,
1583
+ statusJidList: allUsers,
1584
+ ...(sendOpts.relay || {})
1585
+ })
1586
+ return groupJids
1587
+ },
1588
+ sendAlbumMessage: async (jid, medias, options = {}) => {
1589
+ const userJid = authState.creds.me.id
1590
+ for (const media of medias) {
1591
+ if (!media.image && !media.video) throw new TypeError(`medias[i] must have image or video property`)
1592
+ }
1593
+ if (medias.length < 2) throw new RangeError('Minimum 2 media')
1594
+ const time = options.delay || 500
1595
+ delete options.delay
1596
+ const album = await (0, Utils_1.generateWAMessageFromContent)(
1597
+ jid,
1598
+ {
1599
+ albumMessage: {
1600
+ expectedImageCount: medias.filter(media => media.image).length,
1601
+ expectedVideoCount: medias.filter(media => media.video).length,
1602
+ ...options
1603
+ }
1604
+ },
1605
+ { userJid, ...options }
1606
+ )
1607
+ await relayMessage(jid, album.message, { messageId: album.key.id })
1608
+ let mediaHandle
1609
+ let msg
1610
+ for (const i in medias) {
1611
+ const media = medias[i]
1612
+ if (media.image) {
1613
+ msg = await (0, Utils_1.generateWAMessage)(
1614
+ jid,
1615
+ {
1616
+ image: media.image,
1617
+ ...media,
1618
+ ...options
1619
+ },
1620
+ {
1621
+ userJid,
1622
+ upload: async (readStream, opts) => {
1623
+ const up = await waUploadToServer(readStream, {
1624
+ ...opts,
1625
+ newsletter: (0, WABinary_1.isJidNewsletter)(jid)
1626
+ })
1627
+ mediaHandle = up.handle
1628
+ return up
1629
+ },
1630
+ mediaAbProps: authState.creds.mediaAbProps,
1631
+ ...options
1632
+ }
1633
+ )
1634
+ } else if (media.video) {
1635
+ msg = await (0, Utils_1.generateWAMessage)(
1636
+ jid,
1637
+ {
1638
+ video: media.video,
1639
+ ...media,
1640
+ ...options
1641
+ },
1642
+ {
1643
+ userJid,
1644
+ upload: async (readStream, opts) => {
1645
+ const up = await waUploadToServer(readStream, {
1646
+ ...opts,
1647
+ newsletter: (0, WABinary_1.isJidNewsletter)(jid)
1648
+ })
1649
+ mediaHandle = up.handle
1650
+ return up
1651
+ },
1652
+ mediaAbProps: authState.creds.mediaAbProps,
1653
+ ...options
1654
+ }
1655
+ )
1656
+ }
1657
+ if (msg) {
1658
+ msg.message.messageContextInfo = {
1659
+ messageAssociation: {
1660
+ associationType: 1,
1661
+ parentMessageKey: album.key
1662
+ }
1663
+ }
1664
+ }
1665
+ await relayMessage(jid, msg.message, { messageId: msg.key.id })
1666
+ await (0, Utils_1.delay)(time)
1667
+ }
1668
+ return album
1669
+ },
1670
+
1671
+ sendStatusMention: async (content, jids = []) => {
1672
+ return await badzzne2.sendStatusWhatsApp(content, jids)
1673
+ },
1674
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1675
+ const { message, messageId } = message_composer_1.generateTableContent(title, headers, rows, quoted, options)
1676
+ await relayMessage(jid, message, { messageId })
1677
+ return { message, messageId }
1678
+ },
1679
+ sendList: async (jid, title, items, quoted, options = {}) => {
1680
+ const { message, messageId } = message_composer_1.generateListContent(title, items, quoted, options)
1681
+ await relayMessage(jid, message, { messageId })
1682
+ return { message, messageId }
1683
+ },
1684
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1685
+ const { message, messageId } = message_composer_1.generateCodeBlockContent(code, quoted, options)
1686
+ await relayMessage(jid, message, { messageId })
1687
+ return { message, messageId }
1688
+ },
1689
+ sendLatex: async (jid, quoted, options) => {
1690
+ const { message, messageId } = message_composer_1.generateLatexContent(quoted, options)
1691
+ await relayMessage(jid, message, { messageId })
1692
+ return { message, messageId }
1693
+ },
1694
+ sendLatexImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1695
+ const { message, messageId } = await message_composer_1.generateLatexImageContent(
1696
+ quoted,
1697
+ options,
1698
+ uploadFn,
1699
+ renderLatexToPng
1700
+ )
1701
+ await relayMessage(jid, message, { messageId })
1702
+ return { message, messageId }
1703
+ },
1704
+ sendLatexInlineImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1705
+ const { message, messageId } = await message_composer_1.generateLatexInlineImageContent(
1706
+ quoted,
1707
+ options,
1708
+ uploadFn,
1709
+ renderLatexToPng
1710
+ )
1711
+ await relayMessage(jid, message, { messageId })
1712
+ return { message, messageId }
1713
+ },
1714
+ captureUnifiedResponse: message_composer_1.captureUnifiedResponse,
1715
+ sendUnifiedResponse: async (jid, quoted, captured) => {
1716
+ const { message, messageId } = message_composer_1.generateUnifiedResponseContent(quoted, captured)
1717
+ await relayMessage(jid, message, { messageId })
1718
+ return { message, messageId }
1719
+ },
1720
+ sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1721
+ const { message, messageId } = message_composer_1.generateRichMessageContent(submessages, quoted, options)
1722
+ await relayMessage(jid, message, { messageId })
1723
+ return { message, messageId }
1724
+ },
1725
+ sendMessage: async (jid, content, options = {}) => {
1726
+ const userJid = authState.creds.me.id
1727
+ // ── Normalize: buttons[].nativeFlowInfo -> interactiveButtons ──────
1728
+ if (
1729
+ typeof content === 'object' &&
1730
+ Array.isArray(content.buttons) &&
1731
+ content.buttons.length > 0 &&
1732
+ content.buttons.some(b => b.nativeFlowInfo)
1733
+ ) {
1734
+ const interactiveButtons = content.buttons.map(b => {
1735
+ if (b.nativeFlowInfo) {
1736
+ return {
1737
+ name: b.nativeFlowInfo.name,
1738
+ buttonParamsJson: b.nativeFlowInfo.paramsJson || '{}'
1739
+ }
1740
+ }
1741
+ return {
1742
+ name: 'quick_reply',
1743
+ buttonParamsJson: JSON.stringify({
1744
+ display_text: b.buttonText?.displayText || b.buttonId || 'Button',
1745
+ id: b.buttonId || b.buttonText?.displayText || 'btn'
1746
+ })
1747
+ }
1748
+ })
1749
+ const { buttons, headerType, viewOnce, ...rest } = content
1750
+ content = { ...rest, interactiveButtons }
1751
+ }
1752
+ if (
1753
+ typeof content === 'object' &&
1754
+ Array.isArray(content.interactiveButtons) &&
1755
+ content.interactiveButtons.length > 0
1756
+ ) {
1757
+ const {
1758
+ text = '',
1759
+ caption = '',
1760
+ title = '',
1761
+ footer = '',
1762
+ interactiveButtons,
1763
+ hasMediaAttachment = false,
1764
+ image = null,
1765
+ video = null,
1766
+ document = null,
1767
+ mimetype = null,
1768
+ jpegThumbnail = null,
1769
+ location = null,
1770
+ product = null,
1771
+ businessOwnerJid = null,
1772
+ externalAdReply = null
1773
+ } = content
1774
+ // Normalize buttons
1775
+ const processedButtons = []
1776
+ for (let i = 0; i < interactiveButtons.length; i++) {
1777
+ const btn = interactiveButtons[i]
1778
+ if (!btn || typeof btn !== 'object') throw new Error(`interactiveButtons[${i}] must be an object`)
1779
+ if (btn.name && btn.buttonParamsJson) {
1780
+ processedButtons.push(btn)
1781
+ continue
1782
+ }
1783
+ if (btn.id || btn.text || btn.displayText) {
1784
+ processedButtons.push({
1785
+ name: 'quick_reply',
1786
+ buttonParamsJson: JSON.stringify({
1787
+ display_text: btn.text || btn.displayText || `Button ${i + 1}`,
1788
+ id: btn.id || `quick_${i + 1}`
1789
+ })
1790
+ })
1791
+ continue
1792
+ }
1793
+ if (btn.buttonId && btn.buttonText?.displayText) {
1794
+ processedButtons.push({
1795
+ name: 'quick_reply',
1796
+ buttonParamsJson: JSON.stringify({ display_text: btn.buttonText.displayText, id: btn.buttonId })
1797
+ })
1798
+ continue
1799
+ }
1800
+ throw new Error(`interactiveButtons[${i}] has invalid shape`)
1801
+ }
1802
+ let messageContent = {}
1803
+ if (image) {
1804
+ const mi = Buffer.isBuffer(image)
1805
+ ? { image }
1806
+ : { image: { url: typeof image === 'object' ? image.url : image } }
1807
+ const pm = await (0, Utils_1.prepareWAMessageMedia)(mi, { upload: waUploadToServer })
1808
+ messageContent.header = { title: title || '', hasMediaAttachment: true, imageMessage: pm.imageMessage }
1809
+ } else if (video) {
1810
+ const mi = Buffer.isBuffer(video)
1811
+ ? { video }
1812
+ : { video: { url: typeof video === 'object' ? video.url : video } }
1813
+ const pm = await (0, Utils_1.prepareWAMessageMedia)(mi, { upload: waUploadToServer })
1814
+ messageContent.header = { title: title || '', hasMediaAttachment: true, videoMessage: pm.videoMessage }
1815
+ } else if (document) {
1816
+ const mi = Buffer.isBuffer(document)
1817
+ ? { document }
1818
+ : { document: { url: typeof document === 'object' ? document.url : document } }
1819
+ if (mimetype && typeof mi.document === 'object') mi.document.mimetype = mimetype
1820
+ if (jpegThumbnail) {
1821
+ const thumb = Buffer.isBuffer(jpegThumbnail)
1822
+ ? jpegThumbnail
1823
+ : await (async () => {
1824
+ try {
1825
+ const r = await fetch(jpegThumbnail)
1826
+ return Buffer.from(await r.arrayBuffer())
1827
+ } catch {
1828
+ return undefined
1829
+ }
1830
+ })()
1831
+ if (thumb) mi.document.jpegThumbnail = thumb
1832
+ }
1833
+ const pm = await (0, Utils_1.prepareWAMessageMedia)(mi, { upload: waUploadToServer })
1834
+ messageContent.header = { title: title || '', hasMediaAttachment: true, documentMessage: pm.documentMessage }
1835
+ } else if (location && typeof location === 'object') {
1836
+ messageContent.header = {
1837
+ title: title || location.name || 'Location',
1838
+ hasMediaAttachment: false,
1839
+ locationMessage: {
1840
+ degreesLatitude: location.degreesLatitude || location.degressLatitude || 0,
1841
+ degreesLongitude: location.degreesLongitude || location.degressLongitude || 0,
1842
+ name: location.name || '',
1843
+ address: location.address || ''
1844
+ }
1845
+ }
1846
+ } else if (product && typeof product === 'object') {
1847
+ let productImageMessage = null
1848
+ if (product.productImage) {
1849
+ const mi = Buffer.isBuffer(product.productImage)
1850
+ ? { image: product.productImage }
1851
+ : {
1852
+ image: {
1853
+ url: typeof product.productImage === 'object' ? product.productImage.url : product.productImage
1854
+ }
1855
+ }
1856
+ const pm = await (0, Utils_1.prepareWAMessageMedia)(mi, { upload: waUploadToServer })
1857
+ productImageMessage = pm.imageMessage
1858
+ }
1859
+ messageContent.header = {
1860
+ title: title || product.title || 'Product',
1861
+ hasMediaAttachment: false,
1862
+ productMessage: {
1863
+ product: {
1864
+ productImage: productImageMessage,
1865
+ productId: product.productId || '',
1866
+ title: product.title || '',
1867
+ description: product.description || '',
1868
+ currencyCode: product.currencyCode || 'USD',
1869
+ priceAmount1000: parseInt(product.priceAmount1000, 10) || 0,
1870
+ retailerId: product.retailerId || '',
1871
+ url: product.url || '',
1872
+ productImageCount: product.productImageCount || 1
1873
+ },
1874
+ businessOwnerJid: businessOwnerJid || product.businessOwnerJid || userJid
1875
+ }
1876
+ }
1877
+ } else if (title) {
1878
+ messageContent.header = { title, hasMediaAttachment: false }
1879
+ }
1880
+ const hasMedia = !!(image || video || document || location || product)
1881
+ const bodyText = hasMedia ? caption : text || caption
1882
+ if (bodyText) messageContent.body = { text: bodyText }
1883
+ if (footer) messageContent.footer = { text: footer }
1884
+ messageContent.nativeFlowMessage = { buttons: processedButtons }
1885
+ if (externalAdReply && typeof externalAdReply === 'object') {
1886
+ messageContent.contextInfo = {
1887
+ externalAdReply: {
1888
+ title: externalAdReply.title || '',
1889
+ body: externalAdReply.body || '',
1890
+ mediaType: externalAdReply.mediaType || 1,
1891
+ sourceUrl: externalAdReply.sourceUrl || externalAdReply.url || '',
1892
+ thumbnailUrl: externalAdReply.thumbnailUrl || externalAdReply.thumbnail || '',
1893
+ renderLargerThumbnail: externalAdReply.renderLargerThumbnail || false,
1894
+ showAdAttribution: externalAdReply.showAdAttribution !== false,
1895
+ containsAutoReply: externalAdReply.containsAutoReply || false,
1896
+ ...(externalAdReply.mediaUrl && { mediaUrl: externalAdReply.mediaUrl }),
1897
+ ...(Buffer.isBuffer(externalAdReply.thumbnail) && { thumbnail: externalAdReply.thumbnail }),
1898
+ ...(externalAdReply.jpegThumbnail && { jpegThumbnail: externalAdReply.jpegThumbnail })
1899
+ },
1900
+ ...(options.mentionedJid && { mentionedJid: options.mentionedJid })
1901
+ }
1902
+ } else if (options.mentionedJid) {
1903
+ messageContent.contextInfo = { mentionedJid: options.mentionedJid }
1904
+ }
1905
+ const payload = index_js_1.proto.Message.InteractiveMessage.create(messageContent)
1906
+ const msg = (0, Utils_1.generateWAMessageFromContent)(
1907
+ jid,
1908
+ { viewOnceMessage: { message: { interactiveMessage: payload } } },
1909
+ { userJid, quoted: options?.quoted || null }
1910
+ )
1911
+ const additionalNodes = [
1912
+ {
1913
+ tag: 'biz',
1914
+ attrs: {},
1915
+ content: [
1916
+ {
1917
+ tag: 'interactive',
1918
+ attrs: { type: 'native_flow', v: '1' },
1919
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
1920
+ }
1921
+ ]
1922
+ }
1923
+ ]
1924
+ await relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes })
1925
+ return msg
1926
+ }
1927
+ if (
1928
+ typeof content === 'object' &&
1929
+ 'disappearingMessagesInChat' in content &&
1930
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1931
+ (0, WABinary_1.isJidGroup)(jid)
1932
+ ) {
1933
+ const { disappearingMessagesInChat } = content
1934
+ const value =
1935
+ typeof disappearingMessagesInChat === 'boolean'
1936
+ ? disappearingMessagesInChat
1937
+ ? WA_DEFAULT_EPHEMERAL
1938
+ : 0
1939
+ : disappearingMessagesInChat
1940
+ await groupToggleEphemeral(jid, value)
1941
+ } else if (badzzne2.detectType(content)) {
1942
+ const { quoted } = options
1943
+ const messageType = badzzne2.detectType(content)
1944
+ switch (messageType) {
1945
+ case 'PAYMENT': {
1946
+ const paymentContent = await badzzne2.handlePayment(content, quoted)
1947
+ return await relayMessage(jid, paymentContent, {
1948
+ messageId: (0, Utils_1.generateMessageIDV2)(userJid)
1949
+ })
1950
+ }
1951
+ case 'PRODUCT': {
1952
+ const productContent = await badzzne2.handleProduct(content, jid, quoted)
1953
+ const productMsg = await (0, Utils_1.generateWAMessageFromContent)(jid, productContent, { quoted, userJid })
1954
+ return await relayMessage(jid, productMsg.message, {
1955
+ messageId: productMsg.key.id
1956
+ })
1957
+ }
1958
+ case 'INTERACTIVE': {
1959
+ const interactiveContent = await badzzne2.handleInteractive(content, jid, quoted)
1960
+ const interactiveMsg = await (0, Utils_1.generateWAMessageFromContent)(jid, interactiveContent, {
1961
+ quoted,
1962
+ userJid
1963
+ })
1964
+ return await relayMessage(jid, interactiveMsg.message, {
1965
+ messageId: interactiveMsg.key.id
1966
+ })
1967
+ }
1968
+ case 'INTERACTIVE_BUTTONS': {
1969
+ const ibContent = await badzzne2.handleInteractiveButtons(content, jid, quoted)
1970
+ const ibMsg = await (0, Utils_1.generateWAMessageFromContent)(jid, ibContent, { quoted, userJid })
1971
+ return await relayMessage(jid, ibMsg.message, {
1972
+ messageId: ibMsg.key.id
1973
+ })
1974
+ }
1975
+ case 'ALBUM':
1976
+ return await badzzne2.handleAlbum(content, jid, quoted)
1977
+ case 'EVENT':
1978
+ return await badzzne2.handleEvent(content, jid, quoted)
1979
+ case 'POLL_RESULT':
1980
+ return await badzzne2.handlePollResult(content, jid, quoted)
1981
+ case 'GROUP_STORY':
1982
+ return await badzzne2.handleGroupStory(content, jid, quoted)
1983
+ }
1984
+ } else {
1985
+ let mediaHandle
1986
+ const { ai, ...optionsWithoutAI } = options
1987
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
1988
+ logger,
1989
+ userJid,
1990
+ getUrlInfo: text =>
1991
+ (0, link_preview_1.getUrlInfo)(text, {
1992
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1993
+ fetchOpts: {
1994
+ timeout: 3000,
1995
+ ...(httpRequestOptions || {})
1996
+ },
1997
+ logger,
1998
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1999
+ }),
2000
+ getProfilePicUrl: sock.profilePictureUrl,
2001
+ getCallLink: sock.createCallLink,
2002
+ newsletter: (0, WABinary_1.isJidNewsletter)(jid),
2003
+ upload: async (encFilePath, opts) => {
2004
+ const up = await waUploadToServer(encFilePath, {
2005
+ ...opts,
2006
+ newsletter: (0, WABinary_1.isJidNewsletter)(jid)
2007
+ })
2008
+ mediaHandle = up.handle
2009
+ return up
2010
+ },
2011
+ mediaCache: config.mediaCache,
2012
+ options: config.options,
2013
+ messageId: (0, Utils_1.generateMessageIDV2)(sock.user?.id),
2014
+ // Pass persisted media AB props so feature-flagged upload/download paths work.
2015
+ mediaAbProps: authState.creds.mediaAbProps,
2016
+ ...optionsWithoutAI
2017
+ })
2018
+ if (!mediaHandle) {
2019
+ const msgContent = fullMsg.message
2020
+ const msgTypes = ['audioMessage', 'imageMessage', 'videoMessage', 'documentMessage', 'stickerMessage']
2021
+ for (const t of msgTypes) {
2022
+ if (msgContent?.[t]?._uploadHandle) {
2023
+ mediaHandle = msgContent[t]._uploadHandle
2024
+
2025
+ delete msgContent[t]._uploadHandle
2026
+ break
2027
+ }
2028
+ }
2029
+ }
2030
+ const isEventMsg = 'event' in content && !!content.event
2031
+ const isDeleteMsg = 'delete' in content && !!content.delete
2032
+ const isEditMsg = 'edit' in content && !!content.edit
2033
+ const isPinMsg = 'pin' in content && !!content.pin
2034
+ const isPollMessage = 'poll' in content && !!content.poll
2035
+ const additionalAttributes = {}
2036
+ const additionalNodes = []
2037
+ if (isDeleteMsg) {
2038
+ if ((0, WABinary_1.isJidGroup)(content.delete?.remoteJid) && !content.delete?.fromMe) {
2039
+ additionalAttributes.edit = '8'
2040
+ } else {
2041
+ additionalAttributes.edit = '7'
2042
+ }
2043
+ if (content.delete?.server_id) {
2044
+ additionalAttributes.server_id = String(content.delete.server_id)
2045
+ }
2046
+ } else if (isEditMsg) {
2047
+ additionalAttributes.edit = '1'
2048
+ } else if (isPinMsg) {
2049
+ additionalAttributes.edit = '2'
2050
+ } else if (isPollMessage) {
2051
+ additionalNodes.push({
2052
+ tag: 'meta',
2053
+ attrs: {
2054
+ polltype: 'creation'
2055
+ }
2056
+ })
2057
+ } else if (isEventMsg) {
2058
+ additionalNodes.push({
2059
+ tag: 'meta',
2060
+ attrs: {
2061
+ event_type: 'creation'
2062
+ }
2063
+ })
2064
+ }
2065
+ const buttonType = getButtonType(fullMsg.message)
2066
+ if (content?.audio && options?.contextInfo) {
2067
+ const msgContent = fullMsg.message
2068
+ if (msgContent?.audioMessage) {
2069
+ msgContent.audioMessage.contextInfo = options.contextInfo
2070
+ }
2071
+ }
2072
+ if (buttonType) {
2073
+ const btnNode = getButtonArgs(fullMsg.message)
2074
+ if (btnNode) additionalNodes.push(btnNode)
2075
+ }
2076
+ if (mediaHandle) {
2077
+ additionalAttributes['media_id'] = mediaHandle
2078
+ }
2079
+ await relayMessage(jid, fullMsg.message, {
2080
+ messageId: fullMsg.key.id,
2081
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2082
+ additionalAttributes,
2083
+ statusJidList: options.statusJidList,
2084
+ statusPrivacy: options.statusPrivacy,
2085
+ additionalNodes,
2086
+ AI: ai || false
2087
+ })
2088
+ if (config.emitOwnEvents) {
2089
+ process.nextTick(async () => {
2090
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'))
2091
+ })
2092
+ }
2093
+ return fullMsg
2094
+ }
2095
+ },
2096
+
2097
+ sendMetaAI: async (jid1, text, opts = {}) => {
2098
+ const crypto = require('crypto')
2099
+ const { proto } = require('../../WAProto/index.js')
2100
+ const META_AI_BOT_JID = '867051314767696@bot'
2101
+ const yourJid = jid1 || ''
2102
+ const jid = opts.jid || META_AI_BOT_JID
2103
+ const threadId = opts.threadId || Utils_1.generateMessageIDV2(yourJid)
2104
+ const now = Date.now()
2105
+ const senderTimestamp = opts.senderTimestamp || String(Math.floor(now / 1000))
2106
+ const messageSecret = opts.messageSecret || crypto.randomBytes(32)
2107
+ const senderKeyHash = opts.senderKeyHash || crypto.randomBytes(8).toString('base64')
2108
+ const message = {
2109
+ extendedTextMessage: proto.Message.ExtendedTextMessage.fromObject({
2110
+ text,
2111
+ previewType: 'NONE',
2112
+ contextInfo: proto.ContextInfo.fromObject({
2113
+ botMessageSharingInfo: {
2114
+ botEntryPointOrigin: 'FAVICON',
2115
+ forwardScore: 0
2116
+ }
2117
+ }),
2118
+ inviteLinkGroupTypeV2: 'DEFAULT'
2119
+ }),
2120
+ messageContextInfo: proto.MessageContextInfo.fromObject({
2121
+ deviceListMetadata: {
2122
+ senderKeyHash,
2123
+ senderTimestamp
2124
+ },
2125
+ deviceListMetadataVersion: 2,
2126
+ messageSecret,
2127
+ botMetadata: {
2128
+ botModeSelectionMetadata: {
2129
+ overrideMode: [0]
2130
+ },
2131
+ botThreadInfo: {
2132
+ serverInfo: { title: text.substring(0, 50) },
2133
+ clientInfo: { type: 'DEFAULT' }
2134
+ },
2135
+ botRenderingConfigMetadata: {
2136
+ bloksVersioningId: '1eb86e6f4117d052e6bab62fe758a2e2af43747b85c5c1a886c8262bac462ea4',
2137
+ pixelDensity: 2.625
2138
+ }
2139
+ },
2140
+ threadId: [
2141
+ {
2142
+ threadType: 'AI_THREAD',
2143
+ threadKey: {
2144
+ remoteJid: '0002@s.whatsapp.net',
2145
+ fromMe: true,
2146
+ id: threadId
2147
+ }
2148
+ }
2149
+ ]
2150
+ })
2151
+ }
2152
+ const msgId = (0, Utils_1.generateMessageIDV2)(yourJid)
2153
+ const messageOptions = {
2154
+ messageId: msgId,
2155
+ quoted: opts.quoted,
2156
+ links: opts.links
2157
+ }
2158
+ await relayMessage(jid, message, messageOptions)
2159
+ return msgId
2160
+ }
2161
+ }
2162
+ }
2163
+ exports.makeMessagesSocket = makeMessagesSocket