sanka-baileyss 2.3.6 → 2.3.8

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.
@@ -1,11 +1,8 @@
1
1
  "use strict"
2
-
3
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod }
3
+ return (mod && mod.__esModule) ? mod : { "default": mod }
5
4
  }
6
-
7
5
  Object.defineProperty(exports, "__esModule", { value: true })
8
-
9
6
  const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
10
7
  const boom_1 = require("@hapi/boom")
11
8
  const crypto_1 = require("crypto")
@@ -17,1278 +14,969 @@ const WABinary_1 = require("../WABinary")
17
14
  const WAUSync_1 = require("../WAUSync")
18
15
  const newsletter_1 = require("./newsletter")
19
16
  const link_preview_1 = require("../Utils/link-preview")
20
-
21
17
  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
-
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config
19
+ const sock = newsletter_1.makeNewsletterSocket(config)
20
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, newsletterWMexQuery, executeUSyncQuery } = sock
21
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
22
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
23
+ useClones: false
24
+ })
25
+ let mediaConn
26
+ const refreshMediaConn = async (forceGet = false) => {
27
+ const media = await mediaConn
28
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
29
+ mediaConn = (async () => {
30
+ const result = await query({
31
+ tag: 'iq',
32
+ attrs: {
33
+ type: 'set',
34
+ xmlns: 'w:m',
35
+ to: WABinary_1.S_WHATSAPP_NET,
36
+ },
37
+ content: [{ tag: 'media_conn', attrs: {} }]
38
+ })
39
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn')
40
+ const node = {
41
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
42
+ hostname: attrs.hostname,
43
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
44
+ })),
45
+ auth: mediaConnNode.attrs.auth,
46
+ ttl: +mediaConnNode.attrs.ttl,
47
+ fetchDate: new Date()
48
+ }
49
+ logger.debug('fetched media conn')
50
+ return node
51
+ })()
52
+ }
53
+ return mediaConn
54
+ }
55
+ /**
56
+ * generic send receipt function
57
+ * used for receipts of phone call, read, delivery etc.
58
+ * */
59
+ const sendReceipt = async (jid, participant, messageIds, type) => {
60
+ const node = {
61
+ tag: 'receipt',
62
+ attrs: {
63
+ id: messageIds[0],
64
+ },
65
+ }
66
+ const isReadReceipt = type === 'read' || type === 'read-self'
67
+ if (isReadReceipt) {
68
+ node.attrs.t = Utils_1.unixTimestampSeconds().toString()
69
+ }
70
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
71
+ node.attrs.recipient = jid
72
+ node.attrs.to = participant
73
+ }
74
+ else {
75
+ node.attrs.to = jid
76
+ if (participant) {
77
+ node.attrs.participant = participant
78
+ }
79
+ }
80
+ if (type) {
81
+ node.attrs.type = WABinary_1.isJidNewsletter(jid) ? 'read-self' : type
82
+ }
83
+ const remainingMessageIds = messageIds.slice(1)
84
+ if (remainingMessageIds.length) {
85
+ node.content = [
86
+ {
87
+ tag: 'list',
88
+ attrs: {},
89
+ content: remainingMessageIds.map(id => ({
90
+ tag: 'item',
91
+ attrs: { id }
92
+ }))
93
+ }
94
+ ]
95
+ }
96
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages')
97
+ await sendNode(node)
98
+ }
99
+ /** Correctly bulk send receipts to multiple chats, participants */
100
+ const sendReceipts = async (keys, type) => {
101
+ const recps = Utils_1.aggregateMessageKeysNotFromMe(keys)
102
+ for (const { jid, participant, messageIds } of recps) {
103
+ await sendReceipt(jid, participant, messageIds, type)
104
+ }
105
+ }
106
+ /** Bulk read messages. Keys can be from different chats & participants */
107
+ const readMessages = async (keys) => {
108
+ const privacySettings = await fetchPrivacySettings()
109
+ // based on privacy settings, we have to change the read type
110
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
111
+ await sendReceipts(keys, readType)
112
+ }
113
+ /** Fetch image for groups, user, and newsletter **/
114
+ const profilePictureUrl = async (jid) => {
115
+ if (WABinary_1.isJidNewsletter(jid)) {
116
+ let node = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
117
+ input: {
118
+ key: jid,
119
+ type: 'JID',
120
+ view_role: 'GUEST'
121
+ },
122
+ fetch_viewer_metadata: true,
123
+ fetch_full_image: true,
124
+ fetch_creation_time: true
125
+ })
126
+ let result = WABinary_1.getBinaryNodeChild(node, 'result')?.content?.toString()
127
+ let metadata = JSON.parse(result).data[Types_1.XWAPaths.NEWSLETTER]
128
+ return Utils_1.getUrlFromDirectPath(metadata.thread_metadata.picture?.direct_path || '')
129
+ }
130
+ else {
131
+ const result = await query({
132
+ tag: 'iq',
133
+ attrs: {
134
+ target: WABinary_1.jidNormalizedUser(jid),
135
+ to: WABinary_1.S_WHATSAPP_NET,
136
+ type: 'get',
137
+ xmlns: 'w:profile:picture'
138
+ },
139
+ content: [{
140
+ tag: 'picture',
141
+ attrs: {
142
+ type: 'image',
143
+ query: 'url'
144
+ }
145
+ }]
146
+ })
147
+ const child = WABinary_1.getBinaryNodeChild(result, 'picture')
148
+ return child?.attrs?.url || null
149
+ }
150
+ }
151
+ /** Fetch all the devices we've to send a message to */
152
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
153
+ const deviceResults = []
154
+ if (!useCache) {
155
+ logger.debug('not using cache for devices')
156
+ }
157
+ const toFetch = []
158
+ jids = Array.from(new Set(jids))
159
+ for (let jid of jids) {
160
+ const user = WABinary_1.jidDecode(jid)?.user
161
+ jid = WABinary_1.jidNormalizedUser(jid)
162
+ if (useCache) {
163
+ const devices = userDevicesCache.get(user)
164
+ if (devices) {
165
+ deviceResults.push(...devices)
166
+ logger.trace({ user }, 'using cache for devices')
167
+ }
168
+ else {
169
+ toFetch.push(jid)
170
+ }
171
+ }
172
+ else {
173
+ toFetch.push(jid)
174
+ }
175
+ }
176
+ if (!toFetch.length) {
177
+ return deviceResults
178
+ }
179
+ const query = new WAUSync_1.USyncQuery()
180
+ .withContext('message')
181
+ .withDeviceProtocol()
182
+ for (const jid of toFetch) {
183
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
184
+ }
185
+ const result = await executeUSyncQuery(query)
186
+ if (result) {
187
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
188
+ const deviceMap = {}
189
+ for (const item of extracted) {
190
+ deviceMap[item.user] = deviceMap[item.user] || []
191
+ deviceMap[item.user].push(item)
192
+ deviceResults.push(item)
193
+ }
194
+ for (const key in deviceMap) {
195
+ userDevicesCache.set(key, deviceMap[key])
196
+ }
197
+ }
198
+ return deviceResults
199
+ }
200
+ /** Assert Sessions */
201
+ const assertSessions = async (jids, force) => {
202
+ let didFetchNewSession = false
203
+ let jidsRequiringFetch = []
204
+ if (force) {
205
+ jidsRequiringFetch = jids
206
+ }
207
+ else {
208
+ const addrs = jids.map(jid => (signalRepository.jidToSignalProtocolAddress(jid)))
209
+ const sessions = await authState.keys.get('session', addrs)
210
+ for (const jid of jids) {
211
+ const signalId = signalRepository
212
+ .jidToSignalProtocolAddress(jid)
213
+ if (!sessions[signalId]) {
214
+ jidsRequiringFetch.push(jid)
215
+ }
216
+ }
217
+ }
218
+ if (jidsRequiringFetch.length) {
219
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions')
220
+ const result = await query({
221
+ tag: 'iq',
222
+ attrs: {
223
+ xmlns: 'encrypt',
224
+ type: 'get',
225
+ to: WABinary_1.S_WHATSAPP_NET,
226
+ },
227
+ content: [
228
+ {
229
+ tag: 'key',
230
+ attrs: {},
231
+ content: jidsRequiringFetch.map(jid => ({
232
+ tag: 'user',
233
+ attrs: { jid },
234
+ }))
235
+ }
236
+ ]
237
+ })
238
+ await Utils_1.parseAndInjectE2ESessions(result, signalRepository)
239
+ didFetchNewSession = true
240
+ }
241
+ return didFetchNewSession
242
+ }
243
+ /** Send Peer Operation */
244
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
245
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
246
+ if (!authState.creds.me?.id) {
247
+ throw new boom_1.Boom('Not authenticated')
248
+ }
249
+ const protocolMessage = {
250
+ protocolMessage: {
251
+ peerDataOperationRequestMessage: pdoMessage,
252
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
253
+ }
254
+ }
255
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id)
256
+ const msgId = await relayMessage(meJid, protocolMessage, {
257
+ additionalAttributes: {
258
+ category: 'peer',
259
+ // eslint-disable-next-line camelcase
260
+ push_priority: 'high_force',
261
+ },
262
+ })
263
+ return msgId
264
+ }
265
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
266
+ const patched = await patchMessageBeforeSending(message, jids)
267
+ const bytes = Utils_1.encodeWAMessage(patched)
268
+ let shouldIncludeDeviceIdentity = false
269
+ const nodes = await Promise.all(jids.map(async (jid) => {
270
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
271
+ if (type === 'pkmsg') {
272
+ shouldIncludeDeviceIdentity = true
273
+ }
274
+ const node = {
275
+ tag: 'to',
276
+ attrs: { jid },
277
+ content: [{
278
+ tag: 'enc',
279
+ attrs: {
280
+ v: '2',
281
+ type,
282
+ ...extraAttrs || {}
283
+ },
284
+ content: ciphertext
285
+ }]
286
+ }
287
+ return node
288
+ }))
289
+ return {
290
+ nodes,
291
+ shouldIncludeDeviceIdentity
292
+ }
293
+ }
294
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, additionalNodes, AI = false }) => {
295
+ const meId = authState.creds.me.id
296
+ let didPushAdditional = false
297
+ let shouldIncludeDeviceIdentity = false
298
+ const { user, server } = WABinary_1.jidDecode(jid)
299
+ const statusJid = 'status@broadcast'
300
+ const isGroup = server === 'g.us'
301
+ const isPrivate = server === 's.whatsapp.net'
302
+ const isNewsletter = server == 'newsletter'
303
+ const isStatus = jid === statusJid
304
+ const isLid = server === 'lid'
305
+ msgId = msgId || Utils_1.generateMessageID(authState.creds.me.id)
306
+ useUserDevicesCache = useUserDevicesCache !== false
307
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
308
+ const participants = []
309
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid
310
+ const binaryNodeContent = []
311
+ const devices = []
312
+ const meMsg = {
313
+ deviceSentMessage: {
314
+ destinationJid,
315
+ message
316
+ }
317
+ }
318
+ const extraAttrs = {}
319
+ if (participant) {
320
+ // when the retry request is not for a group
321
+ // only send to the specific device that asked for a retry
322
+ // otherwise the message is sent out to every device that should be a recipient
323
+ if (!isGroup && !isStatus) {
324
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' }
325
+ }
326
+ const { user, device } = WABinary_1.jidDecode(participant.jid)
327
+ devices.push({ user, device })
328
+ }
329
+ await authState.keys.transaction(async () => {
330
+ const mediaType = getMediaType(message)
331
+ if (mediaType) {
332
+ extraAttrs['mediatype'] = mediaType
333
+ }
334
+ if (Utils_1.normalizeMessageContent(message)?.pinInChatMessage || Utils_1.normalizeMessageContent(message)?.keepInChatMessage) {
335
+ extraAttrs['decrypt-fail'] = 'hide'
336
+ }
337
+ if (isGroup || isStatus) {
338
+ const [groupData, senderKeyMap] = await Promise.all([
339
+ (async () => {
340
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
341
+ if (groupData && Array.isArray(groupData?.participants)) {
342
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
343
+ }
344
+ else if (!isStatus) {
345
+ groupData = await groupMetadata(jid)
346
+ }
347
+ return groupData
348
+ })(),
349
+ (async () => {
350
+ if (!participant && !isStatus) {
351
+ const result = await authState.keys.get('sender-key-memory', [jid])
352
+ return result[jid] || {}
353
+ }
354
+ return {}
355
+ })()
356
+ ])
357
+ if (!participant) {
358
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
359
+ if (isStatus && statusJidList) {
360
+ participantsList.push(...statusJidList)
361
+ }
362
+ if (!isStatus) {
363
+ additionalAttributes = {
364
+ ...additionalAttributes,
365
+ addressing_mode: groupData?.addressingMode || 'pn'
366
+ }
367
+ }
368
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
369
+ devices.push(...additionalDevices)
370
+ }
371
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)))
372
+ const bytes = Utils_1.encodeWAMessage(patched)
373
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
374
+ group: destinationJid,
375
+ data: bytes,
376
+ meId,
377
+ })
378
+ const senderKeyJids = []
379
+ // ensure a connection is established with every device
380
+ for (const { user, device } of devices) {
381
+ const jid = WABinary_1.jidEncode(user, groupData?.addressingMode === 'lid' ? 'lid' : 's.whatsapp.net', device)
382
+ if (!senderKeyMap[jid] || !!participant) {
383
+ senderKeyJids.push(jid)
384
+ // store that this person has had the sender keys sent to them
385
+ senderKeyMap[jid] = true
386
+ }
387
+ }
388
+ // if there are some participants with whom the session has not been established
389
+ // if there are, we re-send the senderkey
390
+ if (senderKeyJids.length) {
391
+ logger.debug({ senderKeyJids }, 'sending new sender key')
392
+ const senderKeyMsg = {
393
+ senderKeyDistributionMessage: {
394
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
395
+ groupId: destinationJid
396
+ }
397
+ }
398
+ await assertSessions(senderKeyJids, false)
399
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
400
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
401
+ participants.push(...result.nodes)
402
+ }
403
+ binaryNodeContent.push({
404
+ tag: 'enc',
405
+ attrs: { v: '2', type: 'skmsg' },
406
+ content: ciphertext
407
+ })
408
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
409
+ }
410
+ else if (isNewsletter) {
411
+ // Message edit
412
+ if (message.protocolMessage?.editedMessage) {
413
+ msgId = message.protocolMessage.key?.id
414
+ message = message.protocolMessage.editedMessage
415
+ }
416
+ // Message delete
417
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
418
+ msgId = message.protocolMessage.key?.id
419
+ message = {}
420
+ }
421
+ const patched = await patchMessageBeforeSending(message, [])
422
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
423
+ binaryNodeContent.push({
424
+ tag: 'plaintext',
425
+ attrs: mediaType ? { mediatype: mediaType } : {},
426
+ content: bytes
427
+ })
428
+ }
429
+ else {
430
+ const { user: meUser } = WABinary_1.jidDecode(meId)
431
+ if (!participant) {
432
+ devices.push({ user })
433
+ if (user !== meUser) {
434
+ devices.push({ user: meUser })
435
+ }
436
+ if (additionalAttributes?.['category'] !== 'peer') {
437
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
438
+ devices.push(...additionalDevices)
439
+ }
440
+ }
441
+ const allJids = []
442
+ const meJids = []
443
+ const otherJids = []
444
+ for (const { user, device } of devices) {
445
+ const isMe = user === meUser
446
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
447
+ if (isMe) {
448
+ meJids.push(jid)
449
+ }
450
+ else {
451
+ otherJids.push(jid)
452
+ }
453
+ allJids.push(jid)
454
+ }
455
+ await assertSessions(allJids, false)
456
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
457
+ createParticipantNodes(meJids, meMsg, extraAttrs),
458
+ createParticipantNodes(otherJids, message, extraAttrs)
459
+ ])
460
+ participants.push(...meNodes)
461
+ participants.push(...otherNodes)
462
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
463
+ }
464
+ if (participants.length) {
465
+ if (additionalAttributes?.['category'] === 'peer') {
466
+ const peerNode = participants[0]?.content?.[0]
467
+ if (peerNode) {
468
+ binaryNodeContent.push(peerNode) // push only enc
469
+ }
470
+ }
471
+ else {
472
+ binaryNodeContent.push({
473
+ tag: 'participants',
474
+ attrs: {},
475
+ content: participants
476
+ })
477
+ }
478
+ }
479
+ const stanza = {
480
+ tag: 'message',
481
+ attrs: {
482
+ id: msgId,
483
+ type: isNewsletter ? getTypeMessage(message) : 'text',
484
+ ...(additionalAttributes || {})
485
+ },
486
+ content: binaryNodeContent
487
+ }
488
+ // if the participant to send to is explicitly specified (generally retry recp)
489
+ // ensure the message is only sent to that person
490
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
491
+ if (participant) {
492
+ if (WABinary_1.isJidGroup(destinationJid)) {
493
+ stanza.attrs.to = destinationJid
494
+ stanza.attrs.participant = participant.jid
495
+ }
496
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
497
+ stanza.attrs.to = participant.jid
498
+ stanza.attrs.recipient = destinationJid
499
+ }
500
+ else {
501
+ stanza.attrs.to = participant.jid
502
+ }
503
+ }
504
+ else {
505
+ stanza.attrs.to = destinationJid
506
+ }
507
+ if (shouldIncludeDeviceIdentity) {
508
+ stanza.content.push({
509
+ tag: 'device-identity',
510
+ attrs: {},
511
+ content: Utils_1.encodeSignedDeviceIdentity(authState.creds.account, true)
512
+ })
513
+ logger.debug({ jid }, 'adding device identity')
514
+ }
515
+ const messages = Utils_1.normalizeMessageContent(message)
516
+ const buttonType = getButtonType(messages)
517
+ if (!isNewsletter && buttonType) {
518
+ if (!stanza.content || !Array.isArray(stanza.content)) {
519
+ stanza.content = []
520
+ }
521
+ const buttonsNode = getButtonArgs(messages)
522
+ const filteredButtons = WABinary_1.getBinaryFilteredButtons(additionalNodes ? additionalNodes : [])
523
+ if (filteredButtons) {
524
+ stanza.content.push(...additionalNodes)
525
+ didPushAdditional = true
526
+ }
527
+ else {
528
+ stanza.content.push(buttonsNode)
529
+ }
530
+ }
531
+ if (AI && isPrivate) {
532
+ if (!stanza.content || !Array.isArray(stanza.content)) {
533
+ stanza.content = []
534
+ }
535
+ const botNode = {
536
+ tag: 'bot',
537
+ attrs: {
538
+ biz_bot: '1'
539
+ }
540
+ }
541
+ const filteredBizBot = WABinary_1.getBinaryFilteredBizBot(additionalNodes ? additionalNodes : [])
542
+ if (filteredBizBot) {
543
+ stanza.content.push(...additionalNodes)
544
+ didPushAdditional = true
545
+ }
546
+ else {
547
+ stanza.content.push(botNode)
548
+ }
549
+ }
550
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
551
+ if (!stanza.content || !Array.isArray(stanza.content)) {
552
+ stanza.content = []
553
+ }
554
+ stanza.content.push(...additionalNodes)
555
+ }
556
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`)
557
+ await sendNode(stanza)
558
+ })
559
+ return msgId
560
+ }
561
+ const getTypeMessage = (msg) => {
562
+ const message = Utils_1.normalizeMessageContent(msg)
563
+ if (message.reactionMessage) {
564
+ return 'reaction'
565
+ }
566
+ else if (getMediaType(message)) {
567
+ return 'media'
568
+ }
569
+ else {
570
+ return 'text'
571
+ }
572
+ }
573
+ const getMediaType = (message) => {
574
+ if (message.imageMessage) {
575
+ return 'image'
576
+ }
577
+ else if (message.stickerMessage) {
578
+ return message.stickerMessage.isLottie ? '1p_sticker' : 'sticker'
579
+ }
580
+ else if (message.videoMessage) {
581
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
582
+ }
583
+ else if (message.audioMessage) {
584
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
585
+ }
586
+ else if (message.ptvMessage) {
587
+ return 'ptv'
588
+ }
589
+ else if (message.contactMessage) {
590
+ return 'vcard'
591
+ }
592
+ else if (message.documentMessage) {
593
+ return 'document'
594
+ }
595
+ else if (message.contactsArrayMessage) {
596
+ return 'contact_array'
597
+ }
598
+ else if (message.liveLocationMessage) {
599
+ return 'livelocation'
600
+ }
601
+ else if (message.stickerMessage) {
602
+ return 'sticker'
603
+ }
604
+ else if (message.listMessage) {
605
+ return 'list'
606
+ }
607
+ else if (message.listResponseMessage) {
608
+ return 'list_response'
609
+ }
610
+ else if (message.buttonsResponseMessage) {
611
+ return 'buttons_response'
612
+ }
613
+ else if (message.orderMessage) {
614
+ return 'order'
615
+ }
616
+ else if (message.productMessage) {
617
+ return 'product'
618
+ }
619
+ else if (message.interactiveResponseMessage) {
620
+ return 'native_flow_response'
621
+ }
622
+ else if (message.groupInviteMessage) {
623
+ return 'url'
624
+ }
625
+ else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
626
+ return 'cataloglink'
627
+ }
628
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
629
+ return 'productlink'
630
+ }
631
+ }
632
+ const getButtonType = (message) => {
633
+ if (message.listMessage) {
634
+ return 'list'
635
+ }
636
+ else if (message.buttonsMessage) {
637
+ return 'buttons'
638
+ }
639
+ else if(message.interactiveMessage?.nativeFlowMessage) {
640
+ return 'native_flow'
641
+ }
642
+ }
643
+ const getButtonArgs = (message) => {
644
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage
645
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name
646
+ const nativeFlowSpecials = [
647
+ 'mpm', 'cta_catalog', 'send_location',
648
+ 'call_permission_request', 'wa_payment_transaction_details',
649
+ 'automated_greeting_message_view_catalog'
650
+ ]
651
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
652
+ return {
653
+ tag: 'biz',
654
+ attrs: {
655
+ native_flow_name: firstButtonName
656
+ }
657
+ }
658
+ } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
659
+ // Only works for WhatsApp Original, not WhatsApp Business
660
+ return {
661
+ tag: 'biz',
662
+ attrs: {},
663
+ content: [{
664
+ tag: 'interactive',
665
+ attrs: {
666
+ type: 'native_flow',
667
+ v: '1'
668
+ },
669
+ content: [{
670
+ tag: 'native_flow',
671
+ attrs: {
672
+ v: '2',
673
+ name: firstButtonName
674
+ }
675
+ }]
676
+ }]
677
+ }
678
+ } else if (nativeFlow || message.buttonsMessage) {
679
+ // It works for whatsapp original and whatsapp business
680
+ return {
681
+ tag: 'biz',
682
+ attrs: {},
683
+ content: [{
684
+ tag: 'interactive',
685
+ attrs: {
686
+ type: 'native_flow',
687
+ v: '1'
688
+ },
689
+ content: [{
690
+ tag: 'native_flow',
691
+ attrs: {
692
+ v: '9',
693
+ name: 'mixed'
694
+ }
695
+ }]
696
+ }]
697
+ }
698
+ } else if (message.listMessage) {
699
+ return {
700
+ tag: 'biz',
701
+ attrs: {},
702
+ content: [{
703
+ tag: 'list',
704
+ attrs: {
705
+ v: '2',
706
+ type: 'product_list'
707
+ }
708
+ }]
709
+ }
710
+ } else {
711
+ return {
712
+ tag: 'biz',
713
+ attrs: {}
714
+ }
715
+ }
716
+ }
717
+ const getPrivacyTokens = async (jids) => {
718
+ const t = Utils_1.unixTimestampSeconds().toString()
719
+ const result = await query({
720
+ tag: 'iq',
721
+ attrs: {
722
+ to: WABinary_1.S_WHATSAPP_NET,
723
+ type: 'set',
724
+ xmlns: 'privacy'
725
+ },
726
+ content: [
727
+ {
728
+ tag: 'tokens',
729
+ attrs: {},
730
+ content: jids.map(jid => ({
731
+ tag: 'token',
732
+ attrs: {
733
+ jid: WABinary_1.jidNormalizedUser(jid),
734
+ t,
735
+ type: 'trusted_contact'
736
+ }
737
+ }))
738
+ }
739
+ ]
740
+ })
741
+ return result
742
+ }
743
+ const waUploadToServer = Utils_1.getWAUploadToServer(config, refreshMediaConn)
744
+ const waitForMsgMediaUpdate = Utils_1.bindWaitForEvent(ev, 'messages.media-update')
745
+ return {
746
+ ...sock,
747
+ getPrivacyTokens,
748
+ assertSessions,
749
+ relayMessage,
750
+ sendReceipt,
751
+ sendReceipts,
752
+ readMessages,
753
+ profilePictureUrl,
754
+ getUSyncDevices,
755
+ refreshMediaConn,
756
+ waUploadToServer,
757
+ fetchPrivacySettings,
758
+ createParticipantNodes,
759
+ sendPeerDataOperationMessage,
760
+ updateMediaMessage: async (message) => {
761
+ const content = Utils_1.assertMediaContent(message.message)
762
+ const mediaKey = content.mediaKey
763
+ const meId = authState.creds.me.id
764
+ const node = await Utils_1.encryptMediaRetryRequest(message.key, mediaKey, meId)
765
+ let error = undefined
766
+ await Promise.all([
767
+ sendNode(node),
768
+ waitForMsgMediaUpdate(async (update) => {
769
+ const result = update.find(c => c.key.id === message.key.id)
770
+ if (result) {
771
+ if (result.error) {
772
+ error = result.error
773
+ }
774
+ else {
775
+ try {
776
+ const media = await Utils_1.decryptMediaRetryData(result.media, mediaKey, result.key.id)
777
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
778
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result]
779
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: Utils_1.getStatusCodeForMediaRetry(media.result) || 404 })
780
+ }
781
+ content.directPath = media.directPath
782
+ content.url = Utils_1.getUrlFromDirectPath(content.directPath)
783
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
784
+ }
785
+ catch (err) {
786
+ error = err
787
+ }
788
+ }
789
+ return true
790
+ }
791
+ })
792
+ ])
793
+ if (error) {
794
+ throw error
795
+ }
796
+ ev.emit('messages.update', [
797
+ { key: message.key, update: { message: message.message } }
798
+ ])
799
+ return message
800
+ },
801
+ sendStatusMentions: async (jid, content) => {
802
+ const media = await Utils_1.generateWAMessage(WABinary_1.STORIES_JID, content, {
803
+ upload: await waUploadToServer,
804
+ backgroundColor: "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0"),
805
+ font: content.text ? Math.floor(Math.random() * 9) : null
806
+ })
807
+ const additionalNodes = [{
808
+ tag: 'meta',
809
+ attrs: {},
810
+ content: [{
811
+ tag: 'mentioned_users',
812
+ attrs: {},
813
+ content: [{
814
+ tag: 'to',
815
+ attrs: { jid },
816
+ content: undefined
817
+ }]
818
+ }]
819
+ }]
820
+ let Private = WABinary_1.isJidUser(jid)
821
+ let statusJid = Private ? [jid] : (await groupMetadata(jid)).participants.map((num) => num.id)
822
+ await relayMessage(WABinary_1.STORIES_JID, media.message, {
823
+ messageId: media.key.id,
824
+ statusJidList: statusJid,
825
+ additionalNodes
826
+ })
827
+ let type = Private ? 'statusMentionMessage' : 'groupStatusMentionMessage'
828
+ let msg = await Utils_1.generateWAMessageFromContent(jid, {
829
+ [type]: {
830
+ message: {
831
+ protocolMessage: {
832
+ key: media.key,
833
+ type: 25
834
+ }
835
+ }
836
+ }
837
+ }, {})
838
+ await relayMessage(jid, msg.message, {})
839
+ return media
840
+ },
841
+ sendAlbumMessage: async (jid, medias, options = {}) => {
842
+ const userJid = authState.creds.me.id
843
+ for (const media of medias) {
844
+ if (!media.image && !media.video)
845
+ throw new TypeError(`medias[i] must have image or video property`)
846
+ }
847
+ const time = options.delay || 500
848
+ delete options.delay
849
+ const album = await Utils_1.generateWAMessageFromContent(jid, {
850
+ albumMessage: {
851
+ expectedImageCount: medias.filter(media => media.image).length,
852
+ expectedVideoCount: medias.filter(media => media.video).length,
853
+ ...options
854
+ }
855
+ }, { userJid, ...options })
856
+ await relayMessage(jid, album.message, { messageId: album.key.id })
857
+ let mediaHandle
858
+ let msg
859
+ for (const i in medias) {
860
+ const media = medias[i]
861
+ if (media.image) {
862
+ msg = await Utils_1.generateWAMessage(jid, {
863
+ image: media.image,
864
+ ...media,
865
+ ...options
866
+ }, {
867
+ userJid,
868
+ upload: async (encFilePath, opts) => {
869
+ const up = await waUploadToServer(encFilePath, { ...opts, newsletter: WABinary_1.isJidNewsletter(jid) })
870
+ mediaHandle = up.handle
871
+ return up
872
+ },
873
+ ...options
874
+ })
875
+ }
876
+ else if (media.video) {
877
+ msg = await Utils_1.generateWAMessage(jid, {
878
+ video: media.video,
879
+ ...media,
880
+ ...options
881
+ }, {
882
+ userJid,
883
+ upload: async (encFilePath, opts) => {
884
+ const up = await waUploadToServer(encFilePath, { ...opts, newsletter: WABinary_1.isJidNewsletter(jid) })
885
+ mediaHandle = up.handle
886
+ return up
887
+ },
888
+ ...options,
889
+ })
890
+ }
891
+ if (msg) {
892
+ msg.message.messageContextInfo = {
893
+ messageSecret: crypto_1.randomBytes(32),
894
+ messageAssociation: {
895
+ associationType: 1,
896
+ parentMessageKey: album.key
897
+ }
898
+ }
899
+ }
900
+ await relayMessage(jid, msg.message, { messageId: msg.key.id })
901
+ await Utils_1.delay(time)
902
+ }
903
+ return album
904
+ },
905
+ sendMessage: async (jid, content, options = {}) => {
906
+ const userJid = authState.creds.me.id
907
+ if (typeof content === 'object' &&
908
+ 'disappearingMessagesInChat' in content &&
909
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
910
+ WABinary_1.isJidGroup(jid)) {
911
+ const { disappearingMessagesInChat } = content
912
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
913
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
914
+ disappearingMessagesInChat
915
+ await groupToggleEphemeral(jid, value)
916
+ }
917
+ else {
918
+ let mediaHandle
919
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
920
+ logger,
921
+ userJid,
922
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
923
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
924
+ fetchOpts: {
925
+ timeout: 3000,
926
+ ...axiosOptions || {}
927
+ },
928
+ logger,
929
+ uploadImage: generateHighQualityLinkPreview
930
+ ? waUploadToServer
931
+ : undefined
932
+ }),
933
+ getProfilePicUrl: profilePictureUrl,
934
+ upload: async (encFilePath, opts) => {
935
+ const up = await waUploadToServer(encFilePath, { ...opts, newsletter: WABinary_1.isJidNewsletter(jid) })
936
+ mediaHandle = up.handle
937
+ return up
938
+ },
939
+ mediaCache: config.mediaCache,
940
+ options: config.options,
941
+ messageId: Utils_1.generateMessageID(userJid),
942
+ ...options,
943
+ })
944
+ const isPin = 'pin' in content && !!content.pin
945
+ const isEdit = 'edit' in content && !!content.edit
946
+ const isDelete = 'delete' in content && !!content.delete
947
+ const additionalAttributes = {}
948
+ if (isDelete) {
949
+ // if the chat is a group, and I am not the author, then delete the message as an admin
950
+ if (WABinary_1.isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe || WABinary_1.isJidNewsletter(jid)) {
951
+ additionalAttributes.edit = '8'
952
+ }
953
+ else {
954
+ additionalAttributes.edit = '7'
955
+ }
956
+ }
957
+ else if (isEdit) {
958
+ additionalAttributes.edit = WABinary_1.isJidNewsletter(jid) ? '3' : '1'
959
+ }
960
+ else if (isPin) {
961
+ additionalAttributes.edit = '2'
962
+ }
963
+ if (mediaHandle) {
964
+ additionalAttributes['media_id'] = mediaHandle
965
+ }
966
+ if ('cachedGroupMetadata' in options) {
967
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.')
968
+ }
969
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes: options.additionalNodes })
970
+ if (config.emitOwnEvents) {
971
+ process.nextTick(() => {
972
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')))
973
+ })
974
+ }
975
+ return fullMsg
976
+ }
977
+ }
978
+ }
979
+ }
1292
980
  module.exports = {
1293
- makeMessagesSocket
981
+ makeMessagesSocket
1294
982
  }