@realvare/based 2.5.7 → 2.5.71

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