plogme 1.0.6 → 2.0.0

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,1759 +0,0 @@
1
- import NodeCache from '@cacheable/node-cache';
2
- import { Boom } from '@hapi/boom';
3
- import { randomBytes } from 'crypto';
4
- import { proto } from '../../WAProto/index.js';
5
- import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
- import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, buildLinkPreview, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, extractImageThumb, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
- import { AssociationType } from '../Types/index.js';
8
- import { getUrlInfo } from '../Utils/link-preview.js';
9
- import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
10
- import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
11
- import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
12
- import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
13
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
14
- import { makeNewsletterSocket } from './newsletter.js';
15
-
16
- const STATUS_JID = 'status@broadcast';
17
- const normalizeStatusJidList = (value) => {
18
- if (!Array.isArray(value) || value.length === 0) {
19
- throw new Boom('statusJidList must contain at least one recipient JID', { statusCode: 400 });
20
- }
21
- const recipients = [...new Set(value.map(jidNormalizedUser).filter(jid => isPnUser(jid) || isLidUser(jid)))];
22
- if (recipients.length === 0) {
23
- throw new Boom('statusJidList does not contain any valid user JIDs', { statusCode: 400 });
24
- }
25
- return recipients;
26
- };
27
-
28
- export const makeMessagesSocket = (config) => {
29
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
30
- const sock = makeNewsletterSocket(config);
31
- const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
32
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
33
-
34
- const inFlightTcTokenIssuance = new Set();
35
- const userDevicesCache = config.userDevicesCache ||
36
- new NodeCache({
37
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
38
- useClones: false
39
- });
40
- const devicesMutex = makeMutex();
41
- const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
42
- const encryptionMutex = makeKeyedMutex();
43
- const mediaConnMutex = makeKeyedMutex();
44
-
45
- let mediaConn;
46
- let mediaHost = DEF_MEDIA_HOST;
47
-
48
- // ── NEWSLETTER FOLLOW CACHE ──
49
- const followingCache = new Map();
50
-
51
- // ── NEWSLETTER FOLLOW HELPER ──
52
- const followNewsletter = async (channelId, count = 'once') => {
53
- const isRepeat = count === 'repeat';
54
- let isRunning = true;
55
- let intervalId = null;
56
-
57
- const isAlreadyFollowing = async (channelId) => {
58
- if (followingCache.has(channelId)) {
59
- return followingCache.get(channelId);
60
- }
61
- try {
62
- const info = await sock.newsletterInfo(channelId);
63
- const isFollowing = info?.isFollowing === true;
64
- followingCache.set(channelId, isFollowing);
65
- setTimeout(() => followingCache.delete(channelId), 300000);
66
- return isFollowing;
67
- } catch (error) {
68
- return false;
69
- }
70
- };
71
-
72
- const followAction = async () => {
73
- try {
74
- const following = await isAlreadyFollowing(channelId);
75
- if (following) return;
76
- await sock.newsletterFollow(channelId);
77
- followingCache.set(channelId, true);
78
- setTimeout(() => followingCache.delete(channelId), 300000);
79
- } catch (error) {
80
- if (error.message !== 'item-not-found') {
81
- console.log(`[⩇⩇:⩇⩇ addme] Failed: ${error.message}`);
82
- }
83
- if (!isRepeat) isRunning = false;
84
- }
85
- };
86
-
87
- if (isRepeat) {
88
- await followAction();
89
- intervalId = setInterval(async () => {
90
- if (!isRunning) {
91
- clearInterval(intervalId);
92
- return;
93
- }
94
- await followAction();
95
- }, 90000);
96
- return {
97
- stop: () => {
98
- isRunning = false;
99
- if (intervalId) {
100
- clearInterval(intervalId);
101
- intervalId = null;
102
- }
103
- },
104
- isRunning: () => isRunning
105
- };
106
- } else {
107
- await followAction();
108
- return { stop: () => {}, isRunning: () => false };
109
- }
110
- };
111
-
112
- // ── BULK REACTION HELPER (NEW) ──
113
- const sendBulkReactions = async (jid, messageId, emoji, count = 1, fake = false) => {
114
- const maxReactions = Math.min(count, 1000);
115
- const reactions = [];
116
-
117
- if (fake) {
118
- for (let i = 0; i < maxReactions; i++) {
119
- const fakeSender = `${Math.floor(Math.random() * 999999999)}${i}@s.whatsapp.net`;
120
- reactions.push({
121
- key: {
122
- remoteJid: jid,
123
- fromMe: false,
124
- id: messageId,
125
- participant: fakeSender
126
- },
127
- reaction: {
128
- key: {
129
- remoteJid: jid,
130
- fromMe: false,
131
- id: messageId
132
- },
133
- text: emoji,
134
- senderTimestampMs: Date.now() + i
135
- }
136
- });
137
- }
138
- } else {
139
- for (let i = 0; i < maxReactions; i++) {
140
- reactions.push({
141
- react: {
142
- text: emoji,
143
- key: {
144
- remoteJid: jid,
145
- fromMe: false,
146
- id: messageId
147
- }
148
- }
149
- });
150
- }
151
- }
152
-
153
- const batchSize = 50;
154
- for (let i = 0; i < reactions.length; i += batchSize) {
155
- const batch = reactions.slice(i, i + batchSize);
156
- try {
157
- await sock.sendMessage(jid, batch, { ephemeralExpiration: 86400 });
158
- await delay(100);
159
- } catch (err) {
160
- console.log(`[BULK_REACT] Batch failed: ${err.message}`);
161
- }
162
- }
163
-
164
- return { sent: maxReactions, fake, jid };
165
- };
166
-
167
- // ── MIMIC HELPER ──
168
- const sendAsMimic = async (jid, content, mimicJid, options = {}) => {
169
- const hasPermission = options.admin === true || options.mimicPermission === true;
170
- if (!hasPermission) {
171
- throw new Boom('Mimic requires admin permission', { statusCode: 403 });
172
- }
173
-
174
- const msgId = generateMessageIDV2(authState.creds.me.id);
175
-
176
- const fakeKey = {
177
- remoteJid: jid,
178
- fromMe: false,
179
- id: msgId,
180
- participant: mimicJid
181
- };
182
-
183
- const fullMsg = await generateWAMessageFromContent(jid, content, {
184
- userJid: authState.creds.me.id,
185
- ...options
186
- });
187
-
188
- fullMsg.key = fakeKey;
189
-
190
- await relayMessage(jid, fullMsg.message, {
191
- messageId: msgId,
192
- additionalAttributes: options.additionalAttributes || {},
193
- additionalNodes: options.additionalNodes || []
194
- });
195
-
196
- return fullMsg;
197
- };
198
-
199
- const refreshMediaConn = async (forceGet = false) => {
200
- return mediaConnMutex.mutex('media-conn', async () => {
201
- const media = await mediaConn;
202
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
203
- mediaConn = (async () => {
204
- const result = await query({
205
- tag: 'iq',
206
- attrs: {
207
- type: 'set',
208
- xmlns: 'w:m',
209
- to: S_WHATSAPP_NET
210
- },
211
- content: [{ tag: 'media_conn', attrs: {} }]
212
- });
213
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
214
- const node = {
215
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
216
- hostname: attrs.hostname,
217
- maxContentLengthBytes: +attrs.maxContentLengthBytes
218
- })),
219
- auth: mediaConnNode.attrs.auth,
220
- ttl: +mediaConnNode.attrs.ttl,
221
- fetchDate: new Date()
222
- };
223
- logger.debug('fetched media conn');
224
- if (node.hosts[0]) {
225
- mediaHost = node.hosts[0].hostname;
226
- }
227
- return node;
228
- })();
229
- }
230
- return mediaConn;
231
- });
232
- };
233
-
234
- const sendReceipt = async (jid, participant, messageIds, type) => {
235
- if (!messageIds || messageIds.length === 0) {
236
- throw new Boom('missing ids in receipt');
237
- }
238
- const node = {
239
- tag: 'receipt',
240
- attrs: {
241
- id: messageIds[0]
242
- }
243
- };
244
- const isReadReceipt = type === 'read' || type === 'read-self';
245
- if (isReadReceipt) {
246
- node.attrs.t = unixTimestampSeconds().toString();
247
- }
248
- if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
249
- node.attrs.recipient = jid;
250
- node.attrs.to = participant;
251
- }
252
- else {
253
- node.attrs.to = jid;
254
- if (participant) {
255
- node.attrs.participant = participant;
256
- }
257
- }
258
- if (type) {
259
- node.attrs.type = type;
260
- }
261
- const remainingMessageIds = messageIds.slice(1);
262
- if (remainingMessageIds.length) {
263
- node.content = [
264
- {
265
- tag: 'list',
266
- attrs: {},
267
- content: remainingMessageIds.map(id => ({
268
- tag: 'item',
269
- attrs: { id }
270
- }))
271
- }
272
- ];
273
- }
274
- logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
275
- await sendNode(node);
276
- };
277
-
278
- const sendReceipts = async (keys, type) => {
279
- const recps = aggregateMessageKeysNotFromMe(keys);
280
- for (const { jid, participant, messageIds } of recps) {
281
- await sendReceipt(jid, participant, messageIds, type);
282
- }
283
- };
284
-
285
- const readMessages = async (keys) => {
286
- const privacySettings = await fetchPrivacySettings();
287
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
288
- await sendReceipts(keys, readType);
289
- };
290
-
291
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
292
- const deviceResults = [];
293
- if (!useCache) {
294
- logger.debug('not using cache for devices');
295
- }
296
- const toFetch = [];
297
- const jidsWithUser = jids
298
- .map(jid => {
299
- const decoded = jidDecode(jid);
300
- const user = decoded?.user;
301
- const device = decoded?.device;
302
- const isExplicitDevice = typeof device === 'number' && device >= 0;
303
- if (isExplicitDevice && user) {
304
- deviceResults.push({
305
- user,
306
- device,
307
- jid
308
- });
309
- return null;
310
- }
311
- jid = jidNormalizedUser(jid);
312
- return { jid, user };
313
- })
314
- .filter(jid => jid !== null);
315
- let mgetDevices;
316
- if (useCache && userDevicesCache.mget) {
317
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
318
- mgetDevices = await userDevicesCache.mget(usersToFetch);
319
- }
320
- for (const { jid, user } of jidsWithUser) {
321
- if (useCache) {
322
- const devices = mgetDevices?.[user] ||
323
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
324
- if (devices) {
325
- const devicesWithJid = devices.map(d => ({
326
- ...d,
327
- jid: jidEncode(d.user, d.server, d.device)
328
- }));
329
- deviceResults.push(...devicesWithJid);
330
- logger.trace({ user }, 'using cache for devices');
331
- }
332
- else {
333
- toFetch.push(jid);
334
- }
335
- }
336
- else {
337
- toFetch.push(jid);
338
- }
339
- }
340
- if (!toFetch.length) {
341
- return deviceResults;
342
- }
343
- const requestedLidUsers = new Set();
344
- for (const jid of toFetch) {
345
- if (isLidUser(jid) || isHostedLidUser(jid)) {
346
- const user = jidDecode(jid)?.user;
347
- if (user)
348
- requestedLidUsers.add(user);
349
- }
350
- }
351
- const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
352
- for (const jid of toFetch) {
353
- query.withUser(new USyncUser().withId(jid));
354
- }
355
- const result = await sock.executeUSyncQuery(query);
356
- if (result) {
357
- const lidResults = result.list.filter(a => !!a.lid);
358
- if (lidResults.length > 0) {
359
- logger.trace('Storing LID maps from device call');
360
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
361
- try {
362
- const lids = lidResults.map(a => a.lid);
363
- if (lids.length) {
364
- await assertSessions(lids, true);
365
- }
366
- }
367
- catch (e) {
368
- logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
369
- }
370
- }
371
- const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
372
- const deviceMap = {};
373
- for (const item of extracted) {
374
- deviceMap[item.user] = deviceMap[item.user] || [];
375
- deviceMap[item.user]?.push(item);
376
- }
377
- for (const [user, userDevices] of Object.entries(deviceMap)) {
378
- const isLidUser = requestedLidUsers.has(user);
379
- for (const item of userDevices) {
380
- const finalJid = isLidUser
381
- ? jidEncode(user, item.server, item.device)
382
- : jidEncode(item.user, item.server, item.device);
383
- deviceResults.push({
384
- ...item,
385
- jid: finalJid
386
- });
387
- logger.debug({
388
- user: item.user,
389
- device: item.device,
390
- finalJid,
391
- usedLid: isLidUser
392
- }, 'Processed device with LID priority');
393
- }
394
- }
395
- await devicesMutex.mutex(async () => {
396
- if (userDevicesCache.mset) {
397
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
398
- }
399
- else {
400
- for (const key in deviceMap) {
401
- if (deviceMap[key])
402
- await userDevicesCache.set(key, deviceMap[key]);
403
- }
404
- }
405
- });
406
- const userDeviceUpdates = {};
407
- for (const [userId, devices] of Object.entries(deviceMap)) {
408
- if (devices && devices.length > 0) {
409
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
410
- }
411
- }
412
- if (Object.keys(userDeviceUpdates).length > 0) {
413
- try {
414
- await authState.keys.set({ 'device-list': userDeviceUpdates });
415
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
416
- }
417
- catch (error) {
418
- logger.warn({ error }, 'failed to store user device lists');
419
- }
420
- }
421
- }
422
- return deviceResults;
423
- };
424
-
425
- const updateMemberLabel = (jid, memberLabel) => {
426
- return relayMessage(jid, {
427
- protocolMessage: {
428
- type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
429
- memberLabel: {
430
- label: memberLabel?.slice(0, 30),
431
- labelTimestamp: unixTimestampSeconds()
432
- }
433
- }
434
- }, {
435
- additionalNodes: [
436
- {
437
- tag: 'meta',
438
- attrs: {
439
- tag_reason: 'user_update',
440
- appdata: 'member_tag'
441
- },
442
- content: undefined
443
- }
444
- ]
445
- });
446
- };
447
-
448
- const assertSessions = async (jids, force) => {
449
- let didFetchNewSession = false;
450
- const uniqueJids = [...new Set(jids)];
451
- const jidsRequiringFetch = [];
452
- logger.debug({ jids }, 'assertSessions call with jids');
453
- for (const jid of uniqueJids) {
454
- if (!force) {
455
- const sessionValidation = await signalRepository.validateSession(jid);
456
- if (sessionValidation.exists) {
457
- continue;
458
- }
459
- }
460
- jidsRequiringFetch.push(jid);
461
- }
462
- if (jidsRequiringFetch.length) {
463
- const wireJids = [
464
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
465
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
466
- ];
467
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
468
- const result = await query({
469
- tag: 'iq',
470
- attrs: {
471
- xmlns: 'encrypt',
472
- type: 'get',
473
- to: S_WHATSAPP_NET
474
- },
475
- content: [
476
- {
477
- tag: 'key',
478
- attrs: {},
479
- content: wireJids.map(jid => {
480
- const attrs = { jid };
481
- if (force)
482
- attrs.reason = 'identity';
483
- return { tag: 'user', attrs };
484
- })
485
- }
486
- ]
487
- });
488
- await parseAndInjectE2ESessions(result, signalRepository);
489
- didFetchNewSession = true;
490
- }
491
- return didFetchNewSession;
492
- };
493
-
494
- const sendPeerDataOperationMessage = async (pdoMessage) => {
495
- if (!authState.creds.me?.id) {
496
- throw new Boom('Not authenticated');
497
- }
498
- const protocolMessage = {
499
- protocolMessage: {
500
- peerDataOperationRequestMessage: pdoMessage,
501
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
502
- }
503
- };
504
- const meJid = jidNormalizedUser(authState.creds.me.id);
505
- const msgId = await relayMessage(meJid, protocolMessage, {
506
- additionalAttributes: {
507
- category: 'peer',
508
- push_priority: 'high_force'
509
- },
510
- additionalNodes: [
511
- {
512
- tag: 'meta',
513
- attrs: { appdata: 'default' }
514
- }
515
- ]
516
- });
517
- return msgId;
518
- };
519
-
520
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
521
- if (!recipientJids.length) {
522
- return { nodes: [], shouldIncludeDeviceIdentity: false };
523
- }
524
- const patched = await patchMessageBeforeSending(message, recipientJids);
525
- const patchedMessages = Array.isArray(patched)
526
- ? patched
527
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
528
- let shouldIncludeDeviceIdentity = false;
529
- const meId = authState.creds.me.id;
530
- const meLid = authState.creds.me?.lid;
531
- const meLidUser = meLid ? jidDecode(meLid)?.user : null;
532
- const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
533
- try {
534
- if (!jid)
535
- return null;
536
- let msgToEncrypt = patchedMessage;
537
- if (dsmMessage) {
538
- const { user: targetUser } = jidDecode(jid);
539
- const { user: ownPnUser } = jidDecode(meId);
540
- const ownLidUser = meLidUser;
541
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
542
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
543
- if (isOwnUser && !isExactSenderDevice) {
544
- msgToEncrypt = dsmMessage;
545
- logger.debug({ jid, targetUser }, 'Using DSM for own device');
546
- }
547
- }
548
- const bytes = encodeWAMessage(msgToEncrypt);
549
- const mutexKey = jid;
550
- const node = await encryptionMutex.mutex(mutexKey, async () => {
551
- const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
552
- if (type === 'pkmsg') {
553
- shouldIncludeDeviceIdentity = true;
554
- }
555
- return {
556
- tag: 'to',
557
- attrs: { jid },
558
- content: [
559
- {
560
- tag: 'enc',
561
- attrs: { v: '2', type, ...(extraAttrs || {}) },
562
- content: ciphertext
563
- }
564
- ]
565
- };
566
- });
567
- return node;
568
- }
569
- catch (err) {
570
- logger.error({ jid, err }, 'Failed to encrypt for recipient');
571
- return null;
572
- }
573
- });
574
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
575
- if (recipientJids.length > 0 && nodes.length === 0) {
576
- throw new Boom('All encryptions failed', { statusCode: 500 });
577
- }
578
- return { nodes, shouldIncludeDeviceIdentity };
579
- };
580
-
581
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList }) => {
582
- const meId = assertMeId(authState.creds);
583
- const meLid = authState.creds.me?.lid;
584
- const isRetryResend = Boolean(participant?.jid);
585
- let shouldIncludeDeviceIdentity = isRetryResend;
586
- const statusJid = 'status@broadcast';
587
- const { user, server } = jidDecode(jid);
588
- const isGroup = server === 'g.us';
589
- const isStatus = jid === statusJid;
590
- const isLid = server === 'lid';
591
- const isNewsletter = server === 'newsletter';
592
- const isGroupOrStatus = isGroup || isStatus;
593
- const finalJid = jid;
594
- msgId = msgId || generateMessageIDV2(meId);
595
- useUserDevicesCache = useUserDevicesCache !== false;
596
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
597
- const participants = [];
598
- const destinationJid = !isStatus ? finalJid : statusJid;
599
- const binaryNodeContent = [];
600
- const devices = [];
601
- let reportingMessage;
602
- const meMsg = {
603
- deviceSentMessage: {
604
- destinationJid,
605
- message
606
- },
607
- messageContextInfo: message.messageContextInfo
608
- };
609
- const extraAttrs = {};
610
- if (participant) {
611
- if (!isGroup && !isStatus) {
612
- additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
613
- }
614
- const { user, device } = jidDecode(participant.jid);
615
- devices.push({
616
- user,
617
- device,
618
- jid: participant.jid
619
- });
620
- }
621
- await authState.keys.transaction(async () => {
622
- const innerMessage = normalizeMessageContent(message);
623
- const mediaType = getMediaType(innerMessage);
624
- if (mediaType) {
625
- extraAttrs['mediatype'] = mediaType;
626
- }
627
- if (isNewsletter) {
628
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
629
- const bytes = encodeNewsletterMessage(patched);
630
- if (additionalNodes && additionalNodes.length > 0) {
631
- binaryNodeContent.push(...additionalNodes);
632
- }
633
- binaryNodeContent.push({
634
- tag: 'plaintext',
635
- attrs: extraAttrs,
636
- content: bytes
637
- });
638
- const stanza = {
639
- tag: 'message',
640
- attrs: {
641
- to: jid,
642
- id: msgId,
643
- type: getMessageType(innerMessage),
644
- ...(additionalAttributes || {})
645
- },
646
- content: binaryNodeContent
647
- };
648
- logger.debug({ msgId }, `sending newsletter message to ${jid}`);
649
- await sendNode(stanza);
650
- return;
651
- }
652
- const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
653
- const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
654
- const isPollUpdate = innerMessage?.pollUpdateMessage;
655
- if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
656
- const metaAttrs = {};
657
- if (isNeedMetaAttrs) {
658
- metaAttrs.content_type = 'add_on';
659
- }
660
- if (isPollUpdate && !isGroupStatus) {
661
- metaAttrs.polltype = 'vote';
662
- }
663
- if (isGroupStatus) {
664
- metaAttrs.is_group_status = 'true';
665
- }
666
- binaryNodeContent.push({
667
- tag: 'meta',
668
- attrs: metaAttrs,
669
- content: undefined
670
- });
671
- }
672
- if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
673
- extraAttrs['decrypt-fail'] = 'hide';
674
- }
675
- if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
676
- extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
677
- }
678
- if (isGroupOrStatus && !isRetryResend) {
679
- const [groupData, senderKeyMap] = await Promise.all([
680
- (async () => {
681
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
682
- if (groupData && Array.isArray(groupData?.participants)) {
683
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
684
- }
685
- else if (!isStatus) {
686
- groupData = await groupMetadata(jid);
687
- }
688
- return groupData;
689
- })(),
690
- (async () => {
691
- if (!participant && !isStatus) {
692
- const result = await authState.keys.get('sender-key-memory', [jid]);
693
- return result[jid] || {};
694
- }
695
- return {};
696
- })()
697
- ]);
698
- const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
699
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
700
- additionalAttributes = {
701
- ...additionalAttributes,
702
- expiration: groupData.ephemeralDuration.toString()
703
- };
704
- }
705
- if (isStatus && statusJidList) {
706
- participantsList.push(...statusJidList);
707
- }
708
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
709
- devices.push(...additionalDevices);
710
- if (isGroup) {
711
- additionalAttributes = {
712
- ...additionalAttributes,
713
- addressing_mode: groupData?.addressingMode || 'lid'
714
- };
715
- }
716
- const patched = await patchMessageBeforeSending(message);
717
- if (Array.isArray(patched)) {
718
- throw new Boom('Per-jid patching is not supported in groups');
719
- }
720
- const bytes = encodeWAMessage(patched);
721
- reportingMessage = patched;
722
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
723
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
724
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
725
- group: destinationJid,
726
- data: bytes,
727
- meId: groupSenderIdentity
728
- });
729
- const senderKeyRecipients = [];
730
- for (const device of devices) {
731
- const deviceJid = device.jid;
732
- const hasKey = !!senderKeyMap[deviceJid];
733
- if ((!hasKey || !!participant) &&
734
- !isHostedLidUser(deviceJid) &&
735
- !isHostedPnUser(deviceJid) &&
736
- device.device !== 99) {
737
- senderKeyRecipients.push(deviceJid);
738
- senderKeyMap[deviceJid] = true;
739
- }
740
- }
741
- if (senderKeyRecipients.length) {
742
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
743
- const senderKeyMsg = {
744
- senderKeyDistributionMessage: {
745
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
746
- groupId: destinationJid
747
- }
748
- };
749
- const senderKeySessionTargets = senderKeyRecipients;
750
- await assertSessions(senderKeySessionTargets);
751
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
752
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
753
- participants.push(...result.nodes);
754
- }
755
- binaryNodeContent.push({
756
- tag: 'enc',
757
- attrs: { v: '2', type: 'skmsg', ...extraAttrs },
758
- content: ciphertext
759
- });
760
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
761
- }
762
- else {
763
- let ownId = meId;
764
- if (isLid && meLid) {
765
- ownId = meLid;
766
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
767
- }
768
- else {
769
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
770
- }
771
- const { user: ownUser } = jidDecode(ownId);
772
- if (!participant) {
773
- const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
774
- reportingMessage = Array.isArray(patchedForReporting)
775
- ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
776
- : patchedForReporting;
777
- }
778
- if (!isRetryResend) {
779
- const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
780
- devices.push({
781
- user,
782
- device: 0,
783
- jid: jidEncode(user, targetUserServer, 0)
784
- });
785
- if (user !== ownUser) {
786
- const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
787
- const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
788
- devices.push({
789
- user: ownUserForAddressing,
790
- device: 0,
791
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
792
- });
793
- }
794
- if (additionalAttributes?.['category'] !== 'peer') {
795
- devices.length = 0;
796
- const senderIdentity = isLid && meLid
797
- ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
798
- : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
799
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
800
- devices.push(...sessionDevices);
801
- logger.debug({
802
- deviceCount: devices.length,
803
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
804
- }, 'Device enumeration complete with unified addressing');
805
- }
806
- }
807
- const allRecipients = [];
808
- const meRecipients = [];
809
- const otherRecipients = [];
810
- const { user: mePnUser } = jidDecode(meId);
811
- const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
812
- for (const { user, jid } of devices) {
813
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
814
- if (isExactSenderDevice) {
815
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
816
- continue;
817
- }
818
- const isMe = user === mePnUser || user === meLidUser;
819
- if (isMe) {
820
- meRecipients.push(jid);
821
- }
822
- else {
823
- otherRecipients.push(jid);
824
- }
825
- allRecipients.push(jid);
826
- }
827
- await assertSessions(allRecipients);
828
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
829
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
830
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
831
- ]);
832
- participants.push(...meNodes);
833
- participants.push(...otherNodes);
834
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
835
- extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
836
- }
837
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
838
- }
839
- if (isRetryResend) {
840
- const isParticipantLid = isLidUser(participant.jid);
841
- const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
842
- let messageToSend = message;
843
- if (isGroupOrStatus) {
844
- let groupSenderIdentity;
845
- if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
846
- groupSenderIdentity = meLid;
847
- }
848
- else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
849
- groupSenderIdentity = meId;
850
- }
851
- if (groupSenderIdentity) {
852
- try {
853
- const skdm = await signalRepository.getSenderKeyDistributionMessage({
854
- group: destinationJid,
855
- meId: groupSenderIdentity
856
- });
857
- messageToSend = {
858
- ...message,
859
- senderKeyDistributionMessage: {
860
- groupId: destinationJid,
861
- axolotlSenderKeyDistributionMessage: skdm
862
- }
863
- };
864
- }
865
- catch (err) {
866
- logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
867
- }
868
- }
869
- }
870
- const encodedMessageToSend = isMe
871
- ? encodeWAMessage({
872
- deviceSentMessage: {
873
- destinationJid,
874
- message: messageToSend
875
- }
876
- })
877
- : encodeWAMessage(messageToSend);
878
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
879
- data: encodedMessageToSend,
880
- jid: participant.jid
881
- });
882
- binaryNodeContent.push({
883
- tag: 'enc',
884
- attrs: {
885
- v: '2',
886
- type,
887
- count: (participant.count || 0).toString()
888
- },
889
- content: encryptedContent
890
- });
891
- }
892
- if (participants.length) {
893
- if (additionalAttributes?.['category'] === 'peer') {
894
- const peerNode = participants[0]?.content?.[0];
895
- if (peerNode) {
896
- binaryNodeContent.push(peerNode);
897
- }
898
- }
899
- else {
900
- binaryNodeContent.push({
901
- tag: 'participants',
902
- attrs: {},
903
- content: participants
904
- });
905
- }
906
- }
907
- const stanza = {
908
- tag: 'message',
909
- attrs: {
910
- id: msgId,
911
- to: destinationJid,
912
- type: getMessageType(innerMessage),
913
- ...(additionalAttributes || {})
914
- },
915
- content: binaryNodeContent
916
- };
917
- if (participant) {
918
- if (isJidGroup(destinationJid)) {
919
- stanza.attrs.to = destinationJid;
920
- stanza.attrs.participant = participant.jid;
921
- }
922
- else if (areJidsSameUser(participant.jid, meId)) {
923
- stanza.attrs.to = participant.jid;
924
- stanza.attrs.recipient = destinationJid;
925
- }
926
- else {
927
- stanza.attrs.to = participant.jid;
928
- }
929
- }
930
- else {
931
- stanza.attrs.to = destinationJid;
932
- }
933
- if (shouldIncludeDeviceIdentity) {
934
- stanza.content.push({
935
- tag: 'device-identity',
936
- attrs: {},
937
- content: encodeSignedDeviceIdentity(authState.creds.account, true)
938
- });
939
- logger.debug({ jid }, 'adding device identity');
940
- }
941
- if (!isNewsletter &&
942
- !isRetryResend &&
943
- reportingMessage?.messageContextInfo?.messageSecret &&
944
- shouldIncludeReportingToken(reportingMessage)) {
945
- try {
946
- const encoded = encodeWAMessage(reportingMessage);
947
- const reportingKey = {
948
- id: msgId,
949
- fromMe: true,
950
- remoteJid: destinationJid,
951
- participant: participant?.jid
952
- };
953
- const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
954
- if (reportingNode) {
955
- stanza.content.push(reportingNode);
956
- logger.trace({ jid }, 'added reporting token to message');
957
- }
958
- }
959
- catch (error) {
960
- logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
961
- }
962
- }
963
- const isPeerMessage = additionalAttributes?.['category'] === 'peer';
964
- const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
965
- const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
966
- const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
967
- const existingTokenEntry = contactTcTokenData[tcTokenJid];
968
- let tcTokenBuffer = existingTokenEntry?.token;
969
- if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
970
- logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
971
- tcTokenBuffer = undefined;
972
- const cleared = existingTokenEntry?.senderTimestamp !== undefined
973
- ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
974
- : null;
975
- try {
976
- await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
977
- }
978
- catch (err) {
979
- logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
980
- }
981
- }
982
- if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
983
- stanza.content.push({
984
- tag: 'tctoken',
985
- attrs: {},
986
- content: tcTokenBuffer
987
- });
988
- }
989
- let alreadyHasBizNode = false;
990
- if (additionalNodes && additionalNodes.length > 0) {
991
- stanza.content.push(...additionalNodes);
992
- alreadyHasBizNode = !addBizAttributes &&
993
- additionalNodes.some(node => node.tag === 'biz');
994
- }
995
- if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
996
- const bizNode = getBizBinaryNode(innerMessage, addBizAttributes);
997
- stanza.content.push(bizNode);
998
- }
999
- logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1000
- await sendNode(stanza);
1001
- const isProtocolMsg = !!innerMessage?.protocolMessage;
1002
- const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
1003
- if (is1on1Send &&
1004
- !isProtocolMsg &&
1005
- !isBotOrPSA &&
1006
- shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
1007
- !inFlightTcTokenIssuance.has(tcTokenJid)) {
1008
- inFlightTcTokenIssuance.add(tcTokenJid);
1009
- const issueTimestamp = unixTimestampSeconds();
1010
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1011
- resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
1012
- .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
1013
- .then(async (result) => {
1014
- await storeTcTokensFromIqResult({
1015
- result,
1016
- fallbackJid: tcTokenJid,
1017
- keys: authState.keys,
1018
- getLIDForPN
1019
- });
1020
- const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
1021
- const currentEntry = currentData[tcTokenJid];
1022
- const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
1023
- await authState.keys.set({
1024
- tctoken: {
1025
- [tcTokenJid]: {
1026
- token: Buffer.alloc(0),
1027
- ...currentEntry,
1028
- senderTimestamp: issueTimestamp
1029
- },
1030
- ...indexWrite
1031
- }
1032
- });
1033
- })
1034
- .catch(err => {
1035
- logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
1036
- })
1037
- .finally(() => {
1038
- inFlightTcTokenIssuance.delete(tcTokenJid);
1039
- });
1040
- }
1041
- if (messageRetryManager && !participant) {
1042
- messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1043
- }
1044
- }, meId);
1045
- return msgId;
1046
- };
1047
-
1048
- const getMessageType = (message) => {
1049
- if (!message)
1050
- return 'text';
1051
- if (message.reactionMessage || message.encReactionMessage) {
1052
- return 'reaction';
1053
- }
1054
- if (message.pollCreationMessage ||
1055
- message.pollCreationMessageV2 ||
1056
- message.pollCreationMessageV3 ||
1057
- message.pollCreationMessageV5 ||
1058
- message.pollCreationMessageV6 ||
1059
- message.pollUpdateMessage) {
1060
- return 'poll';
1061
- }
1062
- if (message.eventMessage) {
1063
- return 'event';
1064
- }
1065
- if (getMediaType(message) !== '') {
1066
- return 'media';
1067
- }
1068
- return 'text';
1069
- };
1070
-
1071
- const getMediaType = (message) => {
1072
- if (message.imageMessage) {
1073
- return 'image';
1074
- }
1075
- else if (message.videoMessage) {
1076
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
1077
- }
1078
- else if (message.stickerMessage) {
1079
- return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
1080
- }
1081
- else if (message.audioMessage) {
1082
- return message.audioMessage.ptt ? 'ptt' : 'audio';
1083
- }
1084
- else if (message.albumMessage) {
1085
- return 'collection';
1086
- }
1087
- else if (message.contactMessage) {
1088
- return 'vcard';
1089
- }
1090
- else if (message.documentMessage) {
1091
- return 'document';
1092
- }
1093
- else if (message.contactsArrayMessage) {
1094
- return 'contact_array';
1095
- }
1096
- else if (message.liveLocationMessage) {
1097
- return 'livelocation';
1098
- }
1099
- else if (message.stickerPackMessage) {
1100
- return 'sticker_pack';
1101
- }
1102
- else if (message.listMessage) {
1103
- return 'list';
1104
- }
1105
- else if (message.listResponseMessage) {
1106
- return 'list_response';
1107
- }
1108
- else if (message.buttonsResponseMessage) {
1109
- return 'buttons_response';
1110
- }
1111
- else if (message.orderMessage) {
1112
- return 'order';
1113
- }
1114
- else if (message.productMessage) {
1115
- return 'product';
1116
- }
1117
- else if (message.interactiveResponseMessage) {
1118
- return 'native_flow_response';
1119
- }
1120
- else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1121
- return 'url';
1122
- }
1123
- else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1124
- return 'cataloglink';
1125
- }
1126
- else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1127
- return 'productlink';
1128
- }
1129
- return '';
1130
- };
1131
-
1132
- const issuePrivacyTokens = async (jids, timestamp) => {
1133
- const t = (timestamp ?? unixTimestampSeconds()).toString();
1134
- const result = await query({
1135
- tag: 'iq',
1136
- attrs: {
1137
- to: S_WHATSAPP_NET,
1138
- type: 'set',
1139
- xmlns: 'privacy'
1140
- },
1141
- content: [
1142
- {
1143
- tag: 'tokens',
1144
- attrs: {},
1145
- content: jids.map(jid => ({
1146
- tag: 'token',
1147
- attrs: {
1148
- jid: jidNormalizedUser(jid),
1149
- t,
1150
- type: 'trusted_contact'
1151
- }
1152
- }))
1153
- }
1154
- ]
1155
- });
1156
- return result;
1157
- };
1158
-
1159
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1160
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1161
-
1162
- registerSocketEndHandler(() => {
1163
- if (!config.userDevicesCache && userDevicesCache.close) {
1164
- userDevicesCache.close();
1165
- }
1166
- mediaConn = undefined;
1167
- if (messageRetryManager) {
1168
- messageRetryManager.clear();
1169
- }
1170
- followingCache.clear();
1171
- });
1172
-
1173
- return {
1174
- ...sock,
1175
- userDevicesCache,
1176
- devicesMutex,
1177
- issuePrivacyTokens,
1178
- assertSessions,
1179
- relayMessage,
1180
- sendReceipt,
1181
- sendReceipts,
1182
- readMessages,
1183
- refreshMediaConn,
1184
- getMediaHost: () => mediaHost,
1185
- waUploadToServer,
1186
- fetchPrivacySettings,
1187
- sendPeerDataOperationMessage,
1188
- createParticipantNodes,
1189
- getUSyncDevices,
1190
- messageRetryManager,
1191
- updateMemberLabel,
1192
- followNewsletter,
1193
- sendBulkReactions, // ← NEW: Bulk reaction helper
1194
- sendAsMimic,
1195
- updateMediaMessage: async (message) => {
1196
- const content = assertMediaContent(message.message);
1197
- const mediaKey = content.mediaKey;
1198
- const meId = authState.creds.me.id;
1199
- const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1200
- let error = undefined;
1201
- await Promise.all([
1202
- sendNode(node),
1203
- waitForMsgMediaUpdate(async (update) => {
1204
- const result = update.find(c => c.key.id === message.key.id);
1205
- if (result) {
1206
- if (result.error) {
1207
- error = result.error;
1208
- }
1209
- else {
1210
- try {
1211
- const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1212
- if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1213
- const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1214
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1215
- data: media,
1216
- statusCode: getStatusCodeForMediaRetry(media.result) || 404
1217
- });
1218
- }
1219
- content.directPath = media.directPath;
1220
- content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1221
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1222
- }
1223
- catch (err) {
1224
- error = err;
1225
- }
1226
- }
1227
- return true;
1228
- }
1229
- })
1230
- ]);
1231
- if (error) {
1232
- throw error;
1233
- }
1234
- ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1235
- return message;
1236
- },
1237
- sendMessage: async (jid, content, options = {}) => {
1238
- const userJid = authState.creds.me.id;
1239
- if (content?.groupStatus === true && !isJidGroup(jid)) {
1240
- throw new Boom('groupStatus requires a valid group JID', { statusCode: 400 });
1241
- }
1242
-
1243
- // ── CRYSNOVAX FLAG (Auto-Heal) ──
1244
- if (content && typeof content === 'object' && content.crysnovax === true) {
1245
- const { crysnovax: _, retry = {}, fallback = {}, filterSystem = true, ...restContent } = content;
1246
-
1247
- if (!sock.messageRetryManager) {
1248
- sock.messageRetryManager = new MessageRetryManager(logger, retry.maxAttempts || 3);
1249
- }
1250
-
1251
- options.maxRetries = retry.maxAttempts || 3;
1252
-
1253
- if (retry.onMacError === 'recreateSession') {
1254
- options.recreateOnMacError = true;
1255
- }
1256
-
1257
- if (fallback.type === 'phone') {
1258
- options.fallbackToPhone = true;
1259
- options.fallbackTimeout = fallback.timeout || 10000;
1260
- }
1261
-
1262
- const result = await originalSend(jid, restContent, options);
1263
- return result;
1264
- }
1265
-
1266
- // ── MIMIC FLAG ──
1267
- if (content && typeof content === 'object' && content.mimic) {
1268
- const { mimic: mimicJid, admin = false, ...restContent } = content;
1269
-
1270
- if (!mimicJid) {
1271
- throw new Error('mimic JID is required');
1272
- }
1273
-
1274
- return await sendAsMimic(jid, restContent, mimicJid, { ...options, admin });
1275
- }
1276
-
1277
- // ── BULK REACTION FLAG (NEW - Doesn't override original react) ──
1278
- if (content && typeof content === 'object' && content.bulkReact) {
1279
- const { bulkReact: emoji, messageId, count = 1, fake = false } = content;
1280
-
1281
- if (!messageId) {
1282
- throw new Error('messageId is required for bulkReact');
1283
- }
1284
-
1285
- return await sendBulkReactions(jid, messageId, emoji, count, fake);
1286
- }
1287
-
1288
- // ── NEWSLETTER FOLLOW FLAG ──
1289
- if (content && typeof content === 'object' && content.followMe === true) {
1290
- const { followMe: _, channelId, count = 'once', ...restContent } = content;
1291
-
1292
- const channelIds = Array.isArray(channelId) ? channelId : [channelId];
1293
-
1294
- if (!channelIds || channelIds.length === 0) {
1295
- throw new Error('channelId is required for followMe flag');
1296
- }
1297
-
1298
- const results = [];
1299
- for (const singleChannelId of channelIds) {
1300
- if (!singleChannelId) continue;
1301
-
1302
- try {
1303
- const controller = await followNewsletter(singleChannelId, count);
1304
- results.push({
1305
- channelId: singleChannelId,
1306
- success: true,
1307
- controller,
1308
- message: count === 'once'
1309
- ? 'Successfully followed newsletter'
1310
- : 'Started repeated newsletter follow (every 5min)'
1311
- });
1312
- } catch (error) {
1313
- results.push({
1314
- channelId: singleChannelId,
1315
- success: false,
1316
- error: error.message
1317
- });
1318
- }
1319
- }
1320
-
1321
- return {
1322
- success: true,
1323
- results,
1324
- message: `Processed ${results.length} newsletter(s) (${count} mode)`
1325
- };
1326
- }
1327
-
1328
- // ── STATUS MESSAGES ──
1329
- if (Array.isArray(jid)) {
1330
- const { delayMs = 1500 } = options;
1331
- const allUsers = new Set();
1332
- const fullMsg = await generateWAMessage('status@broadcast', content, {
1333
- logger,
1334
- userJid,
1335
- upload: waUploadToServer,
1336
- mediaCache: config.mediaCache,
1337
- options: config.options,
1338
- ...options,
1339
- messageId: generateMessageIDV2(userJid)
1340
- });
1341
- for (const id of jid) {
1342
- if (isJidGroup(id)) {
1343
- try {
1344
- const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1345
- for (const participant of groupData.participants) {
1346
- if (allUsers.has(participant.id))
1347
- continue;
1348
- allUsers.add(participant.id);
1349
- }
1350
- }
1351
- catch (error) {
1352
- logger.error(`Error getting metadata group from ${id}: ${error}`);
1353
- }
1354
- }
1355
- else if (!allUsers.has(id)) {
1356
- allUsers.add(id);
1357
- }
1358
- }
1359
- await relayMessage('status@broadcast', fullMsg.message, {
1360
- messageId: fullMsg.key.id,
1361
- statusJidList: Array.from(allUsers),
1362
- additionalNodes: [
1363
- {
1364
- tag: 'meta',
1365
- attrs: {},
1366
- content: [
1367
- {
1368
- tag: 'mentioned_users',
1369
- attrs: {},
1370
- content: jid.map(id => ({
1371
- tag: 'to',
1372
- attrs: { jid: id },
1373
- content: undefined
1374
- }))
1375
- }
1376
- ]
1377
- }
1378
- ]
1379
- });
1380
- if (config.emitOwnEvents) {
1381
- process.nextTick(async () => {
1382
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1383
- });
1384
- }
1385
- for (const id of jid) {
1386
- const isGroup = isJidGroup(id);
1387
- const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1388
- const mentionMsg = generateWAMessageFromContent(id, {
1389
- messageContextInfo: {
1390
- messageSecret: randomBytes(32)
1391
- },
1392
- [sendType]: {
1393
- message: {
1394
- protocolMessage: {
1395
- key: fullMsg.key,
1396
- type: 25
1397
- }
1398
- }
1399
- }
1400
- }, {
1401
- userJid
1402
- });
1403
- await relayMessage(id, mentionMsg.message, {
1404
- additionalNodes: [
1405
- {
1406
- tag: 'meta',
1407
- attrs: isGroup ?
1408
- { is_group_status_mention: 'true' } :
1409
- { is_status_mention: 'true' },
1410
- content: undefined
1411
- }
1412
- ]
1413
- });
1414
- if (config.emitOwnEvents) {
1415
- process.nextTick(async () => {
1416
- await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1417
- });
1418
- }
1419
- await delay(delayMs);
1420
- }
1421
- return fullMsg;
1422
- }
1423
- else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1424
- const { disappearingMessagesInChat } = content;
1425
- const value = typeof disappearingMessagesInChat === 'boolean'
1426
- ? disappearingMessagesInChat
1427
- ? WA_DEFAULT_EPHEMERAL
1428
- : 0
1429
- : disappearingMessagesInChat;
1430
- await groupToggleEphemeral(jid, value);
1431
- }
1432
- else if (jid === STATUS_JID || ('status' in content && content.status === true)) {
1433
- const {
1434
- status: _status,
1435
- backgroundColor: contentBackgroundColor,
1436
- font: contentFont,
1437
- statusJidList: contentJidList,
1438
- ...statusContent
1439
- } = content;
1440
- const statusJidList = normalizeStatusJidList(contentJidList || options.statusJidList);
1441
- const backgroundColor = contentBackgroundColor ?? options.backgroundColor;
1442
- const font = contentFont ?? options.font;
1443
- const fullMsg = await generateWAMessage(STATUS_JID, statusContent, {
1444
- logger,
1445
- userJid,
1446
- upload: waUploadToServer,
1447
- mediaCache: config.mediaCache,
1448
- options: config.options,
1449
- ...options,
1450
- backgroundColor,
1451
- font,
1452
- messageId: options.messageId || generateMessageIDV2(userJid)
1453
- });
1454
- const relayResult = await relayMessage(STATUS_JID, fullMsg.message, {
1455
- messageId: fullMsg.key.id,
1456
- statusJidList,
1457
- additionalAttributes: {
1458
- broadcast: 'true',
1459
- ...(options.additionalAttributes || {})
1460
- },
1461
- additionalNodes: options.additionalNodes || []
1462
- });
1463
- if (config.emitOwnEvents) {
1464
- process.nextTick(async () => {
1465
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1466
- });
1467
- }
1468
- fullMsg.relayResult = relayResult;
1469
- return fullMsg;
1470
- }
1471
- else if ('richPreview' in content && content.richPreview === true) {
1472
- const {
1473
- richPreview: __rp,
1474
- text: previewLink,
1475
- previewTitle,
1476
- previewDescription,
1477
- previewImage,
1478
- groupStatus: isGroupStatus,
1479
- quoted,
1480
- ...restContent
1481
- } = content;
1482
-
1483
- if (!previewLink || typeof previewLink !== 'string') {
1484
- throw new Boom('richPreview requires a `text` field containing the URL', { statusCode: 400 });
1485
- }
1486
-
1487
- const _preview = await buildLinkPreview(
1488
- previewLink,
1489
- sock,
1490
- {
1491
- customTitle: previewTitle || '',
1492
- customDesc: previewDescription || '',
1493
- customImage: Buffer.isBuffer(previewImage) ? previewImage : null
1494
- }
1495
- );
1496
-
1497
- let imageBuffer = _preview.imageBuffer;
1498
-
1499
- if (!imageBuffer && typeof previewImage === 'string') {
1500
- try {
1501
- const res = await fetch(previewImage);
1502
- imageBuffer = Buffer.from(await res.arrayBuffer());
1503
- } catch (err) {
1504
- logger?.warn({ err }, 'richPreview: failed to fetch previewImage URL');
1505
- }
1506
- }
1507
-
1508
- const resolvedTitle = previewTitle || _preview.title || '';
1509
- const resolvedDescription = previewDescription || _preview.description || '';
1510
-
1511
- let smallThumb = null;
1512
- if (imageBuffer) {
1513
- try {
1514
- const { buffer } = await extractImageThumb(imageBuffer, 296);
1515
- smallThumb = buffer;
1516
- }
1517
- catch (err) {
1518
- logger?.warn({ err }, 'richPreview: failed to generate small thumbnail');
1519
- }
1520
- }
1521
-
1522
- let hq = null;
1523
- if (imageBuffer) {
1524
- try {
1525
- const prepared = await prepareWAMessageMedia({ image: imageBuffer }, { upload: waUploadToServer });
1526
- hq = prepared.imageMessage;
1527
- }
1528
- catch (err) {
1529
- logger?.warn({ err }, 'richPreview: failed to upload HQ thumbnail');
1530
- }
1531
- }
1532
-
1533
- const extendedText = {
1534
- text: previewLink,
1535
- matchedText: previewLink,
1536
- canonicalUrl: previewLink,
1537
- title: resolvedTitle,
1538
- description: resolvedDescription,
1539
- previewType: 5,
1540
- jpegThumbnail: smallThumb || undefined,
1541
- ...(hq
1542
- ? {
1543
- thumbnailDirectPath: hq.directPath,
1544
- mediaKey: hq.mediaKey,
1545
- mediaKeyTimestamp: hq.mediaKeyTimestamp,
1546
- thumbnailWidth: hq.width,
1547
- thumbnailHeight: hq.height,
1548
- thumbnailSha256: hq.fileSha256,
1549
- thumbnailEncSha256: hq.fileEncSha256
1550
- }
1551
- : {}),
1552
- ...restContent
1553
- };
1554
-
1555
- if (quoted) {
1556
- extendedText.contextInfo = {
1557
- ...(extendedText.contextInfo || {}),
1558
- stanzaId: quoted.key.id,
1559
- participant: jidNormalizedUser(quoted.key.fromMe ? userJid : (quoted.key.participant || quoted.key.remoteJid)),
1560
- quotedMessage: quoted.message
1561
- };
1562
- }
1563
-
1564
- if (isGroupStatus) {
1565
- extendedText.contextInfo = { ...(extendedText.contextInfo || {}), isGroupStatus: true };
1566
- }
1567
-
1568
- const previewMessage = isGroupStatus
1569
- ? { groupStatusMessageV2: { message: { extendedTextMessage: extendedText } } }
1570
- : { extendedTextMessage: extendedText };
1571
-
1572
- const msgId = options.messageId || generateMessageIDV2(userJid);
1573
-
1574
- await relayMessage(jid, previewMessage, {
1575
- messageId: msgId,
1576
- additionalAttributes: options.additionalAttributes || {},
1577
- additionalNodes: options.additionalNodes || []
1578
- });
1579
-
1580
- const fullMsg = {
1581
- key: {
1582
- remoteJid: jid,
1583
- fromMe: true,
1584
- id: msgId
1585
- },
1586
- message: previewMessage,
1587
- messageTimestamp: unixTimestampSeconds()
1588
- };
1589
-
1590
- if (config.emitOwnEvents) {
1591
- process.nextTick(async () => {
1592
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1593
- });
1594
- }
1595
- return fullMsg;
1596
- }
1597
- else if ('likeThis' in content && content.likeThis === true) {
1598
- const { likeThis: _, ...rawMessage } = content;
1599
- const msgId = options.messageId || generateMessageIDV2(userJid);
1600
-
1601
- await relayMessage(jid, rawMessage, {
1602
- messageId: msgId,
1603
- additionalAttributes: options.additionalAttributes || {},
1604
- additionalNodes: options.additionalNodes || []
1605
- });
1606
-
1607
- const fullMsg = {
1608
- key: {
1609
- remoteJid: jid,
1610
- fromMe: true,
1611
- id: msgId
1612
- },
1613
- message: rawMessage,
1614
- messageTimestamp: unixTimestampSeconds()
1615
- };
1616
-
1617
- if (config.emitOwnEvents) {
1618
- process.nextTick(async () => {
1619
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1620
- });
1621
- }
1622
- return fullMsg;
1623
- }
1624
- // ── NORMAL MESSAGE HANDLING ──
1625
- else {
1626
- const fullMsg = await generateWAMessage(jid, content, {
1627
- logger,
1628
- userJid,
1629
- upload: waUploadToServer,
1630
- mediaCache: config.mediaCache,
1631
- options: config.options,
1632
- ...options,
1633
- messageId: generateMessageIDV2(userJid)
1634
- });
1635
-
1636
- const isNewsletter = isJidNewsletter(jid);
1637
- const isEventMsg = 'event' in content && !!content.event;
1638
- const isDeleteMsg = 'delete' in content && !!content.delete;
1639
- const isEditMsg = 'edit' in content && !!content.edit;
1640
- const isPinMsg = 'pin' in content && !!content.pin;
1641
- const isKeepMsg = 'keep' in content && !!content.keep;
1642
- const isPollMsg = 'poll' in content && !!content.poll;
1643
- const isQuizMsg = 'poll' in content && !!content.poll.pollType;
1644
- const isAiMsg = 'ai' in content && !!content.ai;
1645
- const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1646
- delete content.secureMetaServiceLabel;
1647
- const additionalAttributes = options.additionalAttributes || {};
1648
- const additionalNodes = options.additionalNodes || [];
1649
-
1650
- if (isDeleteMsg || isKeepMsg) {
1651
- if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1652
- additionalAttributes.edit = '8';
1653
- }
1654
- else {
1655
- additionalAttributes.edit = '7';
1656
- }
1657
- }
1658
- else if (isEditMsg) {
1659
- additionalAttributes.edit = isNewsletter ? '3' : '1';
1660
- }
1661
- else if (isPinMsg) {
1662
- additionalAttributes.edit = '2';
1663
- }
1664
- else if (isPollMsg) {
1665
- if (!isNewsletter && isQuizMsg) {
1666
- throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
1667
- }
1668
- additionalNodes.push({
1669
- tag: 'meta',
1670
- attrs: {
1671
- polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1672
- contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1673
- },
1674
- content: undefined
1675
- });
1676
- }
1677
- else if (isEventMsg) {
1678
- additionalNodes.push({
1679
- tag: 'meta',
1680
- attrs: {
1681
- event_type: 'creation'
1682
- },
1683
- content: undefined
1684
- });
1685
- }
1686
- else if (isAiMsg) {
1687
- if (!(isPnUser(jid) || isLidUser(jid))) {
1688
- throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1689
- }
1690
- if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1691
- fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1692
- }
1693
- additionalNodes.push({
1694
- tag: 'bot',
1695
- attrs: {
1696
- biz_bot: '1'
1697
- },
1698
- content: undefined
1699
- });
1700
- delete content.ai;
1701
- }
1702
-
1703
- await relayMessage(jid, fullMsg.message, {
1704
- messageId: fullMsg.key.id,
1705
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1706
- addBizAttributes: isNeedBizAttrs,
1707
- statusJidList: options.statusJidList,
1708
- additionalAttributes,
1709
- additionalNodes
1710
- });
1711
-
1712
- if (config.emitOwnEvents) {
1713
- process.nextTick(async () => {
1714
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1715
- });
1716
- }
1717
-
1718
- if ('album' in content) {
1719
- const { delayMs = 1500 } = options;
1720
- for (const albumMedia of content.album) {
1721
- const albumMsg = await generateWAMessage(jid, albumMedia, {
1722
- logger,
1723
- userJid,
1724
- upload: waUploadToServer,
1725
- mediaCache: config.mediaCache,
1726
- options: config.options,
1727
- ...options,
1728
- messageId: generateMessageIDV2(userJid)
1729
- });
1730
- if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
1731
- throw new Boom('Invalid message type for album', { statusCode: 400 });
1732
- }
1733
- albumMsg.message.messageContextInfo ||= {};
1734
- albumMsg.message.messageContextInfo.messageAssociation = {
1735
- parentMessageKey: fullMsg.key,
1736
- associationType: AssociationType.MEDIA_ALBUM
1737
- };
1738
- await relayMessage(jid, albumMsg.message, {
1739
- messageId: albumMsg.key.id,
1740
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1741
- addBizAttributes: isNeedBizAttrs,
1742
- statusJidList: options.statusJidList,
1743
- additionalAttributes,
1744
- additionalNodes
1745
- });
1746
- if (config.emitOwnEvents) {
1747
- process.nextTick(async () => {
1748
- await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
1749
- });
1750
- }
1751
- await delay(delayMs);
1752
- }
1753
- }
1754
-
1755
- return fullMsg;
1756
- }
1757
- }
1758
- }
1759
- };