@realvare/based 2.5.5 → 2.5.7

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