@realvare/based 2.5.2 → 2.5.6

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,901 +1,1406 @@
1
- "use strict";
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
- exports.makeMessagesSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
- const crypto_1 = require("crypto");
10
- const WAProto_1 = require("../../WAProto");
11
- const Defaults_1 = require("../Defaults");
12
- const Utils_1 = require("../Utils");
13
- const retry_1 = require("../Utils/retry");
14
- const link_preview_1 = require("../Utils/link-preview");
15
- const WABinary_1 = require("../WABinary");
16
- const WAUSync_1 = require("../WAUSync");
17
- const newsletter_1 = require("./newsletter");
18
- const makeMessagesSocket = (config) => {
19
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
20
- const sock = (0, newsletter_1.makeNewsletterSocket)(config);
21
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
22
- const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
23
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
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
- /** Fetch all the devices we've to send a message to */
115
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
116
- var _a;
117
- const deviceResults = [];
118
- if (!useCache) {
119
- logger.debug('not using cache for devices');
120
- }
121
- const toFetch = [];
122
- jids = Array.from(new Set(jids));
123
- for (let jid of jids) {
124
- const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
125
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
126
- if (useCache) {
127
- const devices = userDevicesCache.get(user);
128
- if (devices) {
129
- deviceResults.push(...devices);
130
- logger.trace({ user }, 'using cache for devices');
131
- }
132
- else {
133
- toFetch.push(jid);
134
- }
135
- }
136
- else {
137
- toFetch.push(jid);
138
- }
139
- }
140
- if (!toFetch.length) {
141
- return deviceResults;
142
- }
143
- const query = new WAUSync_1.USyncQuery()
144
- .withContext('message')
145
- .withDeviceProtocol();
146
- for (const jid of toFetch) {
147
- query.withUser(new WAUSync_1.USyncUser().withId(jid));
148
- }
149
- const result = await sock.executeUSyncQuery(query);
150
- if (result) {
151
- const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
152
- const deviceMap = {};
153
- for (const item of extracted) {
154
- deviceMap[item.user] = deviceMap[item.user] || [];
155
- deviceMap[item.user].push(item);
156
- deviceResults.push(item);
157
- }
158
- for (const key in deviceMap) {
159
- userDevicesCache.set(key, deviceMap[key]);
160
- }
161
- }
162
- return deviceResults;
163
- };
164
- const assertSessions = async (jids, force) => {
165
- let didFetchNewSession = false;
166
- let jidsRequiringFetch = [];
167
- if (force) {
168
- jidsRequiringFetch = jids;
169
- }
170
- else {
171
- const addrs = jids.map(jid => (signalRepository
172
- .jidToSignalProtocolAddress(jid)));
173
- const sessions = await authState.keys.get('session', addrs);
174
- for (const jid of jids) {
175
- const signalId = signalRepository
176
- .jidToSignalProtocolAddress(jid);
177
- if (!sessions[signalId]) {
178
- jidsRequiringFetch.push(jid);
179
- }
180
- }
181
- }
182
- if (jidsRequiringFetch.length) {
183
- logger.debug({ jidsRequiringFetch }, 'fetching sessions');
184
- const result = await query({
185
- tag: 'iq',
186
- attrs: {
187
- xmlns: 'encrypt',
188
- type: 'get',
189
- to: WABinary_1.S_WHATSAPP_NET,
190
- },
191
- content: [
192
- {
193
- tag: 'key',
194
- attrs: {},
195
- content: jidsRequiringFetch.map(jid => ({
196
- tag: 'user',
197
- attrs: { jid },
198
- }))
199
- }
200
- ]
201
- });
202
- await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
203
- didFetchNewSession = true;
204
- }
205
- return didFetchNewSession;
206
- };
207
- const sendPeerDataOperationMessage = async (pdoMessage) => {
208
- var _a;
209
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
210
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
211
- throw new boom_1.Boom('Not authenticated');
212
- }
213
- const protocolMessage = {
214
- protocolMessage: {
215
- peerDataOperationRequestMessage: pdoMessage,
216
- type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
217
- }
218
- };
219
- const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
220
- const msgId = await relayMessage(meJid, protocolMessage, {
221
- additionalAttributes: {
222
- category: 'peer',
223
- // eslint-disable-next-line camelcase
224
- push_priority: 'high_force',
225
- },
226
- });
227
- return msgId;
228
- };
229
- const createParticipantNodes = async (jids, message, extraAttrs) => {
230
- let patched = await patchMessageBeforeSending(message, jids);
231
- if (!Array.isArray(patched)) {
232
- patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched];
233
- }
234
- let shouldIncludeDeviceIdentity = false;
235
- const nodes = await Promise.all(patched.map(async (patchedMessageWithJid) => {
236
- const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid;
237
- if (!jid) {
238
- return {};
239
- }
240
- const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
241
- const { type, ciphertext } = await signalRepository
242
- .encryptMessage({ jid, data: bytes });
243
- if (type === 'pkmsg') {
244
- shouldIncludeDeviceIdentity = true;
245
- }
246
- const node = {
247
- tag: 'to',
248
- attrs: { jid },
249
- content: [{
250
- tag: 'enc',
251
- attrs: {
252
- v: '2',
253
- type,
254
- ...extraAttrs || {}
255
- },
256
- content: ciphertext
257
- }]
258
- };
259
- return node;
260
- }));
261
- return { nodes, shouldIncludeDeviceIdentity };
262
- };
263
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
264
- var _a;
265
- const meId = authState.creds.me.id;
266
- let shouldIncludeDeviceIdentity = false;
267
- const { user, server } = (0, WABinary_1.jidDecode)(jid);
268
- const statusJid = 'status@broadcast';
269
- const isGroup = server === 'g.us';
270
- const isNewsletter = server === 'newsletter';
271
- const isStatus = jid === statusJid;
272
- const isLid = server === 'lid';
273
- msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
274
- useUserDevicesCache = useUserDevicesCache !== false;
275
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
276
- const participants = [];
277
- const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
278
- const binaryNodeContent = [];
279
- const devices = [];
280
- const meMsg = {
281
- deviceSentMessage: {
282
- destinationJid,
283
- message
284
- },
285
- messageContextInfo: message.messageContextInfo
286
- };
287
- const extraAttrs = {};
288
- if (participant) {
289
- // when the retry request is not for a group
290
- // only send to the specific device that asked for a retry
291
- // otherwise the message is sent out to every device that should be a recipient
292
- if (!isGroup && !isStatus) {
293
- additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
294
- }
295
- const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
296
- devices.push({ user, device });
297
- }
298
- await authState.keys.transaction(async () => {
299
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
300
- const mediaType = getMediaType(message);
301
- if (mediaType) {
302
- extraAttrs['mediatype'] = mediaType;
303
- }
304
- if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
305
- extraAttrs['decrypt-fail'] = 'hide';
306
- }
307
- if (isGroup || isStatus) {
308
- const [groupData, senderKeyMap] = await Promise.all([
309
- (async () => {
310
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
311
- if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
312
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
313
- }
314
- else if (!isStatus) {
315
- groupData = await groupMetadata(jid);
316
- }
317
- return groupData;
318
- })(),
319
- (async () => {
320
- if (!participant && !isStatus) {
321
- const result = await authState.keys.get('sender-key-memory', [jid]);
322
- return result[jid] || {};
323
- }
324
- return {};
325
- })()
326
- ]);
327
- if (!participant) {
328
- const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
329
- if (isStatus && statusJidList) {
330
- participantsList.push(...statusJidList);
331
- }
332
- if (!isStatus) {
333
- additionalAttributes = {
334
- ...additionalAttributes,
335
- // eslint-disable-next-line camelcase
336
- addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
337
- };
338
- }
339
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
340
- devices.push(...additionalDevices);
341
- }
342
- const patched = await patchMessageBeforeSending(message);
343
- if (Array.isArray(patched)) {
344
- throw new boom_1.Boom('Per-jid patching is not supported in groups');
345
- }
346
- const bytes = (0, Utils_1.encodeWAMessage)(patched);
347
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
348
- group: destinationJid,
349
- data: bytes,
350
- meId,
351
- });
352
- const senderKeyJids = [];
353
- // ensure a connection is established with every device
354
- for (const { user, device } of devices) {
355
- const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
356
- if (!senderKeyMap[jid] || !!participant) {
357
- senderKeyJids.push(jid);
358
- // store that this person has had the sender keys sent to them
359
- senderKeyMap[jid] = true;
360
- }
361
- }
362
- // if there are some participants with whom the session has not been established
363
- // if there are, we re-send the senderkey
364
- if (senderKeyJids.length) {
365
- logger.debug({ senderKeyJids }, 'sending new sender key');
366
- const senderKeyMsg = {
367
- senderKeyDistributionMessage: {
368
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
369
- groupId: destinationJid
370
- }
371
- };
372
- await assertSessions(senderKeyJids, false);
373
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
374
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
375
- participants.push(...result.nodes);
376
- }
377
- binaryNodeContent.push({
378
- tag: 'enc',
379
- attrs: { v: '2', type: 'skmsg' },
380
- content: ciphertext
381
- });
382
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
383
- }
384
- else if (isNewsletter) {
385
- // Message edit
386
- if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
387
- msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
388
- message = message.protocolMessage.editedMessage;
389
- }
390
- // Message delete
391
- if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
392
- msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
393
- message = {};
394
- }
395
- const patched = await patchMessageBeforeSending(message, []);
396
- if (Array.isArray(patched)) {
397
- throw new boom_1.Boom('Per-jid patching is not supported in channel');
398
- }
399
- const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
400
- binaryNodeContent.push({
401
- tag: 'plaintext',
402
- attrs: mediaType ? { mediatype: mediaType } : {},
403
- content: bytes
404
- });
405
- }
406
- else {
407
- const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
408
- if (!participant) {
409
- devices.push({ user });
410
- if (user !== meUser) {
411
- devices.push({ user: meUser });
412
- }
413
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
414
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
415
- devices.push(...additionalDevices);
416
- }
417
- }
418
- const allJids = [];
419
- const meJids = [];
420
- const otherJids = [];
421
- for (const { user, device } of devices) {
422
- const isMe = user === meUser;
423
- const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_g = (_f = authState.creds) === null || _f === void 0 ? void 0 : _f.me) === null || _g === void 0 ? void 0 : _g.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
424
- if (isMe) {
425
- meJids.push(jid);
426
- }
427
- else {
428
- otherJids.push(jid);
429
- }
430
- allJids.push(jid);
431
- }
432
- await assertSessions(allJids, false);
433
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
434
- createParticipantNodes(meJids, meMsg, extraAttrs),
435
- createParticipantNodes(otherJids, message, extraAttrs)
436
- ]);
437
- participants.push(...meNodes);
438
- participants.push(...otherNodes);
439
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
440
- }
441
- if (participants.length) {
442
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
443
- const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
444
- if (peerNode) {
445
- binaryNodeContent.push(peerNode); // push only enc
446
- }
447
- }
448
- else {
449
- binaryNodeContent.push({
450
- tag: 'participants',
451
- attrs: {},
452
- content: participants
453
- });
454
- }
455
- }
456
- const stanza = {
457
- tag: 'message',
458
- attrs: {
459
- id: msgId,
460
- type: isNewsletter ? getTypeMessage(message) : 'text',
461
- ...(additionalAttributes || {})
462
- },
463
- content: binaryNodeContent
464
- };
465
- // if the participant to send to is explicitly specified (generally retry recp)
466
- // ensure the message is only sent to that person
467
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
468
- if (participant) {
469
- if ((0, WABinary_1.isJidGroup)(destinationJid)) {
470
- stanza.attrs.to = destinationJid;
471
- stanza.attrs.participant = participant.jid;
472
- }
473
- else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
474
- stanza.attrs.to = participant.jid;
475
- stanza.attrs.recipient = destinationJid;
476
- }
477
- else {
478
- stanza.attrs.to = participant.jid;
479
- }
480
- }
481
- else {
482
- stanza.attrs.to = destinationJid;
483
- }
484
- if (shouldIncludeDeviceIdentity) {
485
- stanza.content.push({
486
- tag: 'device-identity',
487
- attrs: {},
488
- content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
489
- });
490
- logger.debug({ jid }, 'adding device identity');
491
- }
492
- if (additionalNodes && additionalNodes.length > 0) {
493
- stanza.content.push(...additionalNodes);
494
- }
495
- const content = (0, Utils_1.normalizeMessageContent)(message);
496
- const contentType = (0, Utils_1.getContentType)(content);
497
- if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
498
- contentType === 'buttonsMessage' ||
499
- contentType === 'listMessage')) {
500
- const bizNode = { tag: 'biz', attrs: {} };
501
- if ((((_l = (_k = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _k === void 0 ? void 0 : _k.message) === null || _l === void 0 ? void 0 : _l.interactiveMessage) || ((_o = (_m = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _m === void 0 ? void 0 : _m.message) === null || _o === void 0 ? void 0 : _o.interactiveMessage) || ((_q = (_p = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _p === void 0 ? void 0 : _p.message) === null || _q === void 0 ? void 0 : _q.interactiveMessage) || (message === null || message === void 0 ? void 0 : message.interactiveMessage)) || (((_s = (_r = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _r === void 0 ? void 0 : _r.message) === null || _s === void 0 ? void 0 : _s.buttonsMessage) || ((_u = (_t = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _t === void 0 ? void 0 : _t.message) === null || _u === void 0 ? void 0 : _u.buttonsMessage) || ((_w = (_v = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _v === void 0 ? void 0 : _v.message) === null || _w === void 0 ? void 0 : _w.buttonsMessage) || (message === null || message === void 0 ? void 0 : message.buttonsMessage))) {
502
- bizNode.content = [{
503
- tag: 'interactive',
504
- attrs: {
505
- type: 'native_flow',
506
- v: '1'
507
- },
508
- content: [{
509
- tag: 'native_flow',
510
- attrs: { v: '9', name: 'mixed' }
511
- }]
512
- }];
513
- }
514
- else if (message === null || message === void 0 ? void 0 : message.listMessage) {
515
- // list message only support in private chat
516
- bizNode.content = [{
517
- tag: 'list',
518
- attrs: {
519
- type: 'product_list',
520
- v: '2'
521
- }
522
- }];
523
- }
524
- else if (message?.interactiveMessage?.carouselMessage ||
525
- message?.viewOnceMessage?.message?.interactiveMessage?.carouselMessage ||
526
- message?.viewOnceMessageV2?.message?.interactiveMessage?.carouselMessage ||
527
- message?.viewOnceMessageV2Extension?.message?.interactiveMessage?.carouselMessage) {
528
- bizNode.content = [{
529
- tag: 'interactive',
530
- attrs: {
531
- type: 'carousel',
532
- v: '1'
533
- },
534
- content: [{
535
- tag: 'carousel',
536
- attrs: { v: '1' }
537
- }]
538
- }];
539
- }
540
- stanza.content.push(bizNode);
541
- }
542
- logger.debug({ msgId }, `sending message to ${participants.length} devices`);
543
- await (0, retry_1.retryWithBackoff)(({ signal }) => sendNode(stanza, { signal }), {
544
- retries: 3,
545
- baseMs: 300,
546
- maxMs: 4000,
547
- jitter: true,
548
- timeoutPerAttemptMs: 5000,
549
- shouldRetry: (err) => {
550
- const status = err?.output?.statusCode || err?.statusCode;
551
- // retry on transient failures
552
- return !status || (status >= 500 || status === 408 || status === 429);
553
- },
554
- onRetry: (err, n) => logger?.warn?.({ err, attempt: n }, 'retrying sendNode')
555
- });
556
- });
557
- return msgId;
558
- };
559
- const getTypeMessage = (msg) => {
560
- if (msg.viewOnceMessage) {
561
- return getTypeMessage(msg.viewOnceMessage.message);
562
- }
563
- else if (msg.viewOnceMessageV2) {
564
- return getTypeMessage(msg.viewOnceMessageV2.message);
565
- }
566
- else if (msg.viewOnceMessageV2Extension) {
567
- return getTypeMessage(msg.viewOnceMessageV2Extension.message);
568
- }
569
- else if (msg.ephemeralMessage) {
570
- return getTypeMessage(msg.ephemeralMessage.message);
571
- }
572
- else if (msg.documentWithCaptionMessage) {
573
- return getTypeMessage(msg.documentWithCaptionMessage.message);
574
- }
575
- else if (msg.reactionMessage) {
576
- return 'reaction';
577
- }
578
- else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
579
- return 'poll';
580
- }
581
- else if (getMediaType(msg)) {
582
- return 'media';
583
- }
584
- else {
585
- return 'text';
586
- }
587
- };
588
- const getMediaType = (message) => {
589
- if (message.imageMessage) {
590
- return 'image';
591
- }
592
- else if (message.videoMessage) {
593
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
594
- }
595
- else if (message.audioMessage) {
596
- return message.audioMessage.ptt ? 'ptt' : 'audio';
597
- }
598
- else if (message.contactMessage) {
599
- return 'vcard';
600
- }
601
- else if (message.documentMessage) {
602
- return 'document';
603
- }
604
- else if (message.contactsArrayMessage) {
605
- return 'contact_array';
606
- }
607
- else if (message.liveLocationMessage) {
608
- return 'livelocation';
609
- }
610
- else if (message.stickerMessage) {
611
- return 'sticker';
612
- }
613
- else if (message.listMessage) {
614
- return 'list';
615
- }
616
- else if (message.listResponseMessage) {
617
- return 'list_response';
618
- }
619
- else if (message.buttonsResponseMessage) {
620
- return 'buttons_response';
621
- }
622
- else if (message.orderMessage) {
623
- return 'order';
624
- }
625
- else if (message.productMessage) {
626
- return 'product';
627
- }
628
- else if (message.interactiveResponseMessage) {
629
- return 'native_flow_response';
630
- }
631
- else if (message.groupInviteMessage) {
632
- return 'url';
633
- }
634
- };
635
- const getPrivacyTokens = async (jids) => {
636
- const t = (0, Utils_1.unixTimestampSeconds)().toString();
637
- const result = await query({
638
- tag: 'iq',
639
- attrs: {
640
- to: WABinary_1.S_WHATSAPP_NET,
641
- type: 'set',
642
- xmlns: 'privacy'
643
- },
644
- content: [
645
- {
646
- tag: 'tokens',
647
- attrs: {},
648
- content: jids.map(jid => ({
649
- tag: 'token',
650
- attrs: {
651
- jid: (0, WABinary_1.jidNormalizedUser)(jid),
652
- t,
653
- type: 'trusted_contact'
654
- }
655
- }))
656
- }
657
- ]
658
- });
659
- return result;
660
- };
661
- const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
662
- const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
663
- return {
664
- ...sock,
665
- getPrivacyTokens,
666
- assertSessions,
667
- relayMessage,
668
- sendReceipt,
669
- sendReceipts,
670
- readMessages,
671
- refreshMediaConn,
672
- waUploadToServer,
673
- fetchPrivacySettings,
674
- getUSyncDevices,
675
- createParticipantNodes,
676
- sendPeerDataOperationMessage,
677
- updateMediaMessage: async (message) => {
678
- const content = (0, Utils_1.assertMediaContent)(message.message);
679
- const mediaKey = content.mediaKey;
680
- const meId = authState.creds.me.id;
681
- const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
682
- let error = undefined;
683
- await Promise.all([
684
- sendNode(node),
685
- waitForMsgMediaUpdate(async (update) => {
686
- const result = update.find(c => c.key.id === message.key.id);
687
- if (result) {
688
- if (result.error) {
689
- error = result.error;
690
- }
691
- else {
692
- try {
693
- const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
694
- if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
695
- const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
696
- throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
697
- }
698
- content.directPath = media.directPath;
699
- content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
700
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
701
- }
702
- catch (err) {
703
- error = err;
704
- }
705
- }
706
- return true;
707
- }
708
- })
709
- ]);
710
- if (error) {
711
- throw error;
712
- }
713
- ev.emit('messages.update', [
714
- { key: message.key, update: { message: message.message } }
715
- ]);
716
- return message;
717
- },
718
- sendMessage: async (jid, content, options = {}) => {
719
- var _a, _b, _c;
720
- const userJid = authState.creds.me.id;
721
- if (!options.ephemeralExpiration) {
722
- if ((0, WABinary_1.isJidGroup)(jid)) {
723
- const groups = await sock.groupQuery(jid, 'get', [{
724
- tag: 'query',
725
- attrs: {
726
- request: 'interactive'
727
- }
728
- }]);
729
- const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
730
- const expiration = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(metadata, 'ephemeral')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.expiration) || 0;
731
- options.ephemeralExpiration = expiration;
732
- }
733
- }
734
- if (typeof content === 'object' &&
735
- 'disappearingMessagesInChat' in content &&
736
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
737
- (0, WABinary_1.isJidGroup)(jid)) {
738
- const { disappearingMessagesInChat } = content;
739
- const value = typeof disappearingMessagesInChat === 'boolean' ?
740
- (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
741
- disappearingMessagesInChat;
742
- await groupToggleEphemeral(jid, value);
743
- }
744
- if (typeof content === 'object' && 'album' in content && content.album) {
745
- const { album, caption } = content;
746
- if (caption && !album[0].caption) {
747
- album[0].caption = caption;
748
- }
749
- let mediaHandle;
750
- let mediaMsg;
751
- const albumMsg = (0, Utils_1.generateWAMessageFromContent)(jid, {
752
- albumMessage: {
753
- expectedImageCount: album.filter(item => 'image' in item).length,
754
- expectedVideoCount: album.filter(item => 'video' in item).length
755
- }
756
- }, { userJid, ...options });
757
- await relayMessage(jid, albumMsg.message, {
758
- messageId: albumMsg.key.id
759
- });
760
- for (const i in album) {
761
- const media = album[i];
762
- if ('image' in media) {
763
- mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
764
- image: media.image,
765
- ...(media.caption ? { caption: media.caption } : {}),
766
- ...options
767
- }, {
768
- userJid,
769
- upload: async (readStream, opts) => {
770
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
771
- mediaHandle = up.handle;
772
- return up;
773
- },
774
- ...options,
775
- });
776
- }
777
- else if ('video' in media) {
778
- mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
779
- video: media.video,
780
- ...(media.caption ? { caption: media.caption } : {}),
781
- ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
782
- ...options
783
- }, {
784
- userJid,
785
- upload: async (readStream, opts) => {
786
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
787
- mediaHandle = up.handle;
788
- return up;
789
- },
790
- ...options,
791
- });
792
- }
793
- if (mediaMsg) {
794
- mediaMsg.message.messageContextInfo = {
795
- messageSecret: (0, crypto_1.randomBytes)(32),
796
- messageAssociation: {
797
- associationType: 1,
798
- parentMessageKey: albumMsg.key
799
- }
800
- };
801
- }
802
- await relayMessage(jid, mediaMsg.message, {
803
- messageId: mediaMsg.key.id
804
- });
805
- await new Promise(resolve => setTimeout(resolve, 800));
806
- }
807
- return albumMsg;
808
- }
809
- else {
810
- let mediaHandle;
811
- const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
812
- logger,
813
- userJid,
814
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
815
- thumbnailWidth: linkPreviewImageThumbnailWidth,
816
- fetchOpts: {
817
- timeout: 3000,
818
- ...axiosOptions || {}
819
- },
820
- logger,
821
- uploadImage: generateHighQualityLinkPreview
822
- ? waUploadToServer
823
- : undefined
824
- }),
825
- getProfilePicUrl: sock.profilePictureUrl,
826
- upload: async (readStream, opts) => {
827
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
828
- mediaHandle = up.handle;
829
- return up;
830
- },
831
- mediaCache: config.mediaCache,
832
- options: config.options,
833
- messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
834
- ...options,
835
- });
836
- const isDeleteMsg = 'delete' in content && !!content.delete;
837
- const isEditMsg = 'edit' in content && !!content.edit;
838
- const isPinMsg = 'pin' in content && !!content.pin;
839
- const isKeepMsg = 'keep' in content && content.keep;
840
- const isPollMessage = 'poll' in content && !!content.poll;
841
- const isAiMsg = 'ai' in content && !!content.ai;
842
- const additionalAttributes = {};
843
- const additionalNodes = [];
844
- // required for delete
845
- if (isDeleteMsg) {
846
- // if the chat is a group, and I am not the author, then delete the message as an admin
847
- if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
848
- additionalAttributes.edit = '8';
849
- }
850
- else {
851
- additionalAttributes.edit = '7';
852
- }
853
- // required for edit message
854
- }
855
- else if (isEditMsg) {
856
- additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
857
- // required for pin message
858
- }
859
- else if (isPinMsg) {
860
- additionalAttributes.edit = '2';
861
- // required for keep message
862
- }
863
- else if (isKeepMsg) {
864
- additionalAttributes.edit = '6';
865
- // required for polling message
866
- }
867
- else if (isPollMessage) {
868
- additionalNodes.push({
869
- tag: 'meta',
870
- attrs: {
871
- polltype: 'creation'
872
- },
873
- });
874
- // required to display AI icon on message
875
- }
876
- else if (isAiMsg) {
877
- additionalNodes.push({
878
- attrs: {
879
- biz_bot: '1'
880
- },
881
- tag: "bot"
882
- });
883
- }
884
- if (mediaHandle) {
885
- additionalAttributes['media_id'] = mediaHandle;
886
- }
887
- if ('cachedGroupMetadata' in options) {
888
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
889
- }
890
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
891
- if (config.emitOwnEvents) {
892
- process.nextTick(() => {
893
- processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
894
- });
895
- }
896
- return fullMsg;
897
- }
898
- }
899
- };
900
- };
901
- exports.makeMessagesSocket = makeMessagesSocket;
1
+ "use strict";
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
+ exports.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const crypto_1 = require("crypto");
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Utils_1 = require("../Utils");
13
+ const retry_1 = require("../Utils/retry");
14
+ const link_preview_1 = require("../Utils/link-preview");
15
+ const WABinary_1 = require("../WABinary");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const newsletter_1 = require("./newsletter");
18
+ const makeMessagesSocket = (config) => {
19
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
20
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
21
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
22
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
23
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
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
+ /** Fetch all the devices we've to send a message to */
115
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
116
+ var _a;
117
+ const deviceResults = [];
118
+ if (!useCache) {
119
+ logger.debug('not using cache for devices');
120
+ }
121
+ const toFetch = [];
122
+ jids = Array.from(new Set(jids));
123
+ for (let jid of jids) {
124
+ const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
125
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
126
+ if (useCache) {
127
+ const devices = userDevicesCache.get(user);
128
+ if (devices) {
129
+ deviceResults.push(...devices);
130
+ logger.trace({ user }, 'using cache for devices');
131
+ }
132
+ else {
133
+ toFetch.push(jid);
134
+ }
135
+ }
136
+ else {
137
+ toFetch.push(jid);
138
+ }
139
+ }
140
+ if (!toFetch.length) {
141
+ return deviceResults;
142
+ }
143
+ const query = new WAUSync_1.USyncQuery()
144
+ .withContext('message')
145
+ .withDeviceProtocol();
146
+ for (const jid of toFetch) {
147
+ query.withUser(new WAUSync_1.USyncUser().withId(jid));
148
+ }
149
+ const result = await sock.executeUSyncQuery(query);
150
+ if (result) {
151
+ const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
152
+ const deviceMap = {};
153
+ for (const item of extracted) {
154
+ deviceMap[item.user] = deviceMap[item.user] || [];
155
+ deviceMap[item.user].push(item);
156
+ deviceResults.push(item);
157
+ }
158
+ for (const key in deviceMap) {
159
+ userDevicesCache.set(key, deviceMap[key]);
160
+ }
161
+ }
162
+ return deviceResults;
163
+ };
164
+ const assertSessions = async (jids, force) => {
165
+ let didFetchNewSession = false;
166
+ let jidsRequiringFetch = [];
167
+ if (force) {
168
+ jidsRequiringFetch = jids;
169
+ }
170
+ else {
171
+ const addrs = jids.map(jid => (signalRepository
172
+ .jidToSignalProtocolAddress(jid)));
173
+ const sessions = await authState.keys.get('session', addrs);
174
+ for (const jid of jids) {
175
+ const signalId = signalRepository
176
+ .jidToSignalProtocolAddress(jid);
177
+ if (!sessions[signalId]) {
178
+ jidsRequiringFetch.push(jid);
179
+ }
180
+ }
181
+ }
182
+ if (jidsRequiringFetch.length) {
183
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
184
+ const result = await query({
185
+ tag: 'iq',
186
+ attrs: {
187
+ xmlns: 'encrypt',
188
+ type: 'get',
189
+ to: WABinary_1.S_WHATSAPP_NET,
190
+ },
191
+ content: [
192
+ {
193
+ tag: 'key',
194
+ attrs: {},
195
+ content: jidsRequiringFetch.map(jid => ({
196
+ tag: 'user',
197
+ attrs: { jid },
198
+ }))
199
+ }
200
+ ]
201
+ });
202
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
203
+ didFetchNewSession = true;
204
+ }
205
+ return didFetchNewSession;
206
+ };
207
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
208
+ var _a;
209
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
210
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
211
+ throw new boom_1.Boom('Not authenticated');
212
+ }
213
+ const protocolMessage = {
214
+ protocolMessage: {
215
+ peerDataOperationRequestMessage: pdoMessage,
216
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
217
+ }
218
+ };
219
+ const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
220
+ const msgId = await relayMessage(meJid, protocolMessage, {
221
+ additionalAttributes: {
222
+ category: 'peer',
223
+ // eslint-disable-next-line camelcase
224
+ push_priority: 'high_force',
225
+ },
226
+ });
227
+ return msgId;
228
+ };
229
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
230
+ let patched = await patchMessageBeforeSending(message, jids);
231
+ if (!Array.isArray(patched)) {
232
+ patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched];
233
+ }
234
+ let shouldIncludeDeviceIdentity = false;
235
+ const nodes = await Promise.all(patched.map(async (patchedMessageWithJid) => {
236
+ const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid;
237
+ if (!jid) {
238
+ return {};
239
+ }
240
+ const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
241
+ const { type, ciphertext } = await signalRepository
242
+ .encryptMessage({ jid, data: bytes });
243
+ if (type === 'pkmsg') {
244
+ shouldIncludeDeviceIdentity = true;
245
+ }
246
+ const node = {
247
+ tag: 'to',
248
+ attrs: { jid },
249
+ content: [{
250
+ tag: 'enc',
251
+ attrs: {
252
+ v: '2',
253
+ type,
254
+ ...extraAttrs || {}
255
+ },
256
+ content: ciphertext
257
+ }]
258
+ };
259
+ return node;
260
+ }));
261
+ return { nodes, shouldIncludeDeviceIdentity };
262
+ };
263
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
264
+ var _a;
265
+ const meId = authState.creds.me.id;
266
+ let shouldIncludeDeviceIdentity = false;
267
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
268
+ const statusJid = 'status@broadcast';
269
+ const isGroup = server === 'g.us';
270
+ const isNewsletter = server === 'newsletter';
271
+ const isStatus = jid === statusJid;
272
+ const isLid = server === 'lid';
273
+ msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
274
+ useUserDevicesCache = useUserDevicesCache !== false;
275
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
276
+ const participants = [];
277
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
278
+ const binaryNodeContent = [];
279
+ const devices = [];
280
+ const meMsg = {
281
+ deviceSentMessage: {
282
+ destinationJid,
283
+ message
284
+ },
285
+ messageContextInfo: message.messageContextInfo
286
+ };
287
+ const extraAttrs = {};
288
+ if (participant) {
289
+ // when the retry request is not for a group
290
+ // only send to the specific device that asked for a retry
291
+ // otherwise the message is sent out to every device that should be a recipient
292
+ if (!isGroup && !isStatus) {
293
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
294
+ }
295
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
296
+ devices.push({ user, device });
297
+ }
298
+ await authState.keys.transaction(async () => {
299
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
300
+ const mediaType = getMediaType(message);
301
+ if (mediaType) {
302
+ extraAttrs['mediatype'] = mediaType;
303
+ }
304
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
305
+ extraAttrs['decrypt-fail'] = 'hide';
306
+ }
307
+ if (isGroup || isStatus) {
308
+ const [groupData, senderKeyMap] = await Promise.all([
309
+ (async () => {
310
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
311
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
312
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
313
+ }
314
+ else if (!isStatus) {
315
+ groupData = await groupMetadata(jid);
316
+ }
317
+ return groupData;
318
+ })(),
319
+ (async () => {
320
+ if (!participant && !isStatus) {
321
+ const result = await authState.keys.get('sender-key-memory', [jid]);
322
+ return result[jid] || {};
323
+ }
324
+ return {};
325
+ })()
326
+ ]);
327
+ if (!participant) {
328
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
329
+ if (isStatus && statusJidList) {
330
+ participantsList.push(...statusJidList);
331
+ }
332
+ if (!isStatus) {
333
+ additionalAttributes = {
334
+ ...additionalAttributes,
335
+ // eslint-disable-next-line camelcase
336
+ addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
337
+ };
338
+ }
339
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
340
+ devices.push(...additionalDevices);
341
+ }
342
+ const patched = await patchMessageBeforeSending(message);
343
+ if (Array.isArray(patched)) {
344
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
345
+ }
346
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
347
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
348
+ group: destinationJid,
349
+ data: bytes,
350
+ meId,
351
+ });
352
+ const senderKeyJids = [];
353
+ // ensure a connection is established with every device
354
+ for (const { user, device } of devices) {
355
+ const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
356
+ if (!senderKeyMap[jid] || !!participant) {
357
+ senderKeyJids.push(jid);
358
+ // store that this person has had the sender keys sent to them
359
+ senderKeyMap[jid] = true;
360
+ }
361
+ }
362
+ // if there are some participants with whom the session has not been established
363
+ // if there are, we re-send the senderkey
364
+ if (senderKeyJids.length) {
365
+ logger.debug({ senderKeyJids }, 'sending new sender key');
366
+ const senderKeyMsg = {
367
+ senderKeyDistributionMessage: {
368
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
369
+ groupId: destinationJid
370
+ }
371
+ };
372
+ await assertSessions(senderKeyJids, false);
373
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
374
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
375
+ participants.push(...result.nodes);
376
+ }
377
+ binaryNodeContent.push({
378
+ tag: 'enc',
379
+ attrs: { v: '2', type: 'skmsg' },
380
+ content: ciphertext
381
+ });
382
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
383
+ }
384
+ else if (isNewsletter) {
385
+ // Message edit
386
+ if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
387
+ msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
388
+ message = message.protocolMessage.editedMessage;
389
+ }
390
+ // Message delete
391
+ if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
392
+ msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
393
+ message = {};
394
+ }
395
+ const patched = await patchMessageBeforeSending(message, []);
396
+ if (Array.isArray(patched)) {
397
+ throw new boom_1.Boom('Per-jid patching is not supported in channel');
398
+ }
399
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
400
+ binaryNodeContent.push({
401
+ tag: 'plaintext',
402
+ attrs: mediaType ? { mediatype: mediaType } : {},
403
+ content: bytes
404
+ });
405
+ }
406
+ else {
407
+ const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
408
+ if (!participant) {
409
+ devices.push({ user });
410
+ if (user !== meUser) {
411
+ devices.push({ user: meUser });
412
+ }
413
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
414
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
415
+ devices.push(...additionalDevices);
416
+ }
417
+ }
418
+ const allJids = [];
419
+ const meJids = [];
420
+ const otherJids = [];
421
+ for (const { user, device } of devices) {
422
+ const isMe = user === meUser;
423
+ const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_g = (_f = authState.creds) === null || _f === void 0 ? void 0 : _f.me) === null || _g === void 0 ? void 0 : _g.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
424
+ if (isMe) {
425
+ meJids.push(jid);
426
+ }
427
+ else {
428
+ otherJids.push(jid);
429
+ }
430
+ allJids.push(jid);
431
+ }
432
+ await assertSessions(allJids, false);
433
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
434
+ createParticipantNodes(meJids, meMsg, extraAttrs),
435
+ createParticipantNodes(otherJids, message, extraAttrs)
436
+ ]);
437
+ participants.push(...meNodes);
438
+ participants.push(...otherNodes);
439
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
440
+ }
441
+ if (participants.length) {
442
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
443
+ const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
444
+ if (peerNode) {
445
+ binaryNodeContent.push(peerNode); // push only enc
446
+ }
447
+ }
448
+ else {
449
+ binaryNodeContent.push({
450
+ tag: 'participants',
451
+ attrs: {},
452
+ content: participants
453
+ });
454
+ }
455
+ }
456
+ const stanza = {
457
+ tag: 'message',
458
+ attrs: {
459
+ id: msgId,
460
+ type: isNewsletter ? getTypeMessage(message) : 'text',
461
+ ...(additionalAttributes || {})
462
+ },
463
+ content: binaryNodeContent
464
+ };
465
+ // if the participant to send to is explicitly specified (generally retry recp)
466
+ // ensure the message is only sent to that person
467
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
468
+ if (participant) {
469
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
470
+ stanza.attrs.to = destinationJid;
471
+ stanza.attrs.participant = participant.jid;
472
+ }
473
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
474
+ stanza.attrs.to = participant.jid;
475
+ stanza.attrs.recipient = destinationJid;
476
+ }
477
+ else {
478
+ stanza.attrs.to = participant.jid;
479
+ }
480
+ }
481
+ else {
482
+ stanza.attrs.to = destinationJid;
483
+ }
484
+ if (shouldIncludeDeviceIdentity) {
485
+ stanza.content.push({
486
+ tag: 'device-identity',
487
+ attrs: {},
488
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
489
+ });
490
+ logger.debug({ jid }, 'adding device identity');
491
+ }
492
+ if (additionalNodes && additionalNodes.length > 0) {
493
+ stanza.content.push(...additionalNodes);
494
+ }
495
+ const content = (0, Utils_1.normalizeMessageContent)(message);
496
+ const contentType = (0, Utils_1.getContentType)(content);
497
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
498
+ contentType === 'buttonsMessage' ||
499
+ contentType === 'listMessage')) {
500
+ const bizNode = { tag: 'biz', attrs: {} };
501
+ if ((((_l = (_k = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _k === void 0 ? void 0 : _k.message) === null || _l === void 0 ? void 0 : _l.interactiveMessage) || ((_o = (_m = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _m === void 0 ? void 0 : _m.message) === null || _o === void 0 ? void 0 : _o.interactiveMessage) || ((_q = (_p = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _p === void 0 ? void 0 : _p.message) === null || _q === void 0 ? void 0 : _q.interactiveMessage) || (message === null || message === void 0 ? void 0 : message.interactiveMessage)) || (((_s = (_r = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _r === void 0 ? void 0 : _r.message) === null || _s === void 0 ? void 0 : _s.buttonsMessage) || ((_u = (_t = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _t === void 0 ? void 0 : _t.message) === null || _u === void 0 ? void 0 : _u.buttonsMessage) || ((_w = (_v = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _v === void 0 ? void 0 : _v.message) === null || _w === void 0 ? void 0 : _w.buttonsMessage) || (message === null || message === void 0 ? void 0 : message.buttonsMessage))) {
502
+ bizNode.content = [{
503
+ tag: 'interactive',
504
+ attrs: {
505
+ type: 'native_flow',
506
+ v: '1'
507
+ },
508
+ content: [{
509
+ tag: 'native_flow',
510
+ attrs: { v: '9', name: 'mixed' }
511
+ }]
512
+ }];
513
+ }
514
+ else if (message === null || message === void 0 ? void 0 : message.listMessage) {
515
+ // list message only support in private chat
516
+ bizNode.content = [{
517
+ tag: 'list',
518
+ attrs: {
519
+ type: 'product_list',
520
+ v: '2'
521
+ }
522
+ }];
523
+ }
524
+ else if (message?.interactiveMessage?.carouselMessage ||
525
+ message?.viewOnceMessage?.message?.interactiveMessage?.carouselMessage ||
526
+ message?.viewOnceMessageV2?.message?.interactiveMessage?.carouselMessage ||
527
+ message?.viewOnceMessageV2Extension?.message?.interactiveMessage?.carouselMessage) {
528
+ bizNode.content = [{
529
+ tag: 'interactive',
530
+ attrs: {
531
+ type: 'carousel',
532
+ v: '1'
533
+ },
534
+ content: [{
535
+ tag: 'carousel',
536
+ attrs: { v: '1' }
537
+ }]
538
+ }];
539
+ }
540
+ stanza.content.push(bizNode);
541
+ }
542
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
543
+ await (0, retry_1.retryWithBackoff)(({ signal }) => sendNode(stanza, { signal }), {
544
+ retries: 3,
545
+ baseMs: 300,
546
+ maxMs: 4000,
547
+ jitter: true,
548
+ timeoutPerAttemptMs: 5000,
549
+ shouldRetry: (err) => {
550
+ const status = err?.output?.statusCode || err?.statusCode;
551
+ // retry on transient failures
552
+ return !status || (status >= 500 || status === 408 || status === 429);
553
+ },
554
+ onRetry: (err, n) => logger?.warn?.({ err, attempt: n }, 'retrying sendNode')
555
+ });
556
+ });
557
+ return msgId;
558
+ };
559
+ const getTypeMessage = (msg) => {
560
+ if (msg.viewOnceMessage) {
561
+ return getTypeMessage(msg.viewOnceMessage.message);
562
+ }
563
+ else if (msg.viewOnceMessageV2) {
564
+ return getTypeMessage(msg.viewOnceMessageV2.message);
565
+ }
566
+ else if (msg.viewOnceMessageV2Extension) {
567
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
568
+ }
569
+ else if (msg.ephemeralMessage) {
570
+ return getTypeMessage(msg.ephemeralMessage.message);
571
+ }
572
+ else if (msg.documentWithCaptionMessage) {
573
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
574
+ }
575
+ else if (msg.reactionMessage) {
576
+ return 'reaction';
577
+ }
578
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
579
+ return 'poll';
580
+ }
581
+ else if (getMediaType(msg)) {
582
+ return 'media';
583
+ }
584
+ else {
585
+ return 'text';
586
+ }
587
+ };
588
+ const getMediaType = (message) => {
589
+ if (message.imageMessage) {
590
+ return 'image';
591
+ }
592
+ else if (message.videoMessage) {
593
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
594
+ }
595
+ else if (message.audioMessage) {
596
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
597
+ }
598
+ else if (message.contactMessage) {
599
+ return 'vcard';
600
+ }
601
+ else if (message.documentMessage) {
602
+ return 'document';
603
+ }
604
+ else if (message.contactsArrayMessage) {
605
+ return 'contact_array';
606
+ }
607
+ else if (message.liveLocationMessage) {
608
+ return 'livelocation';
609
+ }
610
+ else if (message.stickerMessage) {
611
+ return 'sticker';
612
+ }
613
+ else if (message.listMessage) {
614
+ return 'list';
615
+ }
616
+ else if (message.listResponseMessage) {
617
+ return 'list_response';
618
+ }
619
+ else if (message.buttonsResponseMessage) {
620
+ return 'buttons_response';
621
+ }
622
+ else if (message.orderMessage) {
623
+ return 'order';
624
+ }
625
+ else if (message.productMessage) {
626
+ return 'product';
627
+ }
628
+ else if (message.interactiveResponseMessage) {
629
+ return 'native_flow_response';
630
+ }
631
+ else if (message.groupInviteMessage) {
632
+ return 'url';
633
+ }
634
+ };
635
+ const getPrivacyTokens = async (jids) => {
636
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
637
+ const result = await query({
638
+ tag: 'iq',
639
+ attrs: {
640
+ to: WABinary_1.S_WHATSAPP_NET,
641
+ type: 'set',
642
+ xmlns: 'privacy'
643
+ },
644
+ content: [
645
+ {
646
+ tag: 'tokens',
647
+ attrs: {},
648
+ content: jids.map(jid => ({
649
+ tag: 'token',
650
+ attrs: {
651
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
652
+ t,
653
+ type: 'trusted_contact'
654
+ }
655
+ }))
656
+ }
657
+ ]
658
+ });
659
+ return result;
660
+ };
661
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
662
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
663
+
664
+ // Helper function to send message without admin-only logic
665
+ const sendMessageInternal = async (jid, content, options = {}) => {
666
+ var _a, _b, _c;
667
+ const userJid = authState.creds.me.id;
668
+
669
+ if (!options.ephemeralExpiration) {
670
+ if ((0, WABinary_1.isJidGroup)(jid)) {
671
+ const groups = await sock.groupQuery(jid, 'get', [{
672
+ tag: 'query',
673
+ attrs: {
674
+ request: 'interactive'
675
+ }
676
+ }]);
677
+ const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
678
+ const expiration = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(metadata, 'ephemeral')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.expiration) || 0;
679
+ options.ephemeralExpiration = expiration;
680
+ }
681
+ }
682
+ if (typeof content === 'object' &&
683
+ 'disappearingMessagesInChat' in content &&
684
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
685
+ (0, WABinary_1.isJidGroup)(jid)) {
686
+ const { disappearingMessagesInChat } = content;
687
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
688
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
689
+ disappearingMessagesInChat;
690
+ await groupToggleEphemeral(jid, value);
691
+ }
692
+ if (typeof content === 'object' && 'album' in content && content.album) {
693
+ const { album, caption } = content;
694
+ if (caption && !album[0].caption) {
695
+ album[0].caption = caption;
696
+ }
697
+ let mediaHandle;
698
+ let mediaMsg;
699
+ const albumMsg = (0, Utils_1.generateWAMessageFromContent)(jid, {
700
+ albumMessage: {
701
+ expectedImageCount: album.filter(item => 'image' in item).length,
702
+ expectedVideoCount: album.filter(item => 'video' in item).length
703
+ }
704
+ }, { userJid, ...options });
705
+ await relayMessage(jid, albumMsg.message, {
706
+ messageId: albumMsg.key.id
707
+ });
708
+ for (const i in album) {
709
+ const media = album[i];
710
+ if ('image' in media) {
711
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
712
+ image: media.image,
713
+ ...(media.caption ? { caption: media.caption } : {}),
714
+ ...options
715
+ }, {
716
+ userJid,
717
+ upload: async (readStream, opts) => {
718
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
719
+ mediaHandle = up.handle;
720
+ return up;
721
+ },
722
+ ...options,
723
+ });
724
+ }
725
+ else if ('video' in media) {
726
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
727
+ video: media.video,
728
+ ...(media.caption ? { caption: media.caption } : {}),
729
+ ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
730
+ ...options
731
+ }, {
732
+ userJid,
733
+ upload: async (readStream, opts) => {
734
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
735
+ mediaHandle = up.handle;
736
+ return up;
737
+ },
738
+ ...options,
739
+ });
740
+ }
741
+ else if ('url' in media) {
742
+ // Assume URL is an image if not specified
743
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
744
+ image: media.url,
745
+ ...(media.caption ? { caption: media.caption } : {}),
746
+ ...options
747
+ }, {
748
+ userJid,
749
+ upload: async (readStream, opts) => {
750
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
751
+ mediaHandle = up.handle;
752
+ return up;
753
+ },
754
+ ...options,
755
+ });
756
+ }
757
+ if (mediaMsg) {
758
+ mediaMsg.message.messageContextInfo = {
759
+ messageSecret: (0, crypto_1.randomBytes)(32),
760
+ messageAssociation: {
761
+ associationType: 1,
762
+ parentMessageKey: albumMsg.key
763
+ }
764
+ };
765
+ await relayMessage(jid, mediaMsg.message, {
766
+ messageId: mediaMsg.key.id
767
+ });
768
+ await new Promise(resolve => setTimeout(resolve, 800));
769
+ }
770
+ }
771
+ return albumMsg;
772
+ }
773
+ else if (typeof content === 'object' && 'stickerPack' in content && content.stickerPack) {
774
+ // Send sticker pack metadata first, then each sticker associated with it
775
+ const { stickerPack } = content;
776
+ const stickers = stickerPack.stickers || [];
777
+ if (!Array.isArray(stickers) || stickers.length === 0) {
778
+ throw new boom_1.Boom('stickerPack requires at least one sticker', { statusCode: 400 });
779
+ }
780
+
781
+ // Prepare cover thumbnail if provided
782
+ let thumbnailDirectPath;
783
+ let thumbnailEncSha256;
784
+ let thumbnailSha256;
785
+ let thumbnailHeight;
786
+ let thumbnailWidth;
787
+ if (stickerPack.cover) {
788
+ try {
789
+ const thumbMsg = await (0, Utils_1.prepareWAMessageMedia)({ image: stickerPack.cover }, {
790
+ logger,
791
+ userJid,
792
+ upload: async (readStream, opts) => {
793
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
794
+ return up;
795
+ },
796
+ mediaCache: config.mediaCache,
797
+ options: config.options,
798
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
799
+ ...options,
800
+ });
801
+ if (thumbMsg.imageMessage) {
802
+ thumbnailDirectPath = thumbMsg.imageMessage.directPath;
803
+ thumbnailEncSha256 = thumbMsg.imageMessage.fileEncSha256;
804
+ thumbnailSha256 = thumbMsg.imageMessage.fileSha256;
805
+ thumbnailHeight = thumbMsg.imageMessage.height;
806
+ thumbnailWidth = thumbMsg.imageMessage.width;
807
+ }
808
+ }
809
+ catch (err) {
810
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err }, 'failed to prepare stickerPack cover');
811
+ }
812
+ }
813
+
814
+ // Map stickers metadata to proto-friendly shape
815
+ const protoStickers = stickers.map((s, idx) => ({
816
+ fileName: s.fileName || `sticker_${idx}.webp`,
817
+ isAnimated: !!s.isAnimated,
818
+ emojis: Array.isArray(s.emojis) ? s.emojis : (s.emojis ? [s.emojis] : []),
819
+ accessibilityLabel: s.accessibilityLabel,
820
+ isLottie: !!s.isLottie,
821
+ mimetype: s.mimetype || 'image/webp'
822
+ }));
823
+
824
+ const stickerPackObj = {
825
+ name: stickerPack.name,
826
+ publisher: stickerPack.publisher,
827
+ packDescription: stickerPack.description,
828
+ stickers: protoStickers,
829
+ thumbnailDirectPath,
830
+ thumbnailEncSha256,
831
+ thumbnailSha256,
832
+ thumbnailHeight,
833
+ thumbnailWidth,
834
+ };
835
+
836
+ // Create and send the pack metadata message
837
+ const contentForSend = { stickerPackMessage: WAProto_1.proto.Message.StickerPackMessage.fromObject(stickerPackObj) };
838
+ const packMsg = (0, Utils_1.generateWAMessageFromContent)(jid, contentForSend, {
839
+ userJid,
840
+ upload: waUploadToServer,
841
+ mediaCache: config.mediaCache,
842
+ options: config.options,
843
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
844
+ ...options,
845
+ });
846
+ await relayMessage(jid, packMsg.message, { messageId: packMsg.key.id });
847
+
848
+ // Send each sticker associated with the pack
849
+ let lastMsg = packMsg;
850
+ for (const sticker of stickers) {
851
+ const stickerData = sticker.sticker || sticker.data || sticker.buffer || sticker.image || sticker.url || sticker;
852
+ if (!stickerData) {
853
+ throw new boom_1.Boom('Sticker data not found for sticker: ' + JSON.stringify(sticker), { statusCode: 400 });
854
+ }
855
+ const stickerContent = { sticker: stickerData };
856
+ const stickerMsg = await (0, Utils_1.generateWAMessage)(jid, stickerContent, {
857
+ logger,
858
+ userJid,
859
+ upload: async (readStream, opts) => {
860
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
861
+ mediaHandle = up.handle;
862
+ return up;
863
+ },
864
+ mediaCache: config.mediaCache,
865
+ options: config.options,
866
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
867
+ ...options,
868
+ });
869
+ // Associate sticker with the pack message
870
+ stickerMsg.message.messageContextInfo = {
871
+ messageSecret: (0, crypto_1.randomBytes)(32),
872
+ messageAssociation: {
873
+ associationType: 1,
874
+ parentMessageKey: packMsg.key
875
+ }
876
+ };
877
+ await relayMessage(jid, stickerMsg.message, { messageId: stickerMsg.key.id });
878
+ lastMsg = stickerMsg;
879
+ // Add delay between stickers to avoid rate limiting
880
+ await new Promise(resolve => setTimeout(resolve, 800));
881
+ }
882
+ return lastMsg;
883
+ }
884
+ else {
885
+ let mediaHandle;
886
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
887
+ logger,
888
+ userJid,
889
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
890
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
891
+ fetchOpts: {
892
+ timeout: 3000,
893
+ ...axiosOptions || {}
894
+ },
895
+ logger,
896
+ uploadImage: generateHighQualityLinkPreview
897
+ ? waUploadToServer
898
+ : undefined
899
+ }),
900
+ getProfilePicUrl: sock.profilePictureUrl,
901
+ upload: async (readStream, opts) => {
902
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
903
+ mediaHandle = up.handle;
904
+ return up;
905
+ },
906
+ mediaCache: config.mediaCache,
907
+ options: config.options,
908
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
909
+ ...options,
910
+ });
911
+ const isDeleteMsg = 'delete' in content && !!content.delete;
912
+ const isEditMsg = 'edit' in content && !!content.edit;
913
+ const isPinMsg = 'pin' in content && !!content.pin;
914
+ const isKeepMsg = 'keep' in content && content.keep;
915
+ const isPollMessage = 'poll' in content && !!content.poll;
916
+ const isAiMsg = options.ai === true;
917
+ const additionalAttributes = {};
918
+ const additionalNodes = [];
919
+ // required for delete
920
+ if (isDeleteMsg) {
921
+ // if the chat is a group, and I am not the author, then delete the message as an admin
922
+ if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
923
+ additionalAttributes.edit = '8';
924
+ }
925
+ else {
926
+ additionalAttributes.edit = '7';
927
+ }
928
+ // required for edit message
929
+ }
930
+ else if (isEditMsg) {
931
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
932
+ // required for pin message
933
+ }
934
+ else if (isPinMsg) {
935
+ additionalAttributes.edit = '2';
936
+ // required for keep message
937
+ }
938
+ else if (isKeepMsg) {
939
+ additionalAttributes.edit = '6';
940
+ // required for polling message
941
+ }
942
+ else if (isPollMessage) {
943
+ additionalNodes.push({
944
+ tag: 'meta',
945
+ attrs: {
946
+ polltype: 'creation'
947
+ },
948
+ });
949
+ // required to display AI icon on message
950
+ }
951
+ else if (isAiMsg) {
952
+ additionalNodes.push({
953
+ attrs: {
954
+ biz_bot: '1'
955
+ },
956
+ tag: "bot"
957
+ });
958
+ }
959
+ if (mediaHandle) {
960
+ additionalAttributes['media_id'] = mediaHandle;
961
+ }
962
+ if ('cachedGroupMetadata' in options) {
963
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
964
+ }
965
+ // Add AI context if needed
966
+ if (isAiMsg) {
967
+ fullMsg.message.messageContextInfo = {
968
+ ...fullMsg.message.messageContextInfo,
969
+ biz_bot: '1'
970
+ };
971
+ }
972
+
973
+
974
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
975
+ if (config.emitOwnEvents) {
976
+ process.nextTick(() => {
977
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
978
+ });
979
+ }
980
+ return fullMsg;
981
+ }
982
+ };
983
+
984
+ return {
985
+ ...sock,
986
+ getPrivacyTokens,
987
+ assertSessions,
988
+ relayMessage,
989
+ sendReceipt,
990
+ sendReceipts,
991
+ readMessages,
992
+ refreshMediaConn,
993
+ waUploadToServer,
994
+ fetchPrivacySettings,
995
+ getUSyncDevices,
996
+ createParticipantNodes,
997
+ sendPeerDataOperationMessage,
998
+ updateMediaMessage: async (message) => {
999
+ const content = (0, Utils_1.assertMediaContent)(message.message);
1000
+ const mediaKey = content.mediaKey;
1001
+ const meId = authState.creds.me.id;
1002
+ const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
1003
+ let error = undefined;
1004
+ await Promise.all([
1005
+ sendNode(node),
1006
+ waitForMsgMediaUpdate(async (update) => {
1007
+ const result = update.find(c => c.key.id === message.key.id);
1008
+ if (result) {
1009
+ if (result.error) {
1010
+ error = result.error;
1011
+ }
1012
+ else {
1013
+ try {
1014
+ const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
1015
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
1016
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
1017
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
1018
+ }
1019
+ content.directPath = media.directPath;
1020
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
1021
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1022
+ }
1023
+ catch (err) {
1024
+ error = err;
1025
+ }
1026
+ }
1027
+ return true;
1028
+ }
1029
+ })
1030
+ ]);
1031
+ if (error) {
1032
+ throw error;
1033
+ }
1034
+ ev.emit('messages.update', [
1035
+ { key: message.key, update: { message: message.message } }
1036
+ ]);
1037
+ return message;
1038
+ },
1039
+ sendMessage: async (jid, content, options = {}) => {
1040
+ var _a, _b, _c;
1041
+ const userJid = authState.creds.me.id;
1042
+
1043
+ // Handle admin-only messages by sending private messages to each admin
1044
+ if (content.contextInfo?.isAdminOnly && (0, WABinary_1.isJidGroup)(jid)) {
1045
+ try {
1046
+ // Get group metadata to find admins
1047
+ const metadata = await sock.groupMetadata(jid);
1048
+ const participants = metadata.participants || [];
1049
+
1050
+ // Find admin JIDs and ensure they are properly formatted
1051
+ const adminJids = participants
1052
+ .filter(p => p.admin === 'admin' || p.admin === 'superadmin')
1053
+ .map(p => (0, WABinary_1.jidNormalizedUser)(p.id));
1054
+
1055
+ if (adminJids.length === 0) {
1056
+ throw new boom_1.Boom('No admins found in group', { statusCode: 400 });
1057
+ }
1058
+
1059
+ // Remove isAdminOnly from content to avoid recursion
1060
+ const contentCopy = { ...content };
1061
+ if (contentCopy.contextInfo) {
1062
+ const { isAdminOnly, ...contextInfoRest } = contentCopy.contextInfo;
1063
+ contentCopy.contextInfo = contextInfoRest;
1064
+ }
1065
+
1066
+ // Add group context to indicate this is from a group
1067
+ contentCopy.contextInfo = {
1068
+ ...contentCopy.contextInfo,
1069
+ groupJid: jid,
1070
+ adminOnlyMessage: true
1071
+ };
1072
+
1073
+ // Send private message to each admin
1074
+ const results = [];
1075
+ for (const adminJid of adminJids) {
1076
+ try {
1077
+ const result = await sendMessageInternal(adminJid, contentCopy, options);
1078
+ results.push(result);
1079
+ } catch (error) {
1080
+ console.warn(`Failed to send admin-only message to ${adminJid}:`, error);
1081
+ }
1082
+ }
1083
+
1084
+ return results.length > 0 ? results[0] : null; // Return first successful result
1085
+ } catch (error) {
1086
+ console.error('Failed to send admin-only message:', error);
1087
+ throw error;
1088
+ }
1089
+ }
1090
+
1091
+ if (!options.ephemeralExpiration) {
1092
+ if ((0, WABinary_1.isJidGroup)(jid)) {
1093
+ const groups = await sock.groupQuery(jid, 'get', [{
1094
+ tag: 'query',
1095
+ attrs: {
1096
+ request: 'interactive'
1097
+ }
1098
+ }]);
1099
+ const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
1100
+ const expiration = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(metadata, 'ephemeral')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.expiration) || 0;
1101
+ options.ephemeralExpiration = expiration;
1102
+ }
1103
+ }
1104
+ if (typeof content === 'object' &&
1105
+ 'disappearingMessagesInChat' in content &&
1106
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1107
+ (0, WABinary_1.isJidGroup)(jid)) {
1108
+ const { disappearingMessagesInChat } = content;
1109
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
1110
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
1111
+ disappearingMessagesInChat;
1112
+ await groupToggleEphemeral(jid, value);
1113
+ }
1114
+ if (typeof content === 'object' && 'album' in content && content.album) {
1115
+ const { album, caption } = content;
1116
+ if (caption && !album[0].caption) {
1117
+ album[0].caption = caption;
1118
+ }
1119
+ let mediaHandle;
1120
+ let mediaMsg;
1121
+ const albumMsg = (0, Utils_1.generateWAMessageFromContent)(jid, {
1122
+ albumMessage: {
1123
+ expectedImageCount: album.filter(item => 'image' in item).length,
1124
+ expectedVideoCount: album.filter(item => 'video' in item).length
1125
+ }
1126
+ }, { userJid, ...options });
1127
+ await relayMessage(jid, albumMsg.message, {
1128
+ messageId: albumMsg.key.id
1129
+ });
1130
+ for (const i in album) {
1131
+ const media = album[i];
1132
+ if ('image' in media) {
1133
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
1134
+ image: media.image,
1135
+ ...(media.caption ? { caption: media.caption } : {}),
1136
+ ...options
1137
+ }, {
1138
+ userJid,
1139
+ upload: async (readStream, opts) => {
1140
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
1141
+ mediaHandle = up.handle;
1142
+ return up;
1143
+ },
1144
+ ...options,
1145
+ });
1146
+ }
1147
+ else if ('video' in media) {
1148
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
1149
+ video: media.video,
1150
+ ...(media.caption ? { caption: media.caption } : {}),
1151
+ ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
1152
+ ...options
1153
+ }, {
1154
+ userJid,
1155
+ upload: async (readStream, opts) => {
1156
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
1157
+ mediaHandle = up.handle;
1158
+ return up;
1159
+ },
1160
+ ...options,
1161
+ });
1162
+ }
1163
+ else if ('url' in media) {
1164
+ // Assume URL is an image if not specified
1165
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
1166
+ image: media.url,
1167
+ ...(media.caption ? { caption: media.caption } : {}),
1168
+ ...options
1169
+ }, {
1170
+ userJid,
1171
+ upload: async (readStream, opts) => {
1172
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
1173
+ mediaHandle = up.handle;
1174
+ return up;
1175
+ },
1176
+ ...options,
1177
+ });
1178
+ }
1179
+ if (mediaMsg) {
1180
+ mediaMsg.message.messageContextInfo = {
1181
+ messageSecret: (0, crypto_1.randomBytes)(32),
1182
+ messageAssociation: {
1183
+ associationType: 1,
1184
+ parentMessageKey: albumMsg.key
1185
+ }
1186
+ };
1187
+ await relayMessage(jid, mediaMsg.message, {
1188
+ messageId: mediaMsg.key.id
1189
+ });
1190
+ await new Promise(resolve => setTimeout(resolve, 800));
1191
+ }
1192
+ }
1193
+ return albumMsg;
1194
+ }
1195
+ else if (typeof content === 'object' && 'stickerPack' in content && content.stickerPack) {
1196
+ // Send sticker pack metadata first, then each sticker associated with it
1197
+ const { stickerPack } = content;
1198
+ const stickers = stickerPack.stickers || [];
1199
+ if (!Array.isArray(stickers) || stickers.length === 0) {
1200
+ throw new boom_1.Boom('stickerPack requires at least one sticker', { statusCode: 400 });
1201
+ }
1202
+
1203
+ // Prepare cover thumbnail if provided
1204
+ let thumbnailDirectPath;
1205
+ let thumbnailEncSha256;
1206
+ let thumbnailSha256;
1207
+ let thumbnailHeight;
1208
+ let thumbnailWidth;
1209
+ if (stickerPack.cover) {
1210
+ try {
1211
+ const thumbMsg = await (0, Utils_1.prepareWAMessageMedia)({ image: stickerPack.cover }, {
1212
+ logger,
1213
+ userJid,
1214
+ upload: async (readStream, opts) => {
1215
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
1216
+ return up;
1217
+ },
1218
+ mediaCache: config.mediaCache,
1219
+ options: config.options,
1220
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
1221
+ ...options,
1222
+ });
1223
+ if (thumbMsg.imageMessage) {
1224
+ thumbnailDirectPath = thumbMsg.imageMessage.directPath;
1225
+ thumbnailEncSha256 = thumbMsg.imageMessage.fileEncSha256;
1226
+ thumbnailSha256 = thumbMsg.imageMessage.fileSha256;
1227
+ thumbnailHeight = thumbMsg.imageMessage.height;
1228
+ thumbnailWidth = thumbMsg.imageMessage.width;
1229
+ }
1230
+ }
1231
+ catch (err) {
1232
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err }, 'failed to prepare stickerPack cover');
1233
+ }
1234
+ }
1235
+
1236
+ // Map stickers metadata to proto-friendly shape
1237
+ const protoStickers = stickers.map((s, idx) => ({
1238
+ fileName: s.fileName || `sticker_${idx}.webp`,
1239
+ isAnimated: !!s.isAnimated,
1240
+ emojis: Array.isArray(s.emojis) ? s.emojis : (s.emojis ? [s.emojis] : []),
1241
+ accessibilityLabel: s.accessibilityLabel,
1242
+ isLottie: !!s.isLottie,
1243
+ mimetype: s.mimetype || 'image/webp'
1244
+ }));
1245
+
1246
+ const stickerPackObj = {
1247
+ name: stickerPack.name,
1248
+ publisher: stickerPack.publisher,
1249
+ packDescription: stickerPack.description,
1250
+ stickers: protoStickers,
1251
+ thumbnailDirectPath,
1252
+ thumbnailEncSha256,
1253
+ thumbnailSha256,
1254
+ thumbnailHeight,
1255
+ thumbnailWidth,
1256
+ };
1257
+
1258
+ // Create and send the pack metadata message
1259
+ const contentForSend = { stickerPackMessage: WAProto_1.proto.Message.StickerPackMessage.fromObject(stickerPackObj) };
1260
+ const packMsg = (0, Utils_1.generateWAMessageFromContent)(jid, contentForSend, {
1261
+ userJid,
1262
+ upload: waUploadToServer,
1263
+ mediaCache: config.mediaCache,
1264
+ options: config.options,
1265
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
1266
+ ...options,
1267
+ });
1268
+ await relayMessage(jid, packMsg.message, { messageId: packMsg.key.id });
1269
+
1270
+ // Send each sticker associated with the pack
1271
+ let lastMsg = packMsg;
1272
+ for (const sticker of stickers) {
1273
+ const stickerData = sticker.sticker || sticker.data || sticker.buffer || sticker.image || sticker.url || sticker;
1274
+ if (!stickerData) {
1275
+ throw new boom_1.Boom('Sticker data not found for sticker: ' + JSON.stringify(sticker), { statusCode: 400 });
1276
+ }
1277
+ const stickerContent = { sticker: stickerData };
1278
+ const stickerMsg = await (0, Utils_1.generateWAMessage)(jid, stickerContent, {
1279
+ logger,
1280
+ userJid,
1281
+ upload: async (readStream, opts) => {
1282
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
1283
+ return up;
1284
+ },
1285
+ mediaCache: config.mediaCache,
1286
+ options: config.options,
1287
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
1288
+ ...options,
1289
+ });
1290
+ // Associate sticker with the pack message
1291
+ stickerMsg.message.messageContextInfo = {
1292
+ messageSecret: (0, crypto_1.randomBytes)(32),
1293
+ messageAssociation: {
1294
+ associationType: 1,
1295
+ parentMessageKey: packMsg.key
1296
+ }
1297
+ };
1298
+ await relayMessage(jid, stickerMsg.message, { messageId: stickerMsg.key.id });
1299
+ lastMsg = stickerMsg;
1300
+ // Add delay between stickers to avoid rate limiting
1301
+ await new Promise(resolve => setTimeout(resolve, 800));
1302
+ }
1303
+ return lastMsg;
1304
+ }
1305
+ else {
1306
+ let mediaHandle;
1307
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
1308
+ logger,
1309
+ userJid,
1310
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
1311
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1312
+ fetchOpts: {
1313
+ timeout: 3000,
1314
+ ...axiosOptions || {}
1315
+ },
1316
+ logger,
1317
+ uploadImage: generateHighQualityLinkPreview
1318
+ ? waUploadToServer
1319
+ : undefined
1320
+ }),
1321
+ getProfilePicUrl: sock.profilePictureUrl,
1322
+ upload: async (readStream, opts) => {
1323
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
1324
+ mediaHandle = up.handle;
1325
+ return up;
1326
+ },
1327
+ mediaCache: config.mediaCache,
1328
+ options: config.options,
1329
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
1330
+ ...options,
1331
+ });
1332
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1333
+ const isEditMsg = 'edit' in content && !!content.edit;
1334
+ const isPinMsg = 'pin' in content && !!content.pin;
1335
+ const isKeepMsg = 'keep' in content && content.keep;
1336
+ const isPollMessage = 'poll' in content && !!content.poll;
1337
+ const isAiMsg = options.ai === true;
1338
+ const additionalAttributes = {};
1339
+ const additionalNodes = [];
1340
+ // required for delete
1341
+ if (isDeleteMsg) {
1342
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1343
+ if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
1344
+ additionalAttributes.edit = '8';
1345
+ }
1346
+ else {
1347
+ additionalAttributes.edit = '7';
1348
+ }
1349
+ // required for edit message
1350
+ }
1351
+ else if (isEditMsg) {
1352
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
1353
+ // required for pin message
1354
+ }
1355
+ else if (isPinMsg) {
1356
+ additionalAttributes.edit = '2';
1357
+ // required for keep message
1358
+ }
1359
+ else if (isKeepMsg) {
1360
+ additionalAttributes.edit = '6';
1361
+ // required for polling message
1362
+ }
1363
+ else if (isPollMessage) {
1364
+ additionalNodes.push({
1365
+ tag: 'meta',
1366
+ attrs: {
1367
+ polltype: 'creation'
1368
+ },
1369
+ });
1370
+ // required to display AI icon on message
1371
+ }
1372
+ else if (isAiMsg) {
1373
+ additionalNodes.push({
1374
+ attrs: {
1375
+ biz_bot: '1'
1376
+ },
1377
+ tag: "bot"
1378
+ });
1379
+ }
1380
+ if (mediaHandle) {
1381
+ additionalAttributes['media_id'] = mediaHandle;
1382
+ }
1383
+ if ('cachedGroupMetadata' in options) {
1384
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
1385
+ }
1386
+ // Add AI context if needed
1387
+ if (isAiMsg) {
1388
+ fullMsg.message.messageContextInfo = {
1389
+ ...fullMsg.message.messageContextInfo,
1390
+ biz_bot: '1'
1391
+ };
1392
+ }
1393
+
1394
+
1395
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
1396
+ if (config.emitOwnEvents) {
1397
+ process.nextTick(() => {
1398
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
1399
+ });
1400
+ }
1401
+ return fullMsg;
1402
+ }
1403
+ }
1404
+ };
1405
+ };
1406
+ exports.makeMessagesSocket = makeMessagesSocket;