sanka-baileyss 2.3.2 → 2.3.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 (158) hide show
  1. package/WAProto/BotMetadata/BotMetadata.d.ts +594 -1
  2. package/WAProto/BotMetadata/BotMetadata.js +1910 -148
  3. package/WAProto/BotMetadata/BotMetadata.proto +36 -0
  4. package/WAProto/E2E/E2E.d.ts +570 -6
  5. package/WAProto/E2E/E2E.js +1591 -26
  6. package/WAProto/E2E/E2E.proto +10 -1
  7. package/WAProto/HistorySync/HistorySync.d.ts +806 -6
  8. package/WAProto/HistorySync/HistorySync.js +2193 -29
  9. package/WAProto/HistorySync/HistorySync.proto +2 -1
  10. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +570 -6
  11. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +1591 -26
  12. package/WAProto/StatusAttributions/StatusAttributions.d.ts +2 -1
  13. package/WAProto/StatusAttributions/StatusAttributions.js +7 -0
  14. package/WAProto/StatusAttributions/StatusAttributions.proto +1 -0
  15. package/WAProto/SyncAction/SyncAction.d.ts +230 -0
  16. package/WAProto/SyncAction/SyncAction.js +578 -2
  17. package/WAProto/SyncAction/SyncAction.proto +13 -1
  18. package/WAProto/Web/Web.d.ts +570 -6
  19. package/WAProto/Web/Web.js +1591 -26
  20. package/lib/Defaults/baileys-version.json +2 -2
  21. package/lib/Defaults/index.d.ts +42 -25
  22. package/lib/Defaults/index.js +6 -2
  23. package/lib/Signal/libsignal.d.ts +1 -0
  24. package/lib/Socket/Client/index.js +13 -9
  25. package/lib/Socket/Client/types.d.ts +11 -10
  26. package/lib/Socket/Client/types.js +11 -7
  27. package/lib/Socket/Client/websocket.d.ts +9 -8
  28. package/lib/Socket/Client/websocket.js +52 -47
  29. package/lib/Socket/business.d.ts +185 -182
  30. package/lib/Socket/business.js +258 -249
  31. package/lib/Socket/chats.d.ts +90 -87
  32. package/lib/Socket/chats.js +1095 -888
  33. package/lib/Socket/community.d.ts +131 -0
  34. package/lib/Socket/community.js +369 -0
  35. package/lib/Socket/groups.d.ts +50 -41
  36. package/lib/Socket/groups.js +10 -3
  37. package/lib/Socket/index.d.ts +5 -1
  38. package/lib/Socket/index.js +19 -5
  39. package/lib/Socket/messages-recv.d.ts +6 -2
  40. package/lib/Socket/messages-recv.js +31 -8
  41. package/lib/Socket/messages-send.d.ts +5 -1
  42. package/lib/Socket/messages-send.js +1293 -1351
  43. package/lib/Socket/newsletter.d.ts +142 -135
  44. package/lib/Socket/newsletter.js +274 -230
  45. package/lib/Socket/socket.d.ts +37 -35
  46. package/lib/Socket/usync.d.ts +31 -30
  47. package/lib/Socket/usync.js +74 -62
  48. package/lib/Types/Auth.d.ts +89 -72
  49. package/lib/Types/Auth.js +1 -0
  50. package/lib/Types/Call.d.ts +11 -10
  51. package/lib/Types/Call.js +1 -0
  52. package/lib/Types/Chat.d.ts +85 -62
  53. package/lib/Types/Chat.js +4 -1
  54. package/lib/Types/Contact.js +1 -0
  55. package/lib/Types/Events.d.ts +209 -191
  56. package/lib/Types/Events.js +1 -0
  57. package/lib/Types/GroupMetadata.d.ts +12 -27
  58. package/lib/Types/GroupMetadata.js +1 -0
  59. package/lib/Types/Label.d.ts +41 -39
  60. package/lib/Types/Label.js +24 -21
  61. package/lib/Types/LabelAssociation.d.ts +18 -12
  62. package/lib/Types/LabelAssociation.js +6 -3
  63. package/lib/Types/Message.d.ts +3 -2
  64. package/lib/Types/Message.js +7 -3
  65. package/lib/Types/MexUpdates.d.ts +9 -0
  66. package/lib/Types/MexUpdates.js +18 -0
  67. package/lib/Types/Newsletter.d.ts +84 -67
  68. package/lib/Types/Newsletter.js +30 -23
  69. package/lib/Types/Product.d.ts +70 -56
  70. package/lib/Types/Product.js +1 -0
  71. package/lib/Types/Signal.d.ts +46 -35
  72. package/lib/Types/Signal.js +1 -0
  73. package/lib/Types/Socket.d.ts +105 -101
  74. package/lib/Types/Socket.js +1 -0
  75. package/lib/Types/State.d.ts +37 -23
  76. package/lib/Types/State.js +13 -1
  77. package/lib/Types/USync.d.ts +21 -20
  78. package/lib/Types/USync.js +1 -0
  79. package/lib/Types/index.d.ts +51 -42
  80. package/lib/Types/index.js +25 -19
  81. package/lib/Utils/auth-utils.d.ts +14 -11
  82. package/lib/Utils/auth-utils.js +189 -182
  83. package/lib/Utils/baileys-event-stream.d.ts +12 -10
  84. package/lib/Utils/baileys-event-stream.js +52 -46
  85. package/lib/Utils/business.d.ts +15 -8
  86. package/lib/Utils/business.js +229 -217
  87. package/lib/Utils/chat-utils.d.ts +22 -12
  88. package/lib/Utils/chat-utils.js +57 -27
  89. package/lib/Utils/crypto.d.ts +31 -15
  90. package/lib/Utils/crypto.js +136 -107
  91. package/lib/Utils/decode-wa-message.d.ts +34 -245
  92. package/lib/Utils/decode-wa-message.js +205 -217
  93. package/lib/Utils/event-buffer.d.ts +30 -26
  94. package/lib/Utils/event-buffer.js +519 -515
  95. package/lib/Utils/history.d.ts +2 -8
  96. package/lib/Utils/index.js +13 -9
  97. package/lib/Utils/link-preview.d.ts +16 -14
  98. package/lib/Utils/link-preview.js +100 -92
  99. package/lib/Utils/logger.d.ts +9 -7
  100. package/lib/Utils/logger.js +1 -1
  101. package/lib/Utils/lt-hash.d.ts +10 -8
  102. package/lib/Utils/lt-hash.js +49 -44
  103. package/lib/Utils/make-mutex.d.ts +4 -2
  104. package/lib/Utils/make-mutex.js +43 -39
  105. package/lib/Utils/messages-media.d.ts +75 -50
  106. package/lib/Utils/messages.d.ts +60 -35
  107. package/lib/Utils/messages.js +87 -8
  108. package/lib/Utils/noise-handler.d.ts +13 -12
  109. package/lib/Utils/noise-handler.js +143 -138
  110. package/lib/Utils/process-message.d.ts +32 -24
  111. package/lib/Utils/process-message.js +387 -367
  112. package/lib/Utils/signal.d.ts +24 -15
  113. package/lib/Utils/signal.js +143 -131
  114. package/lib/Utils/use-mongo-file-auth-state.d.ts +3 -2
  115. package/lib/Utils/use-mongo-file-auth-state.js +72 -63
  116. package/lib/Utils/use-multi-file-auth-state.d.ts +9 -8
  117. package/lib/Utils/use-multi-file-auth-state.js +110 -102
  118. package/lib/Utils/use-single-file-auth-state.d.ts +8 -7
  119. package/lib/Utils/use-single-file-auth-state.js +66 -61
  120. package/lib/Utils/validate-connection.d.ts +5 -2
  121. package/lib/Utils/validate-connection.js +7 -6
  122. package/lib/WABinary/constants.d.ts +24 -21
  123. package/lib/WABinary/constants.js +1302 -31
  124. package/lib/WABinary/decode.d.ts +4 -1
  125. package/lib/WABinary/decode.js +267 -234
  126. package/lib/WABinary/encode.d.ts +1 -0
  127. package/lib/WABinary/encode.js +248 -226
  128. package/lib/WABinary/generic-utils.d.ts +13 -1
  129. package/lib/WABinary/generic-utils.js +113 -96
  130. package/lib/WABinary/index.js +13 -9
  131. package/lib/WABinary/jid-utils.d.ts +23 -4
  132. package/lib/WABinary/jid-utils.js +58 -39
  133. package/lib/WABinary/types.d.ts +15 -11
  134. package/lib/WABinary/types.js +1 -0
  135. package/lib/WAM/BinaryInfo.d.ts +14 -14
  136. package/lib/WAM/BinaryInfo.js +11 -8
  137. package/lib/WAM/constants.d.ts +34 -26
  138. package/lib/WAM/constants.js +15358 -15349
  139. package/lib/WAM/encode.d.ts +1 -0
  140. package/lib/WAM/encode.js +153 -144
  141. package/lib/WAM/index.js +13 -9
  142. package/lib/index.js +11 -11
  143. package/package.json +1 -2
  144. package/WASignalGroup/GroupProtocol.js +0 -1771
  145. package/WASignalGroup/ciphertext_message.js +0 -10
  146. package/WASignalGroup/group_cipher.js +0 -103
  147. package/WASignalGroup/group_session_builder.js +0 -39
  148. package/WASignalGroup/index.js +0 -5
  149. package/WASignalGroup/keyhelper.js +0 -17
  150. package/WASignalGroup/protobufs.js +0 -2
  151. package/WASignalGroup/queue_job.js +0 -64
  152. package/WASignalGroup/sender_chain_key.js +0 -38
  153. package/WASignalGroup/sender_key_distribution_message.js +0 -68
  154. package/WASignalGroup/sender_key_message.js +0 -79
  155. package/WASignalGroup/sender_key_name.js +0 -59
  156. package/WASignalGroup/sender_key_record.js +0 -47
  157. package/WASignalGroup/sender_key_state.js +0 -110
  158. package/WASignalGroup/sender_message_key.js +0 -30
@@ -1,1352 +1,1294 @@
1
- "use strict"
2
-
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod }
5
- }
6
-
7
- Object.defineProperty(exports, "__esModule", { value: true })
8
-
9
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
10
- const boom_1 = require("@hapi/boom")
11
- const crypto_1 = require("crypto")
12
- const WAProto_1 = require("../../WAProto")
13
- const Defaults_1 = require("../Defaults")
14
- const Utils_1 = require("../Utils")
15
- const Types_1 = require("../Types")
16
- const WABinary_1 = require("../WABinary")
17
- const WAUSync_1 = require("../WAUSync")
18
- const newsletter_1 = require("./newsletter")
19
- const link_preview_1 = require("../Utils/link-preview")
20
-
21
- const makeMessagesSocket = (config) => {
22
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config
23
- const suki = newsletter_1.makeNewsletterSocket(config)
24
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupQuery, groupMetadata, groupToggleEphemeral, newsletterWMexQuery, executeUSyncQuery } = suki
25
-
26
- const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
27
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
28
- useClones: false
29
- })
30
-
31
- let mediaConn
32
-
33
- const refreshMediaConn = async (forceGet = false) => {
34
- const media = await mediaConn
35
-
36
- if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
37
- mediaConn = (async () => {
38
-
39
- const result = await query({
40
- tag: 'iq',
41
- attrs: {
42
- type: 'set',
43
- xmlns: 'w:m',
44
- to: WABinary_1.S_WHATSAPP_NET,
45
- },
46
- content: [{ tag: 'media_conn', attrs: {} }]
47
- })
48
-
49
- const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn')
50
-
51
- const node = {
52
- hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
53
- hostname: attrs.hostname,
54
- maxContentLengthBytes: +attrs.maxContentLengthBytes,
55
- })),
56
- auth: mediaConnNode.attrs.auth,
57
- ttl: +mediaConnNode.attrs.ttl,
58
- fetchDate: new Date()
59
- }
60
-
61
- logger.debug('fetched media conn')
62
-
63
- return node
64
- })()
65
- }
66
-
67
- return mediaConn
68
- }
69
-
70
- /**
71
- * generic send receipt function
72
- * used for receipts of phone call, read, delivery etc.
73
- * */
74
- const sendReceipt = async (jid, participant, messageIds, type) => {
75
- const node = {
76
- tag: 'receipt',
77
- attrs: {
78
- id: messageIds[0],
79
- },
80
- }
81
-
82
- const isReadReceipt = type === 'read' || type === 'read-self'
83
-
84
- if (isReadReceipt) {
85
- node.attrs.t = Utils_1.unixTimestampSeconds().toString()
86
- }
87
-
88
- if (type === 'sender' && WABinary_1.isJidUser(jid)) {
89
- node.attrs.recipient = jid
90
- node.attrs.to = participant
91
- }
92
-
93
- else {
94
- node.attrs.to = jid
95
- if (participant) {
96
- node.attrs.participant = participant
97
- }
98
- }
99
-
100
- if (type) {
101
- node.attrs.type = WABinary_1.isJidNewsletter(jid) ? 'read-self' : type
102
- }
103
-
104
- const remainingMessageIds = messageIds.slice(1)
105
-
106
- if (remainingMessageIds.length) {
107
- node.content = [
108
- {
109
- tag: 'list',
110
- attrs: {},
111
- content: remainingMessageIds.map(id => ({
112
- tag: 'item',
113
- attrs: { id }
114
- }))
115
- }
116
- ]
117
- }
118
-
119
- logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages')
120
-
121
- await sendNode(node)
122
- }
123
-
124
- /** Correctly bulk send receipts to multiple chats, participants */
125
- const sendReceipts = async (keys, type) => {
126
- const recps = Utils_1.aggregateMessageKeysNotFromMe(keys)
127
-
128
- for (const { jid, participant, messageIds } of recps) {
129
- await sendReceipt(jid, participant, messageIds, type)
130
- }
131
- }
132
-
133
- /** Bulk read messages. Keys can be from different chats & participants */
134
- const readMessages = async (keys) => {
135
- const privacySettings = await fetchPrivacySettings()
136
-
137
- // based on privacy settings, we have to change the read type
138
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
139
-
140
- await sendReceipts(keys, readType)
141
- }
142
-
143
- /** Fetch image for groups, user, and newsletter **/
144
- const profilePictureUrl = async (jid) => {
145
- if (WABinary_1.isJidNewsletter(jid)) {
146
-
147
- let node = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
148
- input: {
149
- key: jid,
150
- type: 'JID',
151
- view_role: 'GUEST'
152
- },
153
- fetch_viewer_metadata: true,
154
- fetch_full_image: true,
155
- fetch_creation_time: true
156
- })
157
-
158
- let result = WABinary_1.getBinaryNodeChild(node, 'result')?.content?.toString()
159
-
160
- let metadata = JSON.parse(result).data[Types_1.XWAPaths.NEWSLETTER]
161
-
162
- return Utils_1.getUrlFromDirectPath(metadata.thread_metadata.picture?.direct_path || '')
163
-
164
- }
165
-
166
- else {
167
- const result = await query({
168
- tag: 'iq',
169
- attrs: {
170
- target: WABinary_1.jidNormalizedUser(jid),
171
- to: WABinary_1.S_WHATSAPP_NET,
172
- type: 'get',
173
- xmlns: 'w:profile:picture'
174
- },
175
- content: [{
176
- tag: 'picture',
177
- attrs: {
178
- type: 'image',
179
- query: 'url'
180
- }
181
- }]
182
- })
183
-
184
- const child = WABinary_1.getBinaryNodeChild(result, 'picture')
185
-
186
- return child?.attrs?.url || null
187
- }
188
- }
189
-
190
- /** Fetch all the devices we've to send a message to */
191
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
192
- const deviceResults = []
193
-
194
- if (!useCache) {
195
- logger.debug('not using cache for devices')
196
- }
197
-
198
- const toFetch = []
199
-
200
- jids = Array.from(new Set(jids))
201
-
202
- for (let jid of jids) {
203
- const user = WABinary_1.jidDecode(jid)?.user
204
-
205
- jid = WABinary_1.jidNormalizedUser(jid)
206
-
207
- if (useCache) {
208
- const devices = userDevicesCache.get(user)
209
-
210
- if (devices) {
211
- deviceResults.push(...devices)
212
- logger.trace({ user }, 'using cache for devices')
213
- }
214
-
215
- else {
216
- toFetch.push(jid)
217
- }
218
- }
219
-
220
- else {
221
- toFetch.push(jid)
222
- }
223
- }
224
-
225
- if (!toFetch.length) {
226
- return deviceResults
227
- }
228
-
229
- const query = new WAUSync_1.USyncQuery()
230
- .withContext('message')
231
- .withDeviceProtocol()
232
-
233
- for (const jid of toFetch) {
234
- query.withUser(new WAUSync_1.USyncUser().withId(jid))
235
- }
236
-
237
- const result = await executeUSyncQuery(query)
238
-
239
- if (result) {
240
- const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
241
- const deviceMap = {}
242
-
243
- for (const item of extracted) {
244
- deviceMap[item.user] = deviceMap[item.user] || []
245
- deviceMap[item.user].push(item)
246
- deviceResults.push(item)
247
- }
248
-
249
- for (const key in deviceMap) {
250
- userDevicesCache.set(key, deviceMap[key])
251
- }
252
- }
253
-
254
- return deviceResults
255
- }
256
-
257
- /** Assert Sessions */
258
- const assertSessions = async (jids, force) => {
259
- let didFetchNewSession = false
260
- let jidsRequiringFetch = []
261
-
262
- if (force) {
263
- jidsRequiringFetch = jids
264
- }
265
-
266
- else {
267
- const addrs = jids.map(jid => (signalRepository.jidToSignalProtocolAddress(jid)))
268
-
269
- const sessions = await authState.keys.get('session', addrs)
270
-
271
- for (const jid of jids) {
272
- const signalId = signalRepository
273
- .jidToSignalProtocolAddress(jid)
274
-
275
- if (!sessions[signalId]) {
276
- jidsRequiringFetch.push(jid)
277
- }
278
- }
279
- }
280
-
281
- if (jidsRequiringFetch.length) {
282
- logger.debug({ jidsRequiringFetch }, 'fetching sessions')
283
-
284
- const result = await query({
285
- tag: 'iq',
286
- attrs: {
287
- xmlns: 'encrypt',
288
- type: 'get',
289
- to: WABinary_1.S_WHATSAPP_NET,
290
- },
291
- content: [
292
- {
293
- tag: 'key',
294
- attrs: {},
295
- content: jidsRequiringFetch.map(jid => ({
296
- tag: 'user',
297
- attrs: { jid },
298
- }))
299
- }
300
- ]
301
- })
302
-
303
- await Utils_1.parseAndInjectE2ESessions(result, signalRepository)
304
-
305
- didFetchNewSession = true
306
- }
307
-
308
- return didFetchNewSession
309
- }
310
-
311
- /** Send Peer Operation */
312
- const sendPeerDataOperationMessage = async (pdoMessage) => {
313
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
314
- if (!authState.creds.me?.id) {
315
- throw new boom_1.Boom('Not authenticated')
316
- }
317
-
318
- const protocolMessage = {
319
- protocolMessage: {
320
- peerDataOperationRequestMessage: pdoMessage,
321
- type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
322
- }
323
- }
324
-
325
- const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id)
326
-
327
- const msgId = await relayMessage(meJid, protocolMessage, {
328
- additionalAttributes: {
329
- category: 'peer',
330
- // eslint-disable-next-line camelcase
331
- push_priority: 'high_force',
332
- },
333
- })
334
-
335
- return msgId
336
- }
337
-
338
- const createParticipantNodes = async (jids, message, extraAttrs) => {
339
- const patched = await patchMessageBeforeSending(message, jids)
340
- const bytes = Utils_1.encodeWAMessage(patched)
341
-
342
- let shouldIncludeDeviceIdentity = false
343
-
344
- const nodes = await Promise.all(jids.map(async (jid) => {
345
- const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
346
-
347
- if (type === 'pkmsg') {
348
- shouldIncludeDeviceIdentity = true
349
- }
350
-
351
- const node = {
352
- tag: 'to',
353
- attrs: { jid },
354
- content: [{
355
- tag: 'enc',
356
- attrs: {
357
- v: '2',
358
- type,
359
- ...extraAttrs || {}
360
- },
361
- content: ciphertext
362
- }]
363
- }
364
-
365
- return node
366
- }))
367
-
368
- return {
369
- nodes,
370
- shouldIncludeDeviceIdentity
371
- }
372
- }
373
-
374
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, additionalNodes, AI = true }) => {
375
- const meId = authState.creds.me.id
376
-
377
- let didPushAdditional = false
378
- let shouldIncludeDeviceIdentity = false
379
-
380
- const { user, server } = WABinary_1.jidDecode(jid)
381
-
382
- const statusJid = 'status@broadcast'
383
- const isGroup = server === 'g.us'
384
- const isPrivate = server === 's.whatsapp.net'
385
- const isNewsletter = server == 'newsletter'
386
- const isStatus = jid === statusJid
387
- const isLid = server === 'lid'
388
-
389
- msgId = msgId || Utils_1.generateMessageID(authState.creds.me.id)
390
- useUserDevicesCache = useUserDevicesCache !== false
391
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
392
-
393
- const participants = []
394
- const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid
395
- const binaryNodeContent = []
396
- const devices = []
397
-
398
- const meMsg = {
399
- deviceSentMessage: {
400
- destinationJid,
401
- message
402
- },
403
- messageContextInfo: message.messageContextInfo || {}
404
- }
405
-
406
- const extraAttrs = {}
407
-
408
- const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
409
-
410
- const messages = Utils_1.normalizeMessageContent(message)
411
-
412
- const buttonType = getButtonType(messages)
413
- const pollMessage = messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
414
-
415
-
416
- if (participant) {
417
- // when the retry request is not for a group
418
- // only send to the specific device that asked for a retry
419
- // otherwise the message is sent out to every device that should be a recipient
420
- if (!isGroup && !isStatus) {
421
- additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' }
422
- }
423
-
424
- const { user, device } = WABinary_1.jidDecode(participant.jid)
425
-
426
- devices.push({ user, device })
427
- }
428
-
429
- await authState.keys.transaction(async () => {
430
- const mediaType = getMediaType(message)
431
-
432
- if (mediaType) {
433
- extraAttrs['mediatype'] = mediaType
434
- }
435
-
436
- if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
437
- extraAttrs['decrypt-fail'] = 'hide'
438
- }
439
-
440
- if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
441
- extraAttrs['native_flow_name'] = messages.interactiveResponseMessage.nativeFlowResponseMessage?.name || 'menu_options'
442
- }
443
-
444
- if (isGroup || isStatus) {
445
- const [groupData, senderKeyMap] = await Promise.all([
446
- (async () => {
447
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
448
-
449
- if (groupData && Array.isArray(groupData?.participants)) {
450
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
451
- }
452
-
453
- else if (!isStatus) {
454
- groupData = await groupMetadata(jid)
455
- }
456
-
457
- return groupData
458
- })(),
459
-
460
- (async () => {
461
- if (!participant && !isStatus) {
462
- const result = await authState.keys.get('sender-key-memory', [jid])
463
- return result[jid] || {}
464
- }
465
-
466
- return {}
467
-
468
- })()
469
- ])
470
-
471
- if (!participant) {
472
- const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
473
-
474
- if (isStatus && statusJidList) {
475
- participantsList.push(...statusJidList)
476
- }
477
-
478
- if (!isStatus) {
479
- additionalAttributes = {
480
- ...additionalAttributes,
481
- addressing_mode: groupData.addressingMode
482
- }
483
- }
484
-
485
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
486
- devices.push(...additionalDevices)
487
- }
488
-
489
- const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)))
490
- const bytes = Utils_1.encodeWAMessage(patched)
491
-
492
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
493
- group: destinationJid,
494
- data: bytes,
495
- meId,
496
- })
497
-
498
- const senderKeyJids = []
499
-
500
- // ensure a connection is established with every device
501
- for (const { user, device } of devices) {
502
- const jid = WABinary_1.jidEncode(user, 's.whatsapp.net', device)
503
- if (!senderKeyMap[jid] || !!participant) {
504
- senderKeyJids.push(jid)
505
- // store that this person has had the sender keys sent to them
506
- senderKeyMap[jid] = true
507
- }
508
- }
509
-
510
- // if there are some participants with whom the session has not been established
511
- // if there are, we re-send the senderkey
512
- if (senderKeyJids.length) {
513
- logger.debug({ senderKeyJids }, 'sending new sender key')
514
- const senderKeyMsg = {
515
- senderKeyDistributionMessage: {
516
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
517
- groupId: destinationJid
518
- }
519
- }
520
-
521
- await assertSessions(senderKeyJids, false)
522
-
523
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
524
-
525
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
526
-
527
- participants.push(...result.nodes)
528
- }
529
-
530
- binaryNodeContent.push({
531
- tag: 'enc',
532
- attrs: { v: '2', type: 'skmsg', ...extraAttrs },
533
- content: ciphertext
534
- })
535
-
536
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
537
- }
538
-
539
- else if (isNewsletter) {
540
- // Message edit
541
- if (message.protocolMessage?.editedMessage) {
542
- msgId = message.protocolMessage.key?.id
543
- message = message.protocolMessage.editedMessage
544
- }
545
-
546
- // Message delete
547
- if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
548
- msgId = message.protocolMessage.key?.id
549
- message = {}
550
- }
551
-
552
- const patched = await patchMessageBeforeSending(message, [])
553
- const bytes = Utils_1.encodeNewsletterMessage(patched)
554
-
555
- binaryNodeContent.push({
556
- tag: 'plaintext',
557
- attrs: extraAttrs ? extraAttrs : {},
558
- content: bytes
559
- })
560
- }
561
-
562
- else {
563
- const { user: meUser } = WABinary_1.jidDecode(meId)
564
-
565
- if (!participant) {
566
- devices.push({ user })
567
- if (user !== meUser) {
568
- devices.push({ user: meUser })
569
- }
570
-
571
- if (additionalAttributes?.['category'] !== 'peer') {
572
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
573
-
574
- devices.push(...additionalDevices)
575
- }
576
- }
577
-
578
- const allJids = []
579
- const meJids = []
580
- const otherJids = []
581
-
582
- for (const { user, device } of devices) {
583
- const isMe = user === meUser
584
- const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
585
-
586
- if (isMe) {
587
- meJids.push(jid)
588
- }
589
-
590
- else {
591
- otherJids.push(jid)
592
- }
593
-
594
- allJids.push(jid)
595
- }
596
-
597
- await assertSessions(allJids, false)
598
-
599
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
600
- createParticipantNodes(meJids, meMsg, extraAttrs),
601
- createParticipantNodes(otherJids, message, extraAttrs)
602
- ])
603
-
604
- participants.push(...meNodes)
605
-
606
- participants.push(...otherNodes)
607
-
608
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
609
- }
610
-
611
- if (participants.length) {
612
- if (additionalAttributes?.['category'] === 'peer') {
613
- const peerNode = participants[0]?.content?.[0]
614
-
615
- if (peerNode) {
616
- binaryNodeContent.push(peerNode) // push only enc
617
- }
618
- }
619
-
620
- else {
621
- binaryNodeContent.push({
622
- tag: 'participants',
623
- attrs: {},
624
- content: participants
625
- })
626
- }
627
- }
628
-
629
- const stanza = {
630
- tag: 'message',
631
- attrs: {
632
- id: msgId,
633
- type: getTypeMessage(message),
634
- ...(additionalAttributes || {})
635
- },
636
- content: binaryNodeContent
637
- }
638
-
639
- // if the participant to send to is explicitly specified (generally retry recp)
640
- // ensure the message is only sent to that person
641
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
642
- if (participant) {
643
- if (WABinary_1.isJidGroup(destinationJid)) {
644
- stanza.attrs.to = destinationJid
645
- stanza.attrs.participant = participant.jid
646
- }
647
-
648
- else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
649
- stanza.attrs.to = participant.jid
650
- stanza.attrs.recipient = destinationJid
651
- }
652
-
653
- else {
654
- stanza.attrs.to = participant.jid
655
- }
656
- }
657
-
658
- else {
659
- stanza.attrs.to = destinationJid
660
- }
661
-
662
- if (shouldIncludeDeviceIdentity) {
663
- stanza.content.push({
664
- tag: 'device-identity',
665
- attrs: {},
666
- content: Utils_1.encodeSignedDeviceIdentity(authState.creds.account, true)
667
- })
668
-
669
- logger.debug({ jid }, 'adding device identity')
670
- }
671
-
672
- if (isGroup && regexGroupOld.test(jid) && !message.reactionMessage) {
673
- stanza.content.push({
674
- tag: 'multicast',
675
- attrs: {}
676
- })
677
- }
678
-
679
- if (pollMessage || messages.eventMessage) {
680
- stanza.content.push({
681
- tag: 'meta',
682
- attrs: messages.eventMessage ? {
683
- event_type: 'creation'
684
- } : isNewsletter ? {
685
- polltype: 'creation',
686
- contenttype: pollMessage?.pollContentType === 2 ? 'image' : 'text'
687
- } : {
688
- polltype: 'creation'
689
- }
690
- })
691
- }
692
-
693
- if (!isNewsletter && buttonType) {
694
- const buttonsNode = getButtonArgs(messages)
695
- const filteredButtons = WABinary_1.getBinaryFilteredButtons(additionalNodes ? additionalNodes : [])
696
-
697
- if (filteredButtons) {
698
- stanza.content.push(...additionalNodes)
699
- didPushAdditional = true
700
- }
701
-
702
- else {
703
- stanza.content.push(buttonsNode)
704
- }
705
- }
706
-
707
- if (AI && isPrivate) {
708
- const botNode = {
709
- tag: 'bot',
710
- attrs: {
711
- biz_bot: '1'
712
- }
713
- }
714
-
715
- const filteredBizBot = WABinary_1.getBinaryFilteredBizBot(additionalNodes ? additionalNodes : [])
716
-
717
- if (filteredBizBot) {
718
- stanza.content.push(...additionalNodes)
719
- didPushAdditional = true
720
- }
721
-
722
- else {
723
- stanza.content.push(botNode)
724
- }
725
- }
726
-
727
- if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
728
- stanza.content.push(...additionalNodes)
729
- }
730
-
731
- logger.debug({ msgId }, `sending message to ${participants.length} devices`)
732
-
733
- await sendNode(stanza)
734
- })
735
-
736
- return msgId
737
- }
738
-
739
- const getTypeMessage = (msg) => {
740
- const message = Utils_1.normalizeMessageContent(msg)
741
- if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
742
- return 'poll'
743
- }
744
- else if (message.reactionMessage) {
745
- return 'reaction'
746
- }
747
- else if (message.eventMessage) {
748
- return 'event'
749
- }
750
- else if (getMediaType(message)) {
751
- return 'media'
752
- }
753
- else {
754
- return 'text'
755
- }
756
- }
757
-
758
- const getMediaType = (message) => {
759
- if (message.imageMessage) {
760
- return 'image'
761
- }
762
- else if (message.stickerMessage) {
763
- return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker'
764
- }
765
- else if (message.videoMessage) {
766
- return message.videoMessage.gifPlayback ? 'gif' : 'video'
767
- }
768
- else if (message.audioMessage) {
769
- return message.audioMessage.ptt ? 'ptt' : 'audio'
770
- }
771
- else if (message.ptvMessage) {
772
- return 'ptv'
773
- }
774
- else if (message.contactMessage) {
775
- return 'vcard'
776
- }
777
- else if (message.documentMessage) {
778
- return 'document'
779
- }
780
- else if (message.stickerPackMessage) {
781
- return 'sticker_pack'
782
- }
783
- else if (message.contactsArrayMessage) {
784
- return 'contact_array'
785
- }
786
- else if (message.locationMessage) {
787
- return 'location'
788
- }
789
- else if (message.liveLocationMessage) {
790
- return 'livelocation'
791
- }
792
- else if (message.listMessage) {
793
- return 'list'
794
- }
795
- else if (message.listResponseMessage) {
796
- return 'list_response'
797
- }
798
- else if (message.buttonsResponseMessage) {
799
- return 'buttons_response'
800
- }
801
- else if (message.orderMessage) {
802
- return 'order'
803
- }
804
- else if (message.productMessage) {
805
- return 'product'
806
- }
807
- else if (message.interactiveResponseMessage) {
808
- return 'native_flow_response'
809
- }
810
- else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
811
- return 'cataloglink'
812
- }
813
- else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
814
- return 'productlink'
815
- }
816
- else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
817
- return 'url'
818
- }
819
- }
820
-
821
- const getButtonType = (message) => {
822
- if (message.listMessage) {
823
- return 'list'
824
- }
825
- else if (message.buttonsMessage) {
826
- return 'buttons'
827
- }
828
- else if(message.interactiveMessage?.nativeFlowMessage) {
829
- return 'native_flow'
830
- }
831
- }
832
-
833
- const getButtonArgs = (message) => {
834
- const nativeFlow = message.interactiveMessage?.nativeFlowMessage
835
- const firstButtonName = nativeFlow?.buttons?.[0]?.name
836
- const nativeFlowSpecials = [
837
- 'mpm', 'cta_catalog', 'send_location',
838
- 'call_permission_request', 'wa_payment_transaction_details',
839
- 'automated_greeting_message_view_catalog'
840
- ]
841
-
842
- if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
843
- return {
844
- tag: 'biz',
845
- attrs: {
846
- native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
847
- }
848
- }
849
- } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
850
- // Only works for WhatsApp Original, not WhatsApp Business
851
- return {
852
- tag: 'biz',
853
- attrs: {},
854
- content: [{
855
- tag: 'interactive',
856
- attrs: {
857
- type: 'native_flow',
858
- v: '1'
859
- },
860
- content: [{
861
- tag: 'native_flow',
862
- attrs: {
863
- v: '2',
864
- name: firstButtonName
865
- }
866
- }]
867
- }]
868
- }
869
- } else if (nativeFlow || message.buttonsMessage) {
870
- // It works for whatsapp original and whatsapp business
871
- return {
872
- tag: 'biz',
873
- attrs: {},
874
- content: [{
875
- tag: 'interactive',
876
- attrs: {
877
- type: 'native_flow',
878
- v: '1'
879
- },
880
- content: [{
881
- tag: 'native_flow',
882
- attrs: {
883
- v: '9',
884
- name: 'mixed'
885
- }
886
- }]
887
- }]
888
- }
889
- } else if (message.listMessage) {
890
- return {
891
- tag: 'biz',
892
- attrs: {},
893
- content: [{
894
- tag: 'list',
895
- attrs: {
896
- v: '2',
897
- type: 'product_list'
898
- }
899
- }]
900
- }
901
- } else {
902
- return {
903
- tag: 'biz',
904
- attrs: {}
905
- }
906
- }
907
- }
908
-
909
- const getPrivacyTokens = async (jids) => {
910
- const t = Utils_1.unixTimestampSeconds().toString()
911
-
912
- const result = await query({
913
- tag: 'iq',
914
- attrs: {
915
- to: WABinary_1.S_WHATSAPP_NET,
916
- type: 'set',
917
- xmlns: 'privacy'
918
- },
919
- content: [
920
- {
921
- tag: 'tokens',
922
- attrs: {},
923
- content: jids.map(jid => ({
924
- tag: 'token',
925
- attrs: {
926
- jid: WABinary_1.jidNormalizedUser(jid),
927
- t,
928
- type: 'trusted_contact'
929
- }
930
- }))
931
- }
932
- ]
933
- })
934
-
935
- return result
936
- }
937
-
938
- const getEphemeralGroup = (jid) => {
939
- if (!WABinary_1.isJidGroup(jid)) throw new TypeError("Jid should originate from a group!")
940
-
941
- return groupQuery(jid, 'get', [{
942
- tag: 'query',
943
- attrs: {
944
- request: 'interactive'
945
- }
946
- }])
947
- .then((groups) => WABinary_1.getBinaryNodeChild(groups, 'group'))
948
- .then((metadata) => WABinary_1.getBinaryNodeChild(metadata, 'ephemeral')?.attrs?.expiration || 0)
949
- }
950
-
951
- const waUploadToServer = Utils_1.getWAUploadToServer(config, refreshMediaConn)
952
-
953
- const waitForMsgMediaUpdate = Utils_1.bindWaitForEvent(ev, 'messages.media-update')
954
-
955
- return {
956
- ...suki,
957
- getPrivacyTokens,
958
- assertSessions,
959
- relayMessage,
960
- sendReceipt,
961
- sendReceipts,
962
- readMessages,
963
- profilePictureUrl,
964
- getUSyncDevices,
965
- refreshMediaConn,
966
- waUploadToServer,
967
- getEphemeralGroup,
968
- fetchPrivacySettings,
969
- createParticipantNodes,
970
- sendPeerDataOperationMessage,
971
- updateMediaMessage: async (message) => {
972
- const content = Utils_1.assertMediaContent(message.message)
973
- const mediaKey = content.mediaKey
974
- const meId = authState.creds.me.id
975
- const node = await Utils_1.encryptMediaRetryRequest(message.key, mediaKey, meId)
976
- let error = undefined
977
-
978
- await Promise.all([
979
- sendNode(node),
980
- waitForMsgMediaUpdate(async (update) => {
981
- const result = update.find(c => c.key.id === message.key.id)
982
- if (result) {
983
- if (result.error) {
984
- error = result.error
985
- }
986
-
987
- else {
988
- try {
989
- const media = await Utils_1.decryptMediaRetryData(result.media, mediaKey, result.key.id)
990
-
991
- if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
992
- const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result]
993
-
994
- throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: Utils_1.getStatusCodeForMediaRetry(media.result) || 404 })
995
- }
996
-
997
- content.directPath = media.directPath
998
-
999
- content.url = Utils_1.getUrlFromDirectPath(content.directPath)
1000
-
1001
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
1002
- }
1003
-
1004
- catch (err) {
1005
- error = err
1006
- }
1007
- }
1008
-
1009
- return true
1010
- }
1011
- })
1012
- ])
1013
-
1014
- if (error) {
1015
- throw error
1016
- }
1017
-
1018
- ev.emit('messages.update', [
1019
- { key: message.key, update: { message: message.message } }
1020
- ])
1021
-
1022
- return message
1023
- },
1024
- sendStatusMentions: async (content, jids = []) => {
1025
- const userJid = WABinary_1.jidNormalizedUser(authState.creds.me.id)
1026
- let allUsers = new Set()
1027
- allUsers.add(userJid)
1028
-
1029
- for (const id of jids) {
1030
- const isGroup = WABinary_1.isJidGroup(id)
1031
- const isPrivate = WABinary_1.isJidUser(id)
1032
-
1033
- if (isGroup) {
1034
- try {
1035
- const metadata = await cachedGroupMetadata(id) || await groupMetadata(id)
1036
- const participants = metadata.participants.map(p => WABinary_1.jidNormalizedUser(p.id))
1037
- participants.forEach(jid => allUsers.add(jid))
1038
- } catch (error) {
1039
- logger.error(`Error getting metadata for group ${id}: ${error}`)
1040
- }
1041
- } else if (isPrivate) {
1042
- allUsers.add(WABinary_1.jidNormalizedUser(id))
1043
- }
1044
- }
1045
-
1046
- const uniqueUsers = Array.from(allUsers)
1047
- const getRandomHexColor = () => "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")
1048
-
1049
- const isMedia = content.image || content.video || content.audio
1050
- const isAudio = !!content.audio
1051
-
1052
- const messageContent = { ...content }
1053
-
1054
- if (isMedia && !isAudio) {
1055
- if (messageContent.text) {
1056
- messageContent.caption = messageContent.text
1057
-
1058
- delete messageContent.text
1059
- }
1060
-
1061
- delete messageContent.ptt
1062
- delete messageContent.font
1063
- delete messageContent.backgroundColor
1064
- delete messageContent.textColor
1065
- }
1066
-
1067
- if (isAudio) {
1068
- delete messageContent.text
1069
- delete messageContent.caption
1070
- delete messageContent.font
1071
- delete messageContent.textColor
1072
- }
1073
-
1074
- const font = !isMedia ? (content.font || Math.floor(Math.random() * 9)) : undefined
1075
- const textColor = !isMedia ? (content.textColor || getRandomHexColor()) : undefined
1076
- const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor || getRandomHexColor()) : undefined
1077
- const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined
1078
-
1079
- let msg
1080
- let mediaHandle
1081
- try {
1082
- msg = await Utils_1.generateWAMessage(WABinary_1.STORIES_JID, messageContent, {
1083
- logger,
1084
- userJid,
1085
- getUrlInfo: text => link_preview_1.getUrlInfo(text, {
1086
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1087
- fetchOpts: { timeout: 3000, ...axiosOptions || {} },
1088
- logger,
1089
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1090
- }),
1091
- upload: async (encFilePath, opts) => {
1092
- const up = await waUploadToServer(encFilePath, { ...opts })
1093
- mediaHandle = up.handle
1094
- return up
1095
- },
1096
- mediaCache: config.mediaCache,
1097
- options: config.options,
1098
- font,
1099
- textColor,
1100
- backgroundColor,
1101
- ptt
1102
- })
1103
- } catch (error) {
1104
- logger.error(`Error generating message: ${error}`)
1105
- throw error
1106
- }
1107
-
1108
- await relayMessage(WABinary_1.STORIES_JID, msg.message, {
1109
- messageId: msg.key.id,
1110
- statusJidList: uniqueUsers,
1111
- additionalNodes: [
1112
- {
1113
- tag: 'meta',
1114
- attrs: {},
1115
- content: [
1116
- {
1117
- tag: 'mentioned_users',
1118
- attrs: {},
1119
- content: jids.map(jid => ({
1120
- tag: 'to',
1121
- attrs: { jid: WABinary_1.jidNormalizedUser(jid) }
1122
- }))
1123
- }]
1124
- }]
1125
- })
1126
-
1127
- for (const id of jids) {
1128
- try {
1129
- const normalizedId = WABinary_1.jidNormalizedUser(id)
1130
- const isPrivate = WABinary_1.isJidUser(normalizedId)
1131
- const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage'
1132
-
1133
- const protocolMessage = {
1134
- [type]: {
1135
- message: {
1136
- protocolMessage: {
1137
- key: msg.key,
1138
- type: 25
1139
- }
1140
- }
1141
- },
1142
- messageContextInfo: {
1143
- messageSecret: crypto_1.randomBytes(32)
1144
- }
1145
- }
1146
-
1147
- const statusMsg = await Utils_1.generateWAMessageFromContent(normalizedId,
1148
- protocolMessage,
1149
- {}
1150
- )
1151
-
1152
- await relayMessage(
1153
- normalizedId,
1154
- statusMsg.message,
1155
- {
1156
- additionalNodes: [{
1157
- tag: 'meta',
1158
- attrs: isPrivate ?
1159
- { is_status_mention: 'true' } :
1160
- { is_group_status_mention: 'true' }
1161
- }]
1162
- }
1163
- )
1164
-
1165
- await Utils_1.delay(2000)
1166
- } catch (error) {
1167
- logger.error(`Error sending to ${id}: ${error}`)
1168
- }
1169
- }
1170
-
1171
- return msg
1172
- },
1173
- sendAlbumMessage: async (jid, medias, options = {}) => {
1174
- const userJid = authState.creds.me.id
1175
-
1176
- for (const media of medias) {
1177
- if (!media.image && !media.video)
1178
- throw new TypeError(`medias[i] must have image or video property`)
1179
- }
1180
-
1181
- const time = options.delay || 500
1182
-
1183
- delete options.delay
1184
-
1185
- const album = await Utils_1.generateWAMessageFromContent(jid, {
1186
- albumMessage: {
1187
- expectedImageCount: medias.filter(media => media.image).length,
1188
- expectedVideoCount: medias.filter(media => media.video).length,
1189
- ...options
1190
- }
1191
- }, { userJid, ...options })
1192
-
1193
- await relayMessage(jid, album.message, { messageId: album.key.id })
1194
-
1195
- let mediaHandle
1196
- let msg
1197
-
1198
- for (const i in medias) {
1199
- const media = medias[i]
1200
-
1201
- if (media.image) {
1202
- msg = await Utils_1.generateWAMessage(jid, {
1203
- image: media.image,
1204
- ...media,
1205
- ...options
1206
- }, {
1207
- userJid,
1208
- upload: async (encFilePath, opts) => {
1209
- const up = await waUploadToServer(encFilePath, { ...opts, newsletter: WABinary_1.isJidNewsletter(jid) })
1210
- mediaHandle = up.handle
1211
- return up
1212
- },
1213
- ...options
1214
- })
1215
- }
1216
-
1217
- else if (media.video) {
1218
- msg = await Utils_1.generateWAMessage(jid, {
1219
- video: media.video,
1220
- ...media,
1221
- ...options
1222
- }, {
1223
- userJid,
1224
- upload: async (encFilePath, opts) => {
1225
- const up = await waUploadToServer(encFilePath, { ...opts, newsletter: WABinary_1.isJidNewsletter(jid) })
1226
- mediaHandle = up.handle
1227
- return up
1228
- },
1229
- ...options,
1230
- })
1231
- }
1232
-
1233
- if (msg) {
1234
- msg.message.messageContextInfo = {
1235
- messageSecret: crypto_1.randomBytes(32),
1236
- messageAssociation: {
1237
- associationType: 1,
1238
- parentMessageKey: album.key
1239
- }
1240
- }
1241
- }
1242
-
1243
- await relayMessage(jid, msg.message, { messageId: msg.key.id })
1244
- await Utils_1.delay(time)
1245
- }
1246
-
1247
- return album
1248
- },
1249
- sendMessage: async (jid, content, options = {}) => {
1250
- const userJid = authState.creds.me.id
1251
-
1252
- if (!options.ephemeralExpiration) {
1253
- if (WABinary_1.isJidGroup(jid)) {
1254
- const expiration = await getEphemeralGroup(jid)
1255
- options.ephemeralExpiration = expiration
1256
- }
1257
- }
1258
-
1259
- if (typeof content === 'object' &&
1260
- 'disappearingMessagesInChat' in content &&
1261
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1262
- WABinary_1.isJidGroup(jid)) {
1263
-
1264
- const { disappearingMessagesInChat } = content
1265
-
1266
- const value = typeof disappearingMessagesInChat === 'boolean' ?
1267
- (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
1268
- disappearingMessagesInChat
1269
-
1270
- await groupToggleEphemeral(jid, value)
1271
- }
1272
-
1273
- else {
1274
- let mediaHandle
1275
-
1276
- const fullMsg = await Utils_1.generateWAMessage(jid, content, {
1277
- logger,
1278
- userJid,
1279
- getUrlInfo: text => link_preview_1.getUrlInfo(text, {
1280
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1281
- fetchOpts: {
1282
- timeout: 3000,
1283
- ...axiosOptions || {}
1284
- },
1285
- logger,
1286
- uploadImage: generateHighQualityLinkPreview
1287
- ? waUploadToServer
1288
- : undefined
1289
- }),
1290
- getProfilePicUrl: profilePictureUrl,
1291
- upload: async (encFilePath, opts) => {
1292
- const up = await waUploadToServer(encFilePath, { ...opts, newsletter: WABinary_1.isJidNewsletter(jid) })
1293
- mediaHandle = up.handle
1294
- return up
1295
- },
1296
- mediaCache: config.mediaCache,
1297
- options: config.options,
1298
- messageId: Utils_1.generateMessageID(userJid),
1299
- ...options,
1300
- })
1301
-
1302
- const isPin = 'pin' in content && !!content.pin
1303
- const isEdit = 'edit' in content && !!content.edit
1304
- const isDelete = 'delete' in content && !!content.delete
1305
- const isKeep = 'keep' in content && !!content.keep && content.keep?.type === 2
1306
-
1307
- const additionalAttributes = {}
1308
-
1309
- if (isDelete || isKeep) {
1310
- // if the chat is a group, and I am not the author, then delete the message as an admin
1311
- if (WABinary_1.isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe || WABinary_1.isJidNewsletter(jid)) {
1312
- additionalAttributes.edit = '8'
1313
- }
1314
-
1315
- else {
1316
- additionalAttributes.edit = '7'
1317
- }
1318
- }
1319
-
1320
- else if (isEdit) {
1321
- additionalAttributes.edit = WABinary_1.isJidNewsletter(jid) ? '3' : '1'
1322
- }
1323
-
1324
- else if (isPin) {
1325
- additionalAttributes.edit = '2'
1326
- }
1327
-
1328
- if (mediaHandle) {
1329
- additionalAttributes['media_id'] = mediaHandle
1330
- }
1331
-
1332
- if ('cachedGroupMetadata' in options) {
1333
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.')
1334
- }
1335
-
1336
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes: options.additionalNodes, AI: options.ai })
1337
-
1338
- if (config.emitOwnEvents) {
1339
- process.nextTick(() => {
1340
- processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')))
1341
- })
1342
- }
1343
-
1344
- return fullMsg
1345
- }
1346
- }
1347
- }
1348
- }
1349
-
1350
- module.exports = {
1351
- makeMessagesSocket
1
+ "use strict"
2
+
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod }
5
+ }
6
+
7
+ Object.defineProperty(exports, "__esModule", { value: true })
8
+
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
10
+ const boom_1 = require("@hapi/boom")
11
+ const crypto_1 = require("crypto")
12
+ const WAProto_1 = require("../../WAProto")
13
+ const Defaults_1 = require("../Defaults")
14
+ const Utils_1 = require("../Utils")
15
+ const Types_1 = require("../Types")
16
+ const WABinary_1 = require("../WABinary")
17
+ const WAUSync_1 = require("../WAUSync")
18
+ const newsletter_1 = require("./newsletter")
19
+ const link_preview_1 = require("../Utils/link-preview")
20
+
21
+ const makeMessagesSocket = (config) => {
22
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config
23
+ const suki = newsletter_1.makeNewsletterSocket(config)
24
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, createCallLink, query, fetchPrivacySettings, sendNode, groupQuery, groupMetadata, groupToggleEphemeral, newsletterWMexQuery, executeUSyncQuery } = suki
25
+
26
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
27
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
28
+ useClones: false
29
+ })
30
+
31
+ let mediaConn
32
+
33
+ const refreshMediaConn = async (forceGet = false) => {
34
+ const media = await mediaConn
35
+
36
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
37
+ mediaConn = (async () => {
38
+
39
+ const result = await query({
40
+ tag: 'iq',
41
+ attrs: {
42
+ type: 'set',
43
+ xmlns: 'w:m',
44
+ to: WABinary_1.S_WHATSAPP_NET,
45
+ },
46
+ content: [{ tag: 'media_conn', attrs: {} }]
47
+ })
48
+
49
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn')
50
+
51
+ const node = {
52
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
53
+ hostname: attrs.hostname,
54
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
55
+ })),
56
+ auth: mediaConnNode.attrs.auth,
57
+ ttl: +mediaConnNode.attrs.ttl,
58
+ fetchDate: new Date()
59
+ }
60
+
61
+ logger.debug('fetched media conn')
62
+
63
+ return node
64
+ })()
65
+ }
66
+
67
+ return mediaConn
68
+ }
69
+
70
+ /**
71
+ * generic send receipt function
72
+ * used for receipts of phone call, read, delivery etc.
73
+ * */
74
+ const sendReceipt = async (jid, participant, messageIds, type) => {
75
+ const node = {
76
+ tag: 'receipt',
77
+ attrs: {
78
+ id: messageIds[0],
79
+ },
80
+ }
81
+
82
+ const isReadReceipt = type === 'read' || type === 'read-self'
83
+
84
+ if (isReadReceipt) {
85
+ node.attrs.t = Utils_1.unixTimestampSeconds().toString()
86
+ }
87
+
88
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
89
+ node.attrs.recipient = jid
90
+ node.attrs.to = participant
91
+ }
92
+
93
+ else {
94
+ node.attrs.to = jid
95
+ if (participant) {
96
+ node.attrs.participant = participant
97
+ }
98
+ }
99
+
100
+ if (type) {
101
+ node.attrs.type = WABinary_1.isJidNewsletter(jid) ? 'read-self' : type
102
+ }
103
+
104
+ const remainingMessageIds = messageIds.slice(1)
105
+
106
+ if (remainingMessageIds.length) {
107
+ node.content = [
108
+ {
109
+ tag: 'list',
110
+ attrs: {},
111
+ content: remainingMessageIds.map(id => ({
112
+ tag: 'item',
113
+ attrs: { id }
114
+ }))
115
+ }
116
+ ]
117
+ }
118
+
119
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages')
120
+
121
+ await sendNode(node)
122
+ }
123
+
124
+ /** Correctly bulk send receipts to multiple chats, participants */
125
+ const sendReceipts = async (keys, type) => {
126
+ const recps = Utils_1.aggregateMessageKeysNotFromMe(keys)
127
+
128
+ for (const { jid, participant, messageIds } of recps) {
129
+ await sendReceipt(jid, participant, messageIds, type)
130
+ }
131
+ }
132
+
133
+ /** Bulk read messages. Keys can be from different chats & participants */
134
+ const readMessages = async (keys) => {
135
+ const privacySettings = await fetchPrivacySettings()
136
+
137
+ // based on privacy settings, we have to change the read type
138
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
139
+
140
+ await sendReceipts(keys, readType)
141
+ }
142
+
143
+ /** Fetch image for groups, user, and newsletter **/
144
+ const profilePictureUrl = async (jid) => {
145
+ if (WABinary_1.isJidNewsletter(jid)) {
146
+
147
+ let node = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
148
+ input: {
149
+ key: jid,
150
+ type: 'JID',
151
+ view_role: 'GUEST'
152
+ },
153
+ fetch_viewer_metadata: true,
154
+ fetch_full_image: true,
155
+ fetch_creation_time: true
156
+ })
157
+
158
+ let result = WABinary_1.getBinaryNodeChild(node, 'result')?.content?.toString()
159
+
160
+ let metadata = JSON.parse(result).data[Types_1.XWAPaths.NEWSLETTER]
161
+
162
+ return Utils_1.getUrlFromDirectPath(metadata.thread_metadata.picture?.direct_path || '')
163
+
164
+ }
165
+
166
+ else {
167
+ const result = await query({
168
+ tag: 'iq',
169
+ attrs: {
170
+ target: WABinary_1.jidNormalizedUser(jid),
171
+ to: WABinary_1.S_WHATSAPP_NET,
172
+ type: 'get',
173
+ xmlns: 'w:profile:picture'
174
+ },
175
+ content: [{
176
+ tag: 'picture',
177
+ attrs: {
178
+ type: 'image',
179
+ query: 'url'
180
+ }
181
+ }]
182
+ })
183
+
184
+ const child = WABinary_1.getBinaryNodeChild(result, 'picture')
185
+
186
+ return child?.attrs?.url || null
187
+ }
188
+ }
189
+
190
+ /** Fetch all the devices we've to send a message to */
191
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
192
+ const deviceResults = []
193
+
194
+ if (!useCache) {
195
+ logger.debug('not using cache for devices')
196
+ }
197
+
198
+ const toFetch = []
199
+
200
+ jids = Array.from(new Set(jids))
201
+
202
+ for (let jid of jids) {
203
+ const user = WABinary_1.jidDecode(jid)?.user
204
+
205
+ jid = WABinary_1.jidNormalizedUser(jid)
206
+
207
+ if (useCache) {
208
+ const devices = userDevicesCache.get(user)
209
+
210
+ if (devices) {
211
+ deviceResults.push(...devices)
212
+ logger.trace({ user }, 'using cache for devices')
213
+ }
214
+
215
+ else {
216
+ toFetch.push(jid)
217
+ }
218
+ }
219
+
220
+ else {
221
+ toFetch.push(jid)
222
+ }
223
+ }
224
+
225
+ if (!toFetch.length) {
226
+ return deviceResults
227
+ }
228
+
229
+ const query = new WAUSync_1.USyncQuery()
230
+ .withContext('message')
231
+ .withDeviceProtocol()
232
+
233
+ for (const jid of toFetch) {
234
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
235
+ }
236
+
237
+ const result = await executeUSyncQuery(query)
238
+
239
+ if (result) {
240
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
241
+ const deviceMap = {}
242
+
243
+ for (const item of extracted) {
244
+ deviceMap[item.user] = deviceMap[item.user] || []
245
+ deviceMap[item.user].push(item)
246
+ deviceResults.push(item)
247
+ }
248
+
249
+ for (const key in deviceMap) {
250
+ userDevicesCache.set(key, deviceMap[key])
251
+ }
252
+ }
253
+
254
+ return deviceResults
255
+ }
256
+
257
+ /** Assert Sessions */
258
+ const assertSessions = async (jids, force) => {
259
+ let didFetchNewSession = false
260
+ let jidsRequiringFetch = []
261
+
262
+ if (force) {
263
+ jidsRequiringFetch = jids
264
+ }
265
+
266
+ else {
267
+ const addrs = jids.map(jid => (signalRepository.jidToSignalProtocolAddress(jid)))
268
+
269
+ const sessions = await authState.keys.get('session', addrs)
270
+
271
+ for (const jid of jids) {
272
+ const signalId = signalRepository
273
+ .jidToSignalProtocolAddress(jid)
274
+
275
+ if (!sessions[signalId]) {
276
+ jidsRequiringFetch.push(jid)
277
+ }
278
+ }
279
+ }
280
+
281
+ if (jidsRequiringFetch.length) {
282
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions')
283
+
284
+ const result = await query({
285
+ tag: 'iq',
286
+ attrs: {
287
+ xmlns: 'encrypt',
288
+ type: 'get',
289
+ to: WABinary_1.S_WHATSAPP_NET,
290
+ },
291
+ content: [
292
+ {
293
+ tag: 'key',
294
+ attrs: {},
295
+ content: jidsRequiringFetch.map(jid => ({
296
+ tag: 'user',
297
+ attrs: { jid },
298
+ }))
299
+ }
300
+ ]
301
+ })
302
+
303
+ await Utils_1.parseAndInjectE2ESessions(result, signalRepository)
304
+
305
+ didFetchNewSession = true
306
+ }
307
+
308
+ return didFetchNewSession
309
+ }
310
+
311
+ /** Send Peer Operation */
312
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
313
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
314
+ if (!authState.creds.me?.id) {
315
+ throw new boom_1.Boom('Not authenticated')
316
+ }
317
+
318
+ const protocolMessage = {
319
+ protocolMessage: {
320
+ peerDataOperationRequestMessage: pdoMessage,
321
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
322
+ }
323
+ }
324
+
325
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id)
326
+
327
+ const msgId = await relayMessage(meJid, protocolMessage, {
328
+ additionalAttributes: {
329
+ category: 'peer',
330
+ // eslint-disable-next-line camelcase
331
+ push_priority: 'high_force',
332
+ },
333
+ })
334
+
335
+ return msgId
336
+ }
337
+
338
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
339
+ const patched = await patchMessageBeforeSending(message, jids)
340
+ const bytes = Utils_1.encodeWAMessage(patched)
341
+
342
+ let shouldIncludeDeviceIdentity = false
343
+
344
+ const nodes = await Promise.all(jids.map(async (jid) => {
345
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
346
+
347
+ if (type === 'pkmsg') {
348
+ shouldIncludeDeviceIdentity = true
349
+ }
350
+
351
+ const node = {
352
+ tag: 'to',
353
+ attrs: { jid },
354
+ content: [{
355
+ tag: 'enc',
356
+ attrs: {
357
+ v: '2',
358
+ type,
359
+ ...extraAttrs || {}
360
+ },
361
+ content: ciphertext
362
+ }]
363
+ }
364
+
365
+ return node
366
+ }))
367
+
368
+ return {
369
+ nodes,
370
+ shouldIncludeDeviceIdentity
371
+ }
372
+ }
373
+
374
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, additionalNodes, AI = false }) => {
375
+ const meId = authState.creds.me.id
376
+
377
+ let didPushAdditional = false
378
+ let shouldIncludeDeviceIdentity = false
379
+
380
+ const { user, server } = WABinary_1.jidDecode(jid)
381
+
382
+ const statusJid = 'status@broadcast'
383
+ const isGroup = server === 'g.us'
384
+ const isPrivate = server === 's.whatsapp.net'
385
+ const isNewsletter = server == 'newsletter'
386
+ const isStatus = jid === statusJid
387
+ const isLid = server === 'lid'
388
+
389
+ msgId = msgId || Utils_1.generateMessageID(authState.creds.me.id)
390
+ useUserDevicesCache = useUserDevicesCache !== false
391
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
392
+
393
+ const participants = []
394
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid
395
+ const binaryNodeContent = []
396
+ const devices = []
397
+
398
+ const meMsg = {
399
+ deviceSentMessage: {
400
+ destinationJid,
401
+ message
402
+ },
403
+ messageContextInfo: message.messageContextInfo || {}
404
+ }
405
+
406
+ const extraAttrs = {}
407
+
408
+ const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
409
+
410
+ const messages = Utils_1.normalizeMessageContent(message)
411
+
412
+ const buttonType = getButtonType(messages)
413
+ const pollMessage = messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
414
+
415
+
416
+ if (participant) {
417
+ // when the retry request is not for a group
418
+ // only send to the specific device that asked for a retry
419
+ // otherwise the message is sent out to every device that should be a recipient
420
+ if (!isGroup && !isStatus) {
421
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' }
422
+ }
423
+
424
+ const { user, device } = WABinary_1.jidDecode(participant.jid)
425
+
426
+ devices.push({ user, device })
427
+ }
428
+
429
+ await authState.keys.transaction(async () => {
430
+ const mediaType = getMediaType(message)
431
+
432
+ if (mediaType) {
433
+ extraAttrs['mediatype'] = mediaType
434
+ }
435
+
436
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
437
+ extraAttrs['decrypt-fail'] = 'hide'
438
+ }
439
+
440
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
441
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage.nativeFlowResponseMessage?.name || 'menu_options'
442
+ }
443
+
444
+ if (isGroup || isStatus) {
445
+ const [groupData, senderKeyMap] = await Promise.all([
446
+ (async () => {
447
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
448
+
449
+ if (groupData && Array.isArray(groupData?.participants)) {
450
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
451
+ }
452
+
453
+ else if (!isStatus) {
454
+ groupData = await groupMetadata(jid)
455
+ }
456
+
457
+ return groupData
458
+ })(),
459
+
460
+ (async () => {
461
+ if (!participant && !isStatus) {
462
+ const result = await authState.keys.get('sender-key-memory', [jid])
463
+ return result[jid] || {}
464
+ }
465
+
466
+ return {}
467
+
468
+ })()
469
+ ])
470
+
471
+ if (!participant) {
472
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
473
+
474
+ if (isStatus && statusJidList) {
475
+ participantsList.push(...statusJidList)
476
+ }
477
+
478
+ if (!isStatus) {
479
+ additionalAttributes = {
480
+ ...additionalAttributes,
481
+ addressing_mode: groupData.addressingMode
482
+ }
483
+ }
484
+
485
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
486
+ devices.push(...additionalDevices)
487
+ }
488
+
489
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)))
490
+ const bytes = Utils_1.encodeWAMessage(patched)
491
+
492
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
493
+ group: destinationJid,
494
+ data: bytes,
495
+ meId,
496
+ })
497
+
498
+ const senderKeyJids = []
499
+
500
+ // ensure a connection is established with every device
501
+ for (const { user, device } of devices) {
502
+ const jid = WABinary_1.jidEncode(user, 's.whatsapp.net', device)
503
+ if (!senderKeyMap[jid] || !!participant) {
504
+ senderKeyJids.push(jid)
505
+ // store that this person has had the sender keys sent to them
506
+ senderKeyMap[jid] = true
507
+ }
508
+ }
509
+
510
+ // if there are some participants with whom the session has not been established
511
+ // if there are, we re-send the senderkey
512
+ if (senderKeyJids.length) {
513
+ logger.debug({ senderKeyJids }, 'sending new sender key')
514
+ const senderKeyMsg = {
515
+ senderKeyDistributionMessage: {
516
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
517
+ groupId: destinationJid
518
+ }
519
+ }
520
+
521
+ await assertSessions(senderKeyJids, false)
522
+
523
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
524
+
525
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
526
+
527
+ participants.push(...result.nodes)
528
+ }
529
+
530
+ binaryNodeContent.push({
531
+ tag: 'enc',
532
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
533
+ content: ciphertext
534
+ })
535
+
536
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
537
+ }
538
+
539
+ else if (isNewsletter) {
540
+ // Message edit
541
+ if (message.protocolMessage?.editedMessage) {
542
+ msgId = message.protocolMessage.key?.id
543
+ message = message.protocolMessage.editedMessage
544
+ }
545
+
546
+ // Message delete
547
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
548
+ msgId = message.protocolMessage.key?.id
549
+ message = {}
550
+ }
551
+
552
+ const patched = await patchMessageBeforeSending(message, [])
553
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
554
+
555
+ binaryNodeContent.push({
556
+ tag: 'plaintext',
557
+ attrs: extraAttrs ? extraAttrs : {},
558
+ content: bytes
559
+ })
560
+ }
561
+
562
+ else {
563
+ const { user: meUser } = WABinary_1.jidDecode(meId)
564
+
565
+ if (!participant) {
566
+ devices.push({ user })
567
+ if (user !== meUser) {
568
+ devices.push({ user: meUser })
569
+ }
570
+
571
+ if (additionalAttributes?.['category'] !== 'peer') {
572
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
573
+
574
+ devices.push(...additionalDevices)
575
+ }
576
+ }
577
+
578
+ const allJids = []
579
+ const meJids = []
580
+ const otherJids = []
581
+
582
+ for (const { user, device } of devices) {
583
+ const isMe = user === meUser
584
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
585
+
586
+ if (isMe) {
587
+ meJids.push(jid)
588
+ }
589
+
590
+ else {
591
+ otherJids.push(jid)
592
+ }
593
+
594
+ allJids.push(jid)
595
+ }
596
+
597
+ await assertSessions(allJids, false)
598
+
599
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
600
+ createParticipantNodes(meJids, meMsg, extraAttrs),
601
+ createParticipantNodes(otherJids, message, extraAttrs)
602
+ ])
603
+
604
+ participants.push(...meNodes)
605
+
606
+ participants.push(...otherNodes)
607
+
608
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
609
+ }
610
+
611
+ if (participants.length) {
612
+ if (additionalAttributes?.['category'] === 'peer') {
613
+ const peerNode = participants[0]?.content?.[0]
614
+
615
+ if (peerNode) {
616
+ binaryNodeContent.push(peerNode) // push only enc
617
+ }
618
+ }
619
+
620
+ else {
621
+ binaryNodeContent.push({
622
+ tag: 'participants',
623
+ attrs: {},
624
+ content: participants
625
+ })
626
+ }
627
+ }
628
+
629
+ const stanza = {
630
+ tag: 'message',
631
+ attrs: {
632
+ id: msgId,
633
+ type: getTypeMessage(message),
634
+ ...(additionalAttributes || {})
635
+ },
636
+ content: binaryNodeContent
637
+ }
638
+
639
+ // if the participant to send to is explicitly specified (generally retry recp)
640
+ // ensure the message is only sent to that person
641
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
642
+ if (participant) {
643
+ if (WABinary_1.isJidGroup(destinationJid)) {
644
+ stanza.attrs.to = destinationJid
645
+ stanza.attrs.participant = participant.jid
646
+ }
647
+
648
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
649
+ stanza.attrs.to = participant.jid
650
+ stanza.attrs.recipient = destinationJid
651
+ }
652
+
653
+ else {
654
+ stanza.attrs.to = participant.jid
655
+ }
656
+ }
657
+
658
+ else {
659
+ stanza.attrs.to = destinationJid
660
+ }
661
+
662
+ if (shouldIncludeDeviceIdentity) {
663
+ stanza.content.push({
664
+ tag: 'device-identity',
665
+ attrs: {},
666
+ content: Utils_1.encodeSignedDeviceIdentity(authState.creds.account, true)
667
+ })
668
+
669
+ logger.debug({ jid }, 'adding device identity')
670
+ }
671
+
672
+ if (isGroup && regexGroupOld.test(jid) && !message.reactionMessage) {
673
+ stanza.content.push({
674
+ tag: 'multicast',
675
+ attrs: {}
676
+ })
677
+ }
678
+
679
+ if (pollMessage || messages.eventMessage) {
680
+ stanza.content.push({
681
+ tag: 'meta',
682
+ attrs: messages.eventMessage ? {
683
+ event_type: 'creation'
684
+ } : isNewsletter ? {
685
+ polltype: 'creation',
686
+ contenttype: pollMessage?.pollContentType === 2 ? 'image' : 'text'
687
+ } : {
688
+ polltype: 'creation'
689
+ }
690
+ })
691
+ }
692
+
693
+ if (!isNewsletter && buttonType) {
694
+ const buttonsNode = getButtonArgs(messages)
695
+ const filteredButtons = WABinary_1.getBinaryFilteredButtons(additionalNodes ? additionalNodes : [])
696
+
697
+ if (filteredButtons) {
698
+ stanza.content.push(...additionalNodes)
699
+ didPushAdditional = true
700
+ }
701
+
702
+ else {
703
+ stanza.content.push(buttonsNode)
704
+ }
705
+ }
706
+
707
+ if (AI && isPrivate) {
708
+ const botNode = {
709
+ tag: 'bot',
710
+ attrs: {
711
+ biz_bot: '1'
712
+ }
713
+ }
714
+
715
+ const filteredBizBot = WABinary_1.getBinaryFilteredBizBot(additionalNodes ? additionalNodes : [])
716
+
717
+ if (filteredBizBot) {
718
+ stanza.content.push(...additionalNodes)
719
+ didPushAdditional = true
720
+ }
721
+
722
+ else {
723
+ stanza.content.push(botNode)
724
+ }
725
+ }
726
+
727
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
728
+ stanza.content.push(...additionalNodes)
729
+ }
730
+
731
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`)
732
+
733
+ await sendNode(stanza)
734
+ })
735
+
736
+ return msgId
737
+ }
738
+
739
+ const getTypeMessage = (msg) => {
740
+ const message = Utils_1.normalizeMessageContent(msg)
741
+ if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
742
+ return 'poll'
743
+ }
744
+ else if (message.reactionMessage) {
745
+ return 'reaction'
746
+ }
747
+ else if (message.eventMessage) {
748
+ return 'event'
749
+ }
750
+ else if (getMediaType(message)) {
751
+ return 'media'
752
+ }
753
+ else {
754
+ return 'text'
755
+ }
756
+ }
757
+
758
+ const getMediaType = (message) => {
759
+ if (message.imageMessage) {
760
+ return 'image'
761
+ }
762
+ else if (message.stickerMessage) {
763
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker'
764
+ }
765
+ else if (message.videoMessage) {
766
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
767
+ }
768
+ else if (message.audioMessage) {
769
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
770
+ }
771
+ else if (message.ptvMessage) {
772
+ return 'ptv'
773
+ }
774
+ else if (message.contactMessage) {
775
+ return 'vcard'
776
+ }
777
+ else if (message.documentMessage) {
778
+ return 'document'
779
+ }
780
+ else if (message.stickerPackMessage) {
781
+ return 'sticker_pack'
782
+ }
783
+ else if (message.contactsArrayMessage) {
784
+ return 'contact_array'
785
+ }
786
+ else if (message.locationMessage) {
787
+ return 'location'
788
+ }
789
+ else if (message.liveLocationMessage) {
790
+ return 'livelocation'
791
+ }
792
+ else if (message.listMessage) {
793
+ return 'list'
794
+ }
795
+ else if (message.listResponseMessage) {
796
+ return 'list_response'
797
+ }
798
+ else if (message.buttonsResponseMessage) {
799
+ return 'buttons_response'
800
+ }
801
+ else if (message.orderMessage) {
802
+ return 'order'
803
+ }
804
+ else if (message.productMessage) {
805
+ return 'product'
806
+ }
807
+ else if (message.interactiveResponseMessage) {
808
+ return 'native_flow_response'
809
+ }
810
+ else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
811
+ return 'cataloglink'
812
+ }
813
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
814
+ return 'productlink'
815
+ }
816
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
817
+ return 'url'
818
+ }
819
+ }
820
+
821
+ const getButtonType = (message) => {
822
+ if (message.listMessage) {
823
+ return 'list'
824
+ }
825
+ else if (message.buttonsMessage) {
826
+ return 'buttons'
827
+ }
828
+ else if(message.interactiveMessage?.nativeFlowMessage) {
829
+ return 'native_flow'
830
+ }
831
+ }
832
+
833
+ const getButtonArgs = (message) => {
834
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage
835
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name
836
+ const nativeFlowSpecials = [
837
+ 'mpm', 'cta_catalog', 'send_location',
838
+ 'call_permission_request', 'wa_payment_transaction_details',
839
+ 'automated_greeting_message_view_catalog'
840
+ ]
841
+
842
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
843
+ return {
844
+ tag: 'biz',
845
+ attrs: {
846
+ native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
847
+ }
848
+ }
849
+ } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
850
+ // Only works for WhatsApp Original, not WhatsApp Business
851
+ return {
852
+ tag: 'biz',
853
+ attrs: {},
854
+ content: [{
855
+ tag: 'interactive',
856
+ attrs: {
857
+ type: 'native_flow',
858
+ v: '1'
859
+ },
860
+ content: [{
861
+ tag: 'native_flow',
862
+ attrs: {
863
+ v: '2',
864
+ name: firstButtonName
865
+ }
866
+ }]
867
+ }]
868
+ }
869
+ } else if (nativeFlow || message.buttonsMessage) {
870
+ // It works for whatsapp original and whatsapp business
871
+ return {
872
+ tag: 'biz',
873
+ attrs: {},
874
+ content: [{
875
+ tag: 'interactive',
876
+ attrs: {
877
+ type: 'native_flow',
878
+ v: '1'
879
+ },
880
+ content: [{
881
+ tag: 'native_flow',
882
+ attrs: {
883
+ v: '9',
884
+ name: 'mixed'
885
+ }
886
+ }]
887
+ }]
888
+ }
889
+ } else if (message.listMessage) {
890
+ return {
891
+ tag: 'biz',
892
+ attrs: {},
893
+ content: [{
894
+ tag: 'list',
895
+ attrs: {
896
+ v: '2',
897
+ type: 'product_list'
898
+ }
899
+ }]
900
+ }
901
+ } else {
902
+ return {
903
+ tag: 'biz',
904
+ attrs: {}
905
+ }
906
+ }
907
+ }
908
+
909
+ const getPrivacyTokens = async (jids) => {
910
+ const t = Utils_1.unixTimestampSeconds().toString()
911
+
912
+ const result = await query({
913
+ tag: 'iq',
914
+ attrs: {
915
+ to: WABinary_1.S_WHATSAPP_NET,
916
+ type: 'set',
917
+ xmlns: 'privacy'
918
+ },
919
+ content: [
920
+ {
921
+ tag: 'tokens',
922
+ attrs: {},
923
+ content: jids.map(jid => ({
924
+ tag: 'token',
925
+ attrs: {
926
+ jid: WABinary_1.jidNormalizedUser(jid),
927
+ t,
928
+ type: 'trusted_contact'
929
+ }
930
+ }))
931
+ }
932
+ ]
933
+ })
934
+
935
+ return result
936
+ }
937
+
938
+ const getEphemeralGroup = (jid) => {
939
+ if (!WABinary_1.isJidGroup(jid)) throw new TypeError("Jid should originate from a group!")
940
+
941
+ return groupQuery(jid, 'get', [{
942
+ tag: 'query',
943
+ attrs: {
944
+ request: 'interactive'
945
+ }
946
+ }])
947
+ .then((groups) => WABinary_1.getBinaryNodeChild(groups, 'group'))
948
+ .then((metadata) => WABinary_1.getBinaryNodeChild(metadata, 'ephemeral')?.attrs?.expiration || 0)
949
+ }
950
+
951
+ const waUploadToServer = Utils_1.getWAUploadToServer(config, refreshMediaConn)
952
+
953
+ const waitForMsgMediaUpdate = Utils_1.bindWaitForEvent(ev, 'messages.media-update')
954
+
955
+ return {
956
+ ...suki,
957
+ getPrivacyTokens,
958
+ assertSessions,
959
+ relayMessage,
960
+ sendReceipt,
961
+ sendReceipts,
962
+ readMessages,
963
+ profilePictureUrl,
964
+ getUSyncDevices,
965
+ refreshMediaConn,
966
+ waUploadToServer,
967
+ getEphemeralGroup,
968
+ fetchPrivacySettings,
969
+ createParticipantNodes,
970
+ sendPeerDataOperationMessage,
971
+ updateMediaMessage: async (message) => {
972
+ const content = Utils_1.assertMediaContent(message.message)
973
+ const mediaKey = content.mediaKey
974
+ const meId = authState.creds.me.id
975
+ const node = await Utils_1.encryptMediaRetryRequest(message.key, mediaKey, meId)
976
+ let error = undefined
977
+
978
+ await Promise.all([
979
+ sendNode(node),
980
+ waitForMsgMediaUpdate(async (update) => {
981
+ const result = update.find(c => c.key.id === message.key.id)
982
+ if (result) {
983
+ if (result.error) {
984
+ error = result.error
985
+ }
986
+
987
+ else {
988
+ try {
989
+ const media = await Utils_1.decryptMediaRetryData(result.media, mediaKey, result.key.id)
990
+
991
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
992
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result]
993
+
994
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: Utils_1.getStatusCodeForMediaRetry(media.result) || 404 })
995
+ }
996
+
997
+ content.directPath = media.directPath
998
+
999
+ content.url = Utils_1.getUrlFromDirectPath(content.directPath)
1000
+
1001
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
1002
+ }
1003
+
1004
+ catch (err) {
1005
+ error = err
1006
+ }
1007
+ }
1008
+
1009
+ return true
1010
+ }
1011
+ })
1012
+ ])
1013
+
1014
+ if (error) {
1015
+ throw error
1016
+ }
1017
+
1018
+ ev.emit('messages.update', [
1019
+ { key: message.key, update: { message: message.message } }
1020
+ ])
1021
+
1022
+ return message
1023
+ },
1024
+ sendStatusMentions: async (content, jids = []) => {
1025
+ const userJid = WABinary_1.jidNormalizedUser(authState.creds.me.id)
1026
+ let allUsers = new Set()
1027
+ allUsers.add(userJid)
1028
+
1029
+ for (const id of jids) {
1030
+ const isGroup = WABinary_1.isJidGroup(id)
1031
+ const isPrivate = WABinary_1.isJidUser(id)
1032
+
1033
+ if (isGroup) {
1034
+ try {
1035
+ const metadata = await cachedGroupMetadata(id) || await groupMetadata(id)
1036
+ const participants = metadata.participants.map(p => WABinary_1.jidNormalizedUser(p.id))
1037
+ participants.forEach(jid => allUsers.add(jid))
1038
+ } catch (error) {
1039
+ logger.error(`Error getting metadata for group ${id}: ${error}`)
1040
+ }
1041
+ } else if (isPrivate) {
1042
+ allUsers.add(WABinary_1.jidNormalizedUser(id))
1043
+ }
1044
+ }
1045
+
1046
+ const uniqueUsers = Array.from(allUsers)
1047
+ const getRandomHexColor = () => "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")
1048
+
1049
+ const isMedia = content.image || content.video || content.audio
1050
+ const isAudio = !!content.audio
1051
+
1052
+ const messageContent = { ...content }
1053
+
1054
+ if (isMedia && !isAudio) {
1055
+ if (messageContent.text) {
1056
+ messageContent.caption = messageContent.text
1057
+
1058
+ delete messageContent.text
1059
+ }
1060
+
1061
+ delete messageContent.ptt
1062
+ delete messageContent.font
1063
+ delete messageContent.backgroundColor
1064
+ delete messageContent.textColor
1065
+ }
1066
+
1067
+ if (isAudio) {
1068
+ delete messageContent.text
1069
+ delete messageContent.caption
1070
+ delete messageContent.font
1071
+ delete messageContent.textColor
1072
+ }
1073
+
1074
+ const font = !isMedia ? (content.font || Math.floor(Math.random() * 9)) : undefined
1075
+ const textColor = !isMedia ? (content.textColor || getRandomHexColor()) : undefined
1076
+ const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor || getRandomHexColor()) : undefined
1077
+ const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined
1078
+
1079
+ let msg
1080
+ let mediaHandle
1081
+ try {
1082
+ msg = await Utils_1.generateWAMessage(WABinary_1.STORIES_JID, messageContent, {
1083
+ logger,
1084
+ userJid,
1085
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
1086
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1087
+ fetchOpts: { timeout: 3000, ...axiosOptions || {} },
1088
+ logger,
1089
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1090
+ }),
1091
+ upload: async (encFilePath, opts) => {
1092
+ const up = await waUploadToServer(encFilePath, { ...opts })
1093
+ mediaHandle = up.handle
1094
+ return up
1095
+ },
1096
+ mediaCache: config.mediaCache,
1097
+ options: config.options,
1098
+ font,
1099
+ textColor,
1100
+ backgroundColor,
1101
+ ptt
1102
+ })
1103
+ } catch (error) {
1104
+ logger.error(`Error generating message: ${error}`)
1105
+ throw error
1106
+ }
1107
+
1108
+ await relayMessage(WABinary_1.STORIES_JID, msg.message, {
1109
+ messageId: msg.key.id,
1110
+ statusJidList: uniqueUsers,
1111
+ additionalNodes: [
1112
+ {
1113
+ tag: 'meta',
1114
+ attrs: {},
1115
+ content: [
1116
+ {
1117
+ tag: 'mentioned_users',
1118
+ attrs: {},
1119
+ content: jids.map(jid => ({
1120
+ tag: 'to',
1121
+ attrs: { jid: WABinary_1.jidNormalizedUser(jid) }
1122
+ }))
1123
+ }]
1124
+ }]
1125
+ })
1126
+
1127
+ for (const id of jids) {
1128
+ try {
1129
+ const normalizedId = WABinary_1.jidNormalizedUser(id)
1130
+ const isPrivate = WABinary_1.isJidUser(normalizedId)
1131
+ const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage'
1132
+
1133
+ const protocolMessage = {
1134
+ [type]: {
1135
+ message: {
1136
+ protocolMessage: {
1137
+ key: msg.key,
1138
+ type: 25
1139
+ }
1140
+ }
1141
+ },
1142
+ messageContextInfo: {
1143
+ messageSecret: crypto_1.randomBytes(32)
1144
+ }
1145
+ }
1146
+
1147
+ const statusMsg = await Utils_1.generateWAMessageFromContent(normalizedId,
1148
+ protocolMessage,
1149
+ {}
1150
+ )
1151
+
1152
+ await relayMessage(
1153
+ normalizedId,
1154
+ statusMsg.message,
1155
+ {
1156
+ additionalNodes: [{
1157
+ tag: 'meta',
1158
+ attrs: isPrivate ?
1159
+ { is_status_mention: 'true' } :
1160
+ { is_group_status_mention: 'true' }
1161
+ }]
1162
+ }
1163
+ )
1164
+
1165
+ await Utils_1.delay(2000)
1166
+ } catch (error) {
1167
+ logger.error(`Error sending to ${id}: ${error}`)
1168
+ }
1169
+ }
1170
+
1171
+ return msg
1172
+ },
1173
+ sendMessage: async (jid, content, options = {}) => {
1174
+ const userJid = authState.creds.me.id
1175
+ const additionalAttributes = {}
1176
+
1177
+ if (!options.ephemeralExpiration) {
1178
+ if (WABinary_1.isJidGroup(jid)) {
1179
+ const expiration = await getEphemeralGroup(jid)
1180
+ options.ephemeralExpiration = expiration
1181
+ }
1182
+ }
1183
+
1184
+ if (typeof content === 'object' &&
1185
+ 'disappearingMessagesInChat' in content &&
1186
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1187
+ WABinary_1.isJidGroup(jid)) {
1188
+
1189
+ const { disappearingMessagesInChat } = content
1190
+
1191
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
1192
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
1193
+ disappearingMessagesInChat
1194
+
1195
+ await groupToggleEphemeral(jid, value)
1196
+ }
1197
+
1198
+ else if (typeof content === 'object' && 'album' in content && content.album) {
1199
+ const albumMsg = await Utils_1.prepareAlbumMessageContent(jid, content.album, {
1200
+ suki: {
1201
+ relayMessage,
1202
+ waUploadToServer
1203
+ },
1204
+ userJid: userJid,
1205
+ ...options
1206
+ })
1207
+
1208
+ for (const media of albumMsg) {
1209
+ await Utils_1.delay(options.delay || 500)
1210
+ await relayMessage(jid, media.message, { messageId: media.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes: options.additionalNodes, AI: options.ai })
1211
+ }
1212
+
1213
+ return albumMsg
1214
+ }
1215
+
1216
+ else {
1217
+ let mediaHandle
1218
+
1219
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
1220
+ logger,
1221
+ userJid,
1222
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
1223
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1224
+ fetchOpts: {
1225
+ timeout: 3000,
1226
+ ...axiosOptions || {}
1227
+ },
1228
+ logger,
1229
+ uploadImage: generateHighQualityLinkPreview
1230
+ ? waUploadToServer
1231
+ : undefined
1232
+ }),
1233
+ getProfilePicUrl: profilePictureUrl,
1234
+ getCallLink: createCallLink,
1235
+ upload: async (encFilePath, opts) => {
1236
+ const up = await waUploadToServer(encFilePath, { ...opts, newsletter: WABinary_1.isJidNewsletter(jid) })
1237
+ mediaHandle = up.handle
1238
+ return up
1239
+ },
1240
+ mediaCache: config.mediaCache,
1241
+ options: config.options,
1242
+ messageId: Utils_1.generateMessageID(userJid),
1243
+ ...options,
1244
+ })
1245
+
1246
+ const isPin = 'pin' in content && !!content.pin
1247
+ const isEdit = 'edit' in content && !!content.edit
1248
+ const isDelete = 'delete' in content && !!content.delete
1249
+ const isKeep = 'keep' in content && !!content.keep && content.keep?.type === 2
1250
+
1251
+ if (isDelete || isKeep) {
1252
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1253
+ if (WABinary_1.isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe || WABinary_1.isJidNewsletter(jid)) {
1254
+ additionalAttributes.edit = '8'
1255
+ }
1256
+
1257
+ else {
1258
+ additionalAttributes.edit = '7'
1259
+ }
1260
+ }
1261
+
1262
+ else if (isEdit) {
1263
+ additionalAttributes.edit = WABinary_1.isJidNewsletter(jid) ? '3' : '1'
1264
+ }
1265
+
1266
+ else if (isPin) {
1267
+ additionalAttributes.edit = '2'
1268
+ }
1269
+
1270
+ if (mediaHandle) {
1271
+ additionalAttributes['media_id'] = mediaHandle
1272
+ }
1273
+
1274
+ if ('cachedGroupMetadata' in options) {
1275
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.')
1276
+ }
1277
+
1278
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes: options.additionalNodes, AI: options.ai })
1279
+
1280
+ if (config.emitOwnEvents) {
1281
+ process.nextTick(() => {
1282
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')))
1283
+ })
1284
+ }
1285
+
1286
+ return fullMsg
1287
+ }
1288
+ }
1289
+ }
1290
+ }
1291
+
1292
+ module.exports = {
1293
+ makeMessagesSocket
1352
1294
  }