sanka-baileyss 1.9.1 → 1.9.2

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