wertybailz 1.0.9 → 1.0.11

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.
@@ -12,46 +12,34 @@ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
12
  import { makeNewsletterSocket } from './newsletter.js';
13
13
  import imup from './luxu.js';
14
14
  import * as Utils_1 from '../Utils/index.js';
15
+
15
16
  export const makeMessagesSocket = (config) => {
16
17
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount, aiLabel } = config;
17
18
  const sock = makeNewsletterSocket(config);
18
19
  const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
19
20
  const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
20
- /**
21
- * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
22
- * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
23
- * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
24
- */
25
21
  const inFlightTcTokenIssuance = new Set();
26
22
  const userDevicesCache = config.userDevicesCache ||
27
23
  new NodeCache({
28
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
24
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
29
25
  useClones: false
30
26
  });
31
- /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
32
27
  const devicesMutex = makeMutex();
33
- // Initialize message retry manager if enabled
34
28
  const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
35
- // Prevent race conditions in Signal session encryption by user
36
29
  const encryptionMutex = makeKeyedMutex();
37
30
  let mediaConn;
38
- /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
39
31
  let mediaHost = DEF_MEDIA_HOST;
32
+
40
33
  const refreshMediaConn = async (forceGet = false) => {
41
34
  const media = await mediaConn;
42
35
  if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
43
36
  mediaConn = (async () => {
44
37
  const result = await query({
45
38
  tag: 'iq',
46
- attrs: {
47
- type: 'set',
48
- xmlns: 'w:m',
49
- to: S_WHATSAPP_NET
50
- },
39
+ attrs: { type: 'set', xmlns: 'w:m', to: S_WHATSAPP_NET },
51
40
  content: [{ tag: 'media_conn', attrs: {} }]
52
41
  });
53
42
  const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
54
- // TODO: explore full length of data that whatsapp provides
55
43
  const node = {
56
44
  hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
57
45
  hostname: attrs.hostname,
@@ -62,155 +50,111 @@ export const makeMessagesSocket = (config) => {
62
50
  fetchDate: new Date()
63
51
  };
64
52
  logger.debug('fetched media conn');
65
- if (node.hosts[0]) {
66
- mediaHost = node.hosts[0].hostname;
67
- }
53
+ if (node.hosts[0]) mediaHost = node.hosts[0].hostname;
68
54
  return node;
69
55
  })();
70
56
  }
71
57
  return mediaConn;
72
58
  };
73
- /**
74
- * generic send receipt function
75
- * used for receipts of phone call, read, delivery etc.
76
- * */
59
+
77
60
  const sendReceipt = async (jid, participant, messageIds, type) => {
78
- if (!messageIds || messageIds.length === 0) {
79
- throw new Boom('missing ids in receipt');
80
- }
81
- const node = {
82
- tag: 'receipt',
83
- attrs: {
84
- id: messageIds[0]
85
- }
86
- };
61
+ if (!messageIds || messageIds.length === 0) throw new Boom('missing ids in receipt');
62
+ const node = { tag: 'receipt', attrs: { id: messageIds[0] } };
87
63
  const isReadReceipt = type === 'read' || type === 'read-self';
88
- if (isReadReceipt) {
89
- node.attrs.t = unixTimestampSeconds().toString();
90
- }
64
+ if (isReadReceipt) node.attrs.t = unixTimestampSeconds().toString();
91
65
  if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
92
66
  node.attrs.recipient = jid;
93
67
  node.attrs.to = participant;
94
- }
95
- else {
68
+ } else {
96
69
  node.attrs.to = jid;
97
- if (participant) {
98
- node.attrs.participant = participant;
99
- }
100
- }
101
- if (type) {
102
- node.attrs.type = type;
70
+ if (participant) node.attrs.participant = participant;
103
71
  }
72
+ if (type) node.attrs.type = type;
104
73
  const remainingMessageIds = messageIds.slice(1);
105
74
  if (remainingMessageIds.length) {
106
- node.content = [
107
- {
108
- tag: 'list',
109
- attrs: {},
110
- content: remainingMessageIds.map(id => ({
111
- tag: 'item',
112
- attrs: { id }
113
- }))
114
- }
115
- ];
75
+ node.content = [{
76
+ tag: 'list',
77
+ attrs: {},
78
+ content: remainingMessageIds.map(id => ({ tag: 'item', attrs: { id } }))
79
+ }];
116
80
  }
117
81
  logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
118
82
  await sendNode(node);
119
83
  };
120
- /** Correctly bulk send receipts to multiple chats, participants */
84
+
121
85
  const sendReceipts = async (keys, type) => {
122
86
  const recps = aggregateMessageKeysNotFromMe(keys);
123
87
  for (const { jid, participant, messageIds } of recps) {
124
88
  await sendReceipt(jid, participant, messageIds, type);
125
89
  }
126
90
  };
127
- /** Bulk read messages. Keys can be from different chats & participants */
91
+
128
92
  const readMessages = async (keys) => {
129
93
  const privacySettings = await fetchPrivacySettings();
130
- // based on privacy settings, we have to change the read type
131
94
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
132
95
  await sendReceipts(keys, readType);
133
96
  };
134
- /** Fetch all the devices we've to send a message to */
97
+
135
98
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
136
99
  const deviceResults = [];
137
- if (!useCache) {
138
- logger.debug('not using cache for devices');
139
- }
100
+ if (!useCache) logger.debug('not using cache for devices');
140
101
  const toFetch = [];
141
- const jidsWithUser = jids
142
- .map(jid => {
102
+ const jidsWithUser = jids.map(jid => {
143
103
  const decoded = jidDecode(jid);
144
104
  const user = decoded?.user;
145
105
  const device = decoded?.device;
146
106
  const isExplicitDevice = typeof device === 'number' && device >= 0;
147
107
  if (isExplicitDevice && user) {
148
- deviceResults.push({
149
- user,
150
- device,
151
- jid
152
- });
108
+ deviceResults.push({ user, device, jid });
153
109
  return null;
154
110
  }
155
111
  jid = jidNormalizedUser(jid);
156
112
  return { jid, user };
157
- })
158
- .filter(jid => jid !== null);
113
+ }).filter(jid => jid !== null);
114
+
159
115
  let mgetDevices;
160
116
  if (useCache && userDevicesCache.mget) {
161
117
  const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
162
118
  mgetDevices = await userDevicesCache.mget(usersToFetch);
163
119
  }
120
+
164
121
  for (const { jid, user } of jidsWithUser) {
165
122
  if (useCache) {
166
- const devices = mgetDevices?.[user] ||
167
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
123
+ const devices = mgetDevices?.[user] || (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
168
124
  if (devices) {
169
- const devicesWithJid = devices.map(d => ({
170
- ...d,
171
- jid: jidEncode(d.user, d.server, d.device)
172
- }));
173
- deviceResults.push(...devicesWithJid);
125
+ deviceResults.push(...devices.map(d => ({ ...d, jid: jidEncode(d.user, d.server, d.device) })));
174
126
  logger.trace({ user }, 'using cache for devices');
175
- }
176
- else {
127
+ } else {
177
128
  toFetch.push(jid);
178
129
  }
179
- }
180
- else {
130
+ } else {
181
131
  toFetch.push(jid);
182
132
  }
183
133
  }
184
- if (!toFetch.length) {
185
- return deviceResults;
186
- }
134
+
135
+ if (!toFetch.length) return deviceResults;
136
+
187
137
  const requestedLidUsers = new Set();
188
138
  for (const jid of toFetch) {
189
139
  if (isLidUser(jid) || isHostedLidUser(jid)) {
190
140
  const user = jidDecode(jid)?.user;
191
- if (user)
192
- requestedLidUsers.add(user);
141
+ if (user) requestedLidUsers.add(user);
193
142
  }
194
143
  }
144
+
195
145
  const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
196
- for (const jid of toFetch) {
197
- query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
198
- }
146
+ for (const jid of toFetch) query.withUser(new USyncUser().withId(jid));
199
147
  const result = await sock.executeUSyncQuery(query);
148
+
200
149
  if (result) {
201
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
202
150
  const lidResults = result.list.filter(a => !!a.lid);
203
151
  if (lidResults.length > 0) {
204
152
  logger.trace('Storing LID maps from device call');
205
153
  await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
206
- // Force-refresh sessions for newly mapped LIDs to align identity addressing
207
154
  try {
208
155
  const lids = lidResults.map(a => a.lid);
209
- if (lids.length) {
210
- await assertSessions(lids, true);
211
- }
212
- }
213
- catch (e) {
156
+ if (lids.length) await assertSessions(lids, true);
157
+ } catch (e) {
214
158
  logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
215
159
  }
216
160
  }
@@ -220,132 +164,85 @@ export const makeMessagesSocket = (config) => {
220
164
  deviceMap[item.user] = deviceMap[item.user] || [];
221
165
  deviceMap[item.user]?.push(item);
222
166
  }
223
- // Process each user's devices as a group for bulk LID migration
224
167
  for (const [user, userDevices] of Object.entries(deviceMap)) {
225
168
  const isLidUser = requestedLidUsers.has(user);
226
- // Process all devices for this user
227
169
  for (const item of userDevices) {
228
- const finalJid = isLidUser
229
- ? jidEncode(user, item.server, item.device)
230
- : jidEncode(item.user, item.server, item.device);
231
- deviceResults.push({
232
- ...item,
233
- jid: finalJid
234
- });
235
- logger.debug({
236
- user: item.user,
237
- device: item.device,
238
- finalJid,
239
- usedLid: isLidUser
240
- }, 'Processed device with LID priority');
170
+ const finalJid = isLidUser ? jidEncode(user, item.server, item.device) : jidEncode(item.user, item.server, item.device);
171
+ deviceResults.push({ ...item, jid: finalJid });
241
172
  }
242
173
  }
243
174
  await devicesMutex.mutex(async () => {
244
175
  if (userDevicesCache.mset) {
245
- // if the cache supports mset, we can set all devices in one go
246
176
  await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
247
- }
248
- else {
177
+ } else {
249
178
  for (const key in deviceMap) {
250
- if (deviceMap[key])
251
- await userDevicesCache.set(key, deviceMap[key]);
179
+ if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key]);
252
180
  }
253
181
  }
254
182
  });
255
183
  const userDeviceUpdates = {};
256
184
  for (const [userId, devices] of Object.entries(deviceMap)) {
257
- if (devices && devices.length > 0) {
258
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
259
- }
185
+ if (devices && devices.length > 0) userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
260
186
  }
261
187
  if (Object.keys(userDeviceUpdates).length > 0) {
262
188
  try {
263
189
  await authState.keys.set({ 'device-list': userDeviceUpdates });
264
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
265
- }
266
- catch (error) {
190
+ } catch (error) {
267
191
  logger.warn({ error }, 'failed to store user device lists');
268
192
  }
269
193
  }
270
194
  }
271
195
  return deviceResults;
272
196
  };
273
- /**
274
- * Update Member Label
275
- */
197
+
276
198
  const updateMemberLabel = (jid, memberLabel) => {
277
199
  return relayMessage(jid, {
278
200
  protocolMessage: {
279
201
  type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
280
- memberLabel: {
281
- label: memberLabel?.slice(0, 30),
282
- labelTimestamp: unixTimestampSeconds()
283
- }
202
+ memberLabel: { label: memberLabel?.slice(0, 30), labelTimestamp: unixTimestampSeconds() }
284
203
  }
285
204
  }, {
286
- additionalNodes: [
287
- {
288
- tag: 'meta',
289
- attrs: {
290
- tag_reason: 'user_update',
291
- appdata: 'member_tag'
292
- },
293
- content: undefined
294
- }
295
- ]
205
+ additionalNodes: [{ tag: 'meta', attrs: { tag_reason: 'user_update', appdata: 'member_tag' }, content: undefined }]
296
206
  });
297
207
  };
208
+
298
209
  const assertSessions = async (jids, force) => {
299
210
  let didFetchNewSession = false;
300
211
  const uniqueJids = [...new Set(jids)];
301
212
  const jidsRequiringFetch = [];
302
- logger.debug({ jids }, 'assertSessions call with jids');
303
213
  for (const jid of uniqueJids) {
304
214
  if (!force) {
305
215
  const sessionValidation = await signalRepository.validateSession(jid);
306
- if (sessionValidation.exists) {
307
- continue;
308
- }
216
+ if (sessionValidation.exists) continue;
309
217
  }
310
218
  jidsRequiringFetch.push(jid);
311
219
  }
312
220
  if (jidsRequiringFetch.length) {
313
- // LID if mapped, otherwise original
314
221
  const wireJids = [
315
222
  ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
316
223
  ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
317
224
  ];
318
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
319
225
  const result = await query({
320
226
  tag: 'iq',
321
- attrs: {
322
- xmlns: 'encrypt',
323
- type: 'get',
324
- to: S_WHATSAPP_NET
325
- },
326
- content: [
327
- {
328
- tag: 'key',
329
- attrs: {},
330
- content: wireJids.map(jid => {
331
- const attrs = { jid };
332
- if (force)
333
- attrs.reason = 'identity';
334
- return { tag: 'user', attrs };
335
- })
336
- }
337
- ]
227
+ attrs: { xmlns: 'encrypt', type: 'get', to: S_WHATSAPP_NET },
228
+ content: [{
229
+ tag: 'key',
230
+ attrs: {},
231
+ content: wireJids.map(jid => {
232
+ const attrs = { jid };
233
+ if (force) attrs.reason = 'identity';
234
+ return { tag: 'user', attrs };
235
+ })
236
+ }]
338
237
  });
339
238
  await parseAndInjectE2ESessions(result, signalRepository);
340
239
  didFetchNewSession = true;
341
240
  }
342
241
  return didFetchNewSession;
343
242
  };
243
+
344
244
  const sendPeerDataOperationMessage = async (pdoMessage) => {
345
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
346
- if (!authState.creds.me?.id) {
347
- throw new Boom('Not authenticated');
348
- }
245
+ if (!authState.creds.me?.id) throw new Boom('Not authenticated');
349
246
  const protocolMessage = {
350
247
  protocolMessage: {
351
248
  peerDataOperationRequestMessage: pdoMessage,
@@ -353,36 +250,23 @@ export const makeMessagesSocket = (config) => {
353
250
  }
354
251
  };
355
252
  const meJid = jidNormalizedUser(authState.creds.me.id);
356
- const msgId = await relayMessage(meJid, protocolMessage, {
357
- additionalAttributes: {
358
- category: 'peer',
359
- push_priority: 'high_force'
360
- },
361
- additionalNodes: [
362
- {
363
- tag: 'meta',
364
- attrs: { appdata: 'default' }
365
- }
366
- ]
253
+ return await relayMessage(meJid, protocolMessage, {
254
+ additionalAttributes: { category: 'peer', push_priority: 'high_force' },
255
+ additionalNodes: [{ tag: 'meta', attrs: { appdata: 'default' } }]
367
256
  });
368
- return msgId;
369
257
  };
258
+
370
259
  const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
371
- if (!recipientJids.length) {
372
- return { nodes: [], shouldIncludeDeviceIdentity: false };
373
- }
260
+ if (!recipientJids.length) return { nodes: [], shouldIncludeDeviceIdentity: false };
374
261
  const patched = await patchMessageBeforeSending(message, recipientJids);
375
- const patchedMessages = Array.isArray(patched)
376
- ? patched
377
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
262
+ const patchedMessages = Array.isArray(patched) ? patched : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
378
263
  let shouldIncludeDeviceIdentity = false;
379
264
  const meId = authState.creds.me.id;
380
265
  const meLid = authState.creds.me?.lid;
381
266
  const meLidUser = meLid ? jidDecode(meLid)?.user : null;
382
267
  const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
383
268
  try {
384
- if (!jid)
385
- return null;
269
+ if (!jid) return null;
386
270
  let msgToEncrypt = patchedMessage;
387
271
  if (dsmMessage) {
388
272
  const { user: targetUser } = jidDecode(jid);
@@ -396,530 +280,376 @@ export const makeMessagesSocket = (config) => {
396
280
  }
397
281
  }
398
282
  const bytes = encodeWAMessage(msgToEncrypt);
399
- const mutexKey = jid;
400
- const node = await encryptionMutex.mutex(mutexKey, async () => {
283
+ const node = await encryptionMutex.mutex(jid, async () => {
401
284
  const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
402
- if (type === 'pkmsg') {
403
- shouldIncludeDeviceIdentity = true;
404
- }
285
+ if (type === 'pkmsg') shouldIncludeDeviceIdentity = true;
405
286
  return {
406
287
  tag: 'to',
407
288
  attrs: { jid },
408
- content: [
409
- {
410
- tag: 'enc',
411
- attrs: { v: '2', type, ...(extraAttrs || {}) },
412
- content: ciphertext
413
- }
414
- ]
289
+ content: [{ tag: 'enc', attrs: { v: '2', type, ...(extraAttrs || {}) }, content: ciphertext }]
415
290
  };
416
291
  });
417
292
  return node;
418
- }
419
- catch (err) {
293
+ } catch (err) {
420
294
  logger.error({ jid, err }, 'Failed to encrypt for recipient');
421
295
  return null;
422
296
  }
423
297
  });
424
298
  const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
425
- if (recipientJids.length > 0 && nodes.length === 0) {
426
- throw new Boom('All encryptions failed', { statusCode: 500 });
427
- }
299
+ if (recipientJids.length > 0 && nodes.length === 0) throw new Boom('All encryptions failed', { statusCode: 500 });
428
300
  return { nodes, shouldIncludeDeviceIdentity };
429
301
  };
302
+
430
303
  const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
431
- const meId = assertMeId(authState.creds)
432
- const meLid = authState.creds.me?.lid
433
- const isRetryResend = Boolean(participant?.jid)
434
- let shouldIncludeDeviceIdentity = isRetryResend
435
- const statusJid = 'status@broadcast'
436
- const { user, server } = jidDecode(jid)
437
- const isGroup = server === 'g.us'
438
- const isStatus = jid === statusJid
439
- const isLid = server === 'lid'
440
- const isNewsletter = server === 'newsletter'
441
- const isGroupOrStatus = isGroup || isStatus
442
- const finalJid = jid
443
- msgId = msgId || generateMessageIDV2(meId)
444
- useUserDevicesCache = useUserDevicesCache!== false
445
- useCachedGroupMetadata = useCachedGroupMetadata!== false &&!isStatus
446
- const participants = []
447
- const destinationJid = !isStatus? finalJid : statusJid
448
- const binaryNodeContent = []
449
- const devices = []
450
- const buttonType = getButtonType(message)
451
- let didPushAdditional = false
452
- let reportingMessage
453
- const meMsg = {
454
- deviceSentMessage: {
455
- destinationJid,
456
- message
457
- },
458
- messageContextInfo: message.messageContextInfo
459
- }
460
- const extraAttrs = {}
461
- if (participant) {
462
- if (!isGroup &&!isStatus) {
463
- additionalAttributes = {...additionalAttributes, device_fanout: 'false' }
464
- }
465
- const { user, device } = jidDecode(participant.jid)
466
- devices.push({ user, device, jid: participant.jid })
467
- }
468
- await authState.keys.transaction(async () => {
469
- const mediaType = getMediaType(message)
470
- if (mediaType) {
471
- extraAttrs['mediatype'] = mediaType
472
- }
473
- if (isNewsletter) {
474
- const patched = patchMessageBeforeSending? await patchMessageBeforeSending(message, []) : message
475
- const bytes = encodeNewsletterMessage(patched)
476
- binaryNodeContent.push({
477
- tag: 'plaintext',
478
- attrs: {},
479
- content: bytes
480
- })
481
- const stanza = {
482
- tag: 'message',
483
- attrs: {
484
- to: jid,
485
- id: msgId,
486
- type: getMessageType(message),
487
- ...(additionalAttributes || {})
488
- },
489
- content: binaryNodeContent
490
- }
491
- logger.debug({ msgId }, `sending newsletter message to ${jid}`)
492
- await sendNode(stanza)
493
- return
494
- }
495
- if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
496
- extraAttrs['decrypt-fail'] = 'hide'
304
+ const meId = assertMeId(authState.creds);
305
+ const meLid = authState.creds.me?.lid;
306
+ const isRetryResend = Boolean(participant?.jid);
307
+ let shouldIncludeDeviceIdentity = isRetryResend;
308
+ const statusJid = 'status@broadcast';
309
+ const { user, server } = jidDecode(jid);
310
+ const isGroup = server === 'g.us';
311
+ const isStatus = jid === statusJid;
312
+ const isLid = server === 'lid';
313
+ const isNewsletter = server === 'newsletter';
314
+ const isGroupOrStatus = isGroup || isStatus;
315
+ const finalJid = jid;
316
+ msgId = msgId || generateMessageIDV2(meId);
317
+ useUserDevicesCache = useUserDevicesCache !== false;
318
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
319
+ const participants = [];
320
+ const destinationJid = !isStatus ? finalJid : statusJid;
321
+ const binaryNodeContent = [];
322
+ const devices = [];
323
+ const buttonType = getButtonType(message);
324
+ let didPushAdditional = false;
325
+ let reportingMessage;
326
+ const meMsg = { deviceSentMessage: { destinationJid, message }, messageContextInfo: message.messageContextInfo };
327
+ const extraAttrs = {};
328
+
329
+ if (participant) {
330
+ if (!isGroup && !isStatus) additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
331
+ const { user, device } = jidDecode(participant.jid);
332
+ devices.push({ user, device, jid: participant.jid });
497
333
  }
498
- if (isGroupOrStatus &&!isRetryResend) {
499
- const [groupData, senderKeyMap] = await Promise.all([
500
- (async () => {
501
- let groupData = useCachedGroupMetadata && cachedGroupMetadata? await cachedGroupMetadata(jid) : undefined
502
- if (groupData && Array.isArray(groupData?.participants)) {
503
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
504
- } else if (!isStatus) {
505
- groupData = await groupMetadata(jid)
506
- }
507
- return groupData
508
- })(),
509
- (async () => {
510
- if (!participant &&!isStatus) {
511
- const result = await authState.keys.get('sender-key-memory', [jid])
512
- return result[jid] || {}
513
- }
514
- return {}
515
- })()
516
- ])
517
- const participantsList = groupData? groupData.participants.map(p => p.id) : []
518
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
519
- additionalAttributes = {...additionalAttributes, expiration: groupData.ephemeralDuration.toString() }
520
- }
521
- if (isStatus && statusJidList) {
522
- participantsList.push(...statusJidList)
523
- }
524
- const additionalDevices = await getUSyncDevices(participantsList,!!useUserDevicesCache, false)
525
- devices.push(...additionalDevices)
526
- if (isGroup) {
527
- additionalAttributes = {...additionalAttributes, addressing_mode: groupData?.addressingMode || 'lid' }
528
- }
529
- const patched = await patchMessageBeforeSending(message)
530
- if (Array.isArray(patched)) {
531
- throw new Boom('Per-jid patching is not supported in groups')
532
- }
533
- const bytes = encodeWAMessage(patched)
534
- reportingMessage = patched
535
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
536
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid? meLid : meId
537
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
538
- group: destinationJid,
539
- data: bytes,
540
- meId: groupSenderIdentity
541
- })
542
- const senderKeyRecipients = []
543
- for (const device of devices) {
544
- const deviceJid = device.jid
545
- const hasKey = !!senderKeyMap[deviceJid]
546
- if ((!hasKey || !!participant) &&!isHostedLidUser(deviceJid) &&!isHostedPnUser(deviceJid) && device.device !== 99) {
547
- senderKeyRecipients.push(deviceJid)
548
- senderKeyMap[deviceJid] = true
549
- }
550
- }
551
- if (senderKeyRecipients.length) {
552
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
553
- const senderKeyMsg = {
554
- senderKeyDistributionMessage: {
555
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
556
- groupId: destinationJid
557
- }
334
+
335
+ await authState.keys.transaction(async () => {
336
+ const mediaType = getMediaType(message);
337
+ if (mediaType) extraAttrs['mediatype'] = mediaType;
338
+
339
+ if (isNewsletter) {
340
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
341
+ const bytes = encodeNewsletterMessage(patched);
342
+ binaryNodeContent.push({ tag: 'plaintext', attrs: {}, content: bytes });
343
+ const stanza = {
344
+ tag: 'message',
345
+ attrs: { to: jid, id: msgId, type: getMessageType(message), ...(additionalAttributes || {}) },
346
+ content: binaryNodeContent
347
+ };
348
+ await sendNode(stanza);
349
+ return;
558
350
  }
559
- const senderKeySessionTargets = senderKeyRecipients
560
- await assertSessions(senderKeySessionTargets)
561
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
562
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
563
- participants.push(...result.nodes)
564
- }
565
- binaryNodeContent.push({
566
- tag: 'enc',
567
- attrs: { v: '2', type: 'skmsg',...extraAttrs },
568
- content: ciphertext
569
- })
570
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
571
- } else {
572
- let ownId = meId
573
- if (isLid && meLid) {
574
- ownId = meLid
575
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
576
- } else {
577
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
578
- }
579
- const { user: ownUser } = jidDecode(ownId)
580
- if (!participant) {
581
- const patchedForReporting = await patchMessageBeforeSending(message, [jid])
582
- reportingMessage = Array.isArray(patchedForReporting)
583
- ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
584
- : patchedForReporting
585
- }
586
- if (!isRetryResend) {
587
- const targetUserServer = isLid? 'lid' : 's.whatsapp.net'
588
- devices.push({
589
- user,
590
- device: 0,
591
- jid: jidEncode(user, targetUserServer, 0)
592
- })
593
- if (user !== ownUser) {
594
- const ownUserServer = isLid? 'lid' : 's.whatsapp.net'
595
- const ownUserForAddressing = isLid && meLid? jidDecode(meLid).user : jidDecode(meId).user
596
- devices.push({
597
- user: ownUserForAddressing,
598
- device: 0,
599
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
600
- })
351
+
352
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
353
+ extraAttrs['decrypt-fail'] = 'hide';
601
354
  }
602
- if (additionalAttributes?.['category'] !== 'peer') {
603
- devices.length = 0
604
- const senderIdentity = isLid && meLid
605
- ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
606
- : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined)
607
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
608
- devices.push(...sessionDevices)
609
- logger.debug({
610
- deviceCount: devices.length,
611
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
612
- }, 'Device enumeration complete with unified addressing')
355
+
356
+ if (isGroupOrStatus && !isRetryResend) {
357
+ const [groupData, senderKeyMap] = await Promise.all([
358
+ (async () => {
359
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
360
+ if (groupData && Array.isArray(groupData?.participants)) {
361
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
362
+ } else if (!isStatus) {
363
+ groupData = await groupMetadata(jid);
364
+ }
365
+ return groupData;
366
+ })(),
367
+ (async () => {
368
+ if (!participant && !isStatus) {
369
+ const result = await authState.keys.get('sender-key-memory', [jid]);
370
+ return result[jid] || {};
371
+ }
372
+ return {};
373
+ })()
374
+ ]);
375
+
376
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
377
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
378
+ additionalAttributes = { ...additionalAttributes, expiration: groupData.ephemeralDuration.toString() };
379
+ }
380
+ if (isStatus && statusJidList) participantsList.push(...statusJidList);
381
+
382
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
383
+ devices.push(...additionalDevices);
384
+ if (isGroup) additionalAttributes = { ...additionalAttributes, addressing_mode: groupData?.addressingMode || 'lid' };
385
+
386
+ const patched = await patchMessageBeforeSending(message);
387
+ if (Array.isArray(patched)) throw new Boom('Per-jid patching is not supported in groups');
388
+ const bytes = encodeWAMessage(patched);
389
+ reportingMessage = patched;
390
+
391
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
392
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
393
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
394
+ group: destinationJid, data: bytes, meId: groupSenderIdentity
395
+ });
396
+
397
+ const senderKeyRecipients = [];
398
+ for (const device of devices) {
399
+ const deviceJid = device.jid;
400
+ const hasKey = !!senderKeyMap[deviceJid];
401
+ if ((!hasKey || !!participant) && !isHostedLidUser(deviceJid) && !isHostedPnUser(deviceJid) && device.device !== 99) {
402
+ senderKeyRecipients.push(deviceJid);
403
+ senderKeyMap[deviceJid] = true;
404
+ }
405
+ }
406
+
407
+ if (senderKeyRecipients.length) {
408
+ const senderKeyMsg = {
409
+ senderKeyDistributionMessage: {
410
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
411
+ groupId: destinationJid
412
+ }
413
+ };
414
+ await assertSessions(senderKeyRecipients);
415
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
416
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
417
+ participants.push(...result.nodes);
418
+ }
419
+
420
+ binaryNodeContent.push({ tag: 'enc', attrs: { v: '2', type: 'skmsg', ...extraAttrs }, content: ciphertext });
421
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
422
+ } else {
423
+ let ownId = meId;
424
+ if (isLid && meLid) {
425
+ ownId = meLid;
426
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
427
+ }
428
+ const { user: ownUser } = jidDecode(ownId);
429
+ if (!participant) {
430
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
431
+ reportingMessage = Array.isArray(patchedForReporting)
432
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
433
+ : patchedForReporting;
434
+ }
435
+ if (!isRetryResend) {
436
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
437
+ devices.push({ user, device: 0, jid: jidEncode(user, targetUserServer, 0) });
438
+ if (user !== ownUser) {
439
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
440
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
441
+ devices.push({ user: ownUserForAddressing, device: 0, jid: jidEncode(ownUserForAddressing, ownUserServer, 0) });
442
+ }
443
+ if (additionalAttributes?.['category'] !== 'peer') {
444
+ devices.length = 0;
445
+ const senderIdentity = isLid && meLid
446
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
447
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
448
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
449
+ devices.push(...sessionDevices);
450
+ }
451
+ }
452
+
453
+ const allRecipients = [], meRecipients = [], otherRecipients = [];
454
+ const { user: mePnUser } = jidDecode(meId);
455
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
456
+ for (const { user, jid } of devices) {
457
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
458
+ if (isExactSenderDevice) continue;
459
+ const isMe = user === mePnUser || user === meLidUser;
460
+ if (isMe) meRecipients.push(jid); else otherRecipients.push(jid);
461
+ allRecipients.push(jid);
462
+ }
463
+
464
+ await assertSessions(allRecipients);
465
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
466
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
467
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
468
+ ]);
469
+ participants.push(...meNodes);
470
+ participants.push(...otherNodes);
471
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
472
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
473
+ }
474
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
613
475
  }
614
- }
615
- const allRecipients = []
616
- const meRecipients = []
617
- const otherRecipients = []
618
- const { user: mePnUser } = jidDecode(meId)
619
- const { user: meLidUser } = meLid? jidDecode(meLid) : { user: null }
620
- for (const { user, jid } of devices) {
621
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
622
- if (isExactSenderDevice) {
623
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
624
- continue
476
+
477
+ if (participants.length) {
478
+ if (additionalAttributes?.['category'] === 'peer') {
479
+ const peerNode = participants[0]?.content?.[0];
480
+ if (peerNode) binaryNodeContent.push(peerNode);
481
+ } else {
482
+ binaryNodeContent.push({ tag: 'participants', attrs: {}, content: participants });
483
+ }
625
484
  }
626
- const isMe = user === mePnUser || user === meLidUser
627
- if (isMe) {
628
- meRecipients.push(jid)
485
+
486
+ const stanza = {
487
+ tag: 'message',
488
+ attrs: { id: msgId, to: destinationJid, type: getMessageType(message), ...(additionalAttributes || {}) },
489
+ content: binaryNodeContent
490
+ };
491
+
492
+ if (participant) {
493
+ if (isJidGroup(destinationJid)) { stanza.attrs.to = destinationJid; stanza.attrs.participant = participant.jid; }
494
+ else if (areJidsSameUser(participant.jid, meId)) { stanza.attrs.to = participant.jid; stanza.attrs.recipient = destinationJid; }
495
+ else stanza.attrs.to = participant.jid;
629
496
  } else {
630
- otherRecipients.push(jid)
497
+ stanza.attrs.to = destinationJid;
631
498
  }
632
- allRecipients.push(jid)
633
- }
634
- await assertSessions(allRecipients)
635
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
636
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
637
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
638
- ])
639
- participants.push(...meNodes)
640
- participants.push(...otherNodes)
641
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
642
- extraAttrs['phash'] = generateParticipantHashV2([...meRecipients,...otherRecipients])
643
- }
644
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
645
- }
646
- if (participants.length) {
647
- if (additionalAttributes?.['category'] === 'peer') {
648
- const peerNode = participants[0]?.content?.[0]
649
- if (peerNode) {
650
- binaryNodeContent.push(peerNode)
499
+
500
+ if (shouldIncludeDeviceIdentity) {
501
+ stanza.content.push({ tag: 'device-identity', attrs: {}, content: encodeSignedDeviceIdentity(authState.creds.account, true) });
651
502
  }
652
- } else {
653
- binaryNodeContent.push({
654
- tag: 'participants',
655
- attrs: {},
656
- content: participants
657
- })
658
- }
659
- }
660
- const stanza = {
661
- tag: 'message',
662
- attrs: {
663
- id: msgId,
664
- to: destinationJid,
665
- type: getMessageType(message),
666
- ...(additionalAttributes || {})
667
- },
668
- content: binaryNodeContent
669
- }
670
- if (participant) {
671
- if (isJidGroup(destinationJid)) {
672
- stanza.attrs.to = destinationJid
673
- stanza.attrs.participant = participant.jid
674
- } else if (areJidsSameUser(participant.jid, meId)) {
675
- stanza.attrs.to = participant.jid
676
- stanza.attrs.recipient = destinationJid
677
- } else {
678
- stanza.attrs.to = participant.jid
679
- }
680
- } else {
681
- stanza.attrs.to = destinationJid
682
- }
683
- if (shouldIncludeDeviceIdentity) {
684
- stanza.content.push({
685
- tag: 'device-identity',
686
- attrs: {},
687
- content: encodeSignedDeviceIdentity(authState.creds.account, true)
688
- })
689
- logger.debug({ jid }, 'adding device identity')
690
- }
691
- if (!isNewsletter && buttonType &&!isStatus) {
692
- const content = getAdditionalNode(buttonType)
693
- const filteredNode = getBinaryNodeFilter(additionalNodes)
694
- if (filteredNode) {
695
- didPushAdditional = true
696
- stanza.content.push(...additionalNodes)
697
- } else {
698
- stanza.content.push(...content)
699
- }
700
- logger.debug({ jid }, 'adding business node')
701
- }
702
- if (!isNewsletter &&!isGroupOrStatus && aiLabel) {
703
- const botNode = { tag: 'bot', attrs: { biz_bot: '1' } }
704
- const filteredBizBot = getBinaryNodeFilter(additionalNodes? additionalNodes : [])
705
- if (filteredBizBot) {
706
- stanza.content.push(...additionalNodes)
707
- didPushAdditional = true
708
- } else {
709
- stanza.content.push(botNode)
710
- }
711
- }
712
- if (!isNewsletter &&!isRetryResend && reportingMessage?.messageContextInfo?.messageSecret && shouldIncludeReportingToken(reportingMessage)) {
713
- try {
714
- const encoded = encodeWAMessage(reportingMessage)
715
- const reportingKey = { id: msgId, fromMe: true, remoteJid: destinationJid, participant: participant?.jid }
716
- const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey)
717
- if (reportingNode) {
718
- stanza.content.push(reportingNode)
719
- logger.trace({ jid }, 'added reporting token to message')
503
+
504
+ if (!isNewsletter && buttonType && !isStatus) {
505
+ const content = getAdditionalNode(buttonType);
506
+ const filteredNode = getBinaryNodeFilter(additionalNodes);
507
+ if (filteredNode) { didPushAdditional = true; stanza.content.push(...additionalNodes); }
508
+ else stanza.content.push(...content);
720
509
  }
721
- } catch (error) {
722
- logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token')
723
- }
724
- }
725
- const isPeerMessage = additionalAttributes?.['category'] === 'peer'
726
- const is1on1Send = !isGroup &&!isRetryResend &&!isStatus &&!isNewsletter &&!isPeerMessage
727
- const tcTokenJid = is1on1Send? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid
728
- const contactTcTokenData = is1on1Send? await authState.keys.get('tctoken', [tcTokenJid]) : {}
729
- const existingTokenEntry = contactTcTokenData[tcTokenJid]
730
- let tcTokenBuffer = existingTokenEntry?.token
731
- if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
732
- logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing')
733
- tcTokenBuffer = undefined
734
- const cleared = existingTokenEntry?.senderTimestamp !== undefined
735
- ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
736
- : null
737
- try {
738
- await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } })
739
- } catch (err) {
740
- logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup')
741
- }
742
- }
743
- if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
744
- stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
745
- }
746
510
 
747
- if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
748
- stanza.content.push(...additionalNodes)
749
- }
750
- logger.debug({ msgId }, `sending message to ${participants.length} devices`)
751
- await sendNode(stanza)
752
- const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage
753
- const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid)
754
- if (is1on1Send &&!isProtocolMsg &&!isBotOrPSA && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&!inFlightTcTokenIssuance.has(tcTokenJid)) {
755
- inFlightTcTokenIssuance.add(tcTokenJid)
756
- const issueTimestamp = unixTimestampSeconds()
757
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
758
- resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
759
- .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
760
- .then(async (result) => {
761
- await storeTcTokensFromIqResult({ result, fallbackJid: tcTokenJid, keys: authState.keys, getLIDForPN })
762
- const currentData = await authState.keys.get('tctoken', [tcTokenJid])
763
- const currentEntry = currentData[tcTokenJid]
764
- const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
765
- await authState.keys.set({
766
- tctoken: {
767
- [tcTokenJid]: { token: Buffer.alloc(0),...currentEntry, senderTimestamp: issueTimestamp },
768
- ...indexWrite
511
+ if (!isNewsletter && !isGroupOrStatus && aiLabel) {
512
+ const botNode = { tag: 'bot', attrs: { biz_bot: '1' } };
513
+ const filteredBizBot = getBinaryNodeFilter(additionalNodes ? additionalNodes : []);
514
+ if (filteredBizBot) { stanza.content.push(...additionalNodes); didPushAdditional = true; }
515
+ else stanza.content.push(botNode);
516
+ }
517
+
518
+ if (!isNewsletter && !isRetryResend && reportingMessage?.messageContextInfo?.messageSecret && shouldIncludeReportingToken(reportingMessage)) {
519
+ try {
520
+ const encoded = encodeWAMessage(reportingMessage);
521
+ const reportingKey = { id: msgId, fromMe: true, remoteJid: destinationJid, participant: participant?.jid };
522
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
523
+ if (reportingNode) stanza.content.push(reportingNode);
524
+ } catch (error) {
525
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
769
526
  }
770
- })
771
- })
772
- .catch(err => {
773
- logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed')
774
- })
775
- .finally(() => {
776
- inFlightTcTokenIssuance.delete(tcTokenJid)
777
- })
778
- }
779
-
780
- if (messageRetryManager && !participant) {
781
- messageRetryManager.addRecentMessage(destinationJid, msgId, message)
782
- }
783
- }, meId)
527
+ }
528
+
529
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
530
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
531
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
532
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
533
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
534
+ let tcTokenBuffer = existingTokenEntry?.token;
535
+
536
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
537
+ tcTokenBuffer = undefined;
538
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
539
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp } : null;
540
+ try { await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } }); } catch (err) {}
541
+ }
542
+
543
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
544
+ stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer });
545
+ }
546
+
547
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
548
+ stanza.content.push(...additionalNodes);
549
+ }
550
+
551
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
552
+ await sendNode(stanza);
553
+
554
+ const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
555
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
556
+ if (is1on1Send && !isProtocolMsg && !isBotOrPSA && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) && !inFlightTcTokenIssuance.has(tcTokenJid)) {
557
+ inFlightTcTokenIssuance.add(tcTokenJid);
558
+ const issueTimestamp = unixTimestampSeconds();
559
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
560
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
561
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
562
+ .then(async (result) => {
563
+ await storeTcTokensFromIqResult({ result, fallbackJid: tcTokenJid, keys: authState.keys, getLIDForPN });
564
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
565
+ const currentEntry = currentData[tcTokenJid];
566
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
567
+ await authState.keys.set({
568
+ tctoken: {
569
+ [tcTokenJid]: { token: Buffer.alloc(0), ...currentEntry, senderTimestamp: issueTimestamp },
570
+ ...indexWrite
571
+ }
572
+ });
573
+ })
574
+ .catch(err => { logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed'); })
575
+ .finally(() => { inFlightTcTokenIssuance.delete(tcTokenJid); });
576
+ }
577
+
578
+ if (messageRetryManager && !participant) {
579
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
580
+ }
581
+ }, meId);
582
+
583
+ return msgId;
584
+ };
784
585
 
785
- return msgId
786
- }
787
586
  const getMessageType = (message) => {
788
587
  const normalizedMessage = normalizeMessageContent(message);
789
- if (!normalizedMessage)
790
- return 'text';
791
- if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
792
- return 'reaction';
793
- }
794
- if (normalizedMessage.pollCreationMessage ||
795
- normalizedMessage.pollCreationMessageV2 ||
796
- normalizedMessage.pollCreationMessageV3 ||
797
- normalizedMessage.pollUpdateMessage) {
798
- return 'poll';
799
- }
800
- if (normalizedMessage.eventMessage) {
801
- return 'event';
802
- }
803
- if (getMediaType(normalizedMessage) !== '') {
804
- return 'media';
805
- }
588
+ if (!normalizedMessage) return 'text';
589
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) return 'reaction';
590
+ if (normalizedMessage.pollCreationMessage || normalizedMessage.pollCreationMessageV2 ||
591
+ normalizedMessage.pollCreationMessageV3 || normalizedMessage.pollUpdateMessage) return 'poll';
592
+ if (normalizedMessage.eventMessage) return 'event';
593
+ if (normalizedMessage.stickerPackMessage) return 'text';
594
+ if (getMediaType(normalizedMessage) !== '') return 'media';
806
595
  return 'text';
807
596
  };
597
+
808
598
  const getMediaType = (message) => {
809
- if (message.imageMessage) {
810
- return 'image';
811
- }
812
- else if (message.videoMessage) {
813
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
814
- }
815
- else if (message.audioMessage) {
816
- return message.audioMessage.ptt ? 'ptt' : 'audio';
817
- }
818
- else if (message.contactMessage) {
819
- return 'vcard';
820
- }
821
- else if (message.documentMessage) {
822
- return 'document';
823
- }
824
- else if (message.contactsArrayMessage) {
825
- return 'contact_array';
826
- }
827
- else if (message.liveLocationMessage) {
828
- return 'livelocation';
829
- }
830
- else if (message.stickerMessage) {
831
- return 'sticker';
832
- }
833
- else if (message.listMessage) {
834
- return 'list';
835
- }
836
- else if (message.listResponseMessage) {
837
- return 'list_response';
838
- }
839
- else if (message.buttonsResponseMessage) {
840
- return 'buttons_response';
841
- }
842
- else if (message.orderMessage) {
843
- return 'order';
844
- }
845
- else if (message.productMessage) {
846
- return 'product';
847
- }
848
- else if (message.interactiveResponseMessage) {
849
- return 'native_flow_response';
850
- }
851
- else if (message.groupInviteMessage) {
852
- return 'url';
853
- }
599
+ if (message.imageMessage) return 'image';
600
+ else if (message.videoMessage) return message.videoMessage.gifPlayback ? 'gif' : 'video';
601
+ else if (message.audioMessage) return message.audioMessage.ptt ? 'ptt' : 'audio';
602
+ else if (message.contactMessage) return 'vcard';
603
+ else if (message.documentMessage) return 'document';
604
+ else if (message.contactsArrayMessage) return 'contact_array';
605
+ else if (message.liveLocationMessage) return 'livelocation';
606
+ else if (message.stickerMessage) return 'sticker';
607
+ else if (message.stickerPackMessage) return 'sticker_pack';
608
+ else if (message.listMessage) return 'list';
609
+ else if (message.listResponseMessage) return 'list_response';
610
+ else if (message.buttonsResponseMessage) return 'buttons_response';
611
+ else if (message.orderMessage) return 'order';
612
+ else if (message.productMessage) return 'product';
613
+ else if (message.interactiveResponseMessage) return 'native_flow_response';
614
+ else if (message.groupInviteMessage) return 'url';
854
615
  return '';
855
616
  };
617
+
856
618
  const getButtonType = (message) => {
857
- if (message.listMessage) {
858
- return 'list'
859
- }
860
- else if (message.buttonsMessage) {
861
- return 'buttons'
862
- }
863
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
864
- return 'review_and_pay'
865
- }
866
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
867
- return 'review_order'
868
- }
869
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
870
- return 'payment_info'
871
- } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_key_info') {
872
- return 'payment_key_info'
873
- } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
874
- return 'payment_status'
875
- }
876
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
877
- return 'payment_method'
878
- }
879
- else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
880
- return 'interactive'
881
- }
882
- else if (message.interactiveMessage?.nativeFlowMessage) {
883
- return 'native_flow'
884
- }
619
+ if (message.listMessage) return 'list';
620
+ else if (message.buttonsMessage) return 'buttons';
621
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') return 'review_and_pay';
622
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') return 'review_order';
623
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') return 'payment_info';
624
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_key_info') return 'payment_key_info';
625
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') return 'payment_status';
626
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') return 'payment_method';
627
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) return 'interactive';
628
+ else if (message.interactiveMessage?.nativeFlowMessage) return 'native_flow';
885
629
  };
630
+
886
631
  const issuePrivacyTokens = async (jids, timestamp) => {
887
632
  const t = (timestamp ?? unixTimestampSeconds()).toString();
888
- const result = await query({
633
+ return await query({
889
634
  tag: 'iq',
890
- attrs: {
891
- to: S_WHATSAPP_NET,
892
- type: 'set',
893
- xmlns: 'privacy'
894
- },
895
- content: [
896
- {
897
- tag: 'tokens',
898
- attrs: {},
899
- content: jids.map(jid => ({
900
- tag: 'token',
901
- attrs: {
902
- jid: jidNormalizedUser(jid),
903
- t,
904
- type: 'trusted_contact'
905
- }
906
- }))
907
- }
908
- ]
635
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'privacy' },
636
+ content: [{
637
+ tag: 'tokens',
638
+ attrs: {},
639
+ content: jids.map(jid => ({ tag: 'token', attrs: { jid: jidNormalizedUser(jid), t, type: 'trusted_contact' } }))
640
+ }]
909
641
  });
910
- return result;
911
642
  };
643
+
912
644
  const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
913
645
  const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
646
+
914
647
  registerSocketEndHandler(() => {
915
- if (!config.userDevicesCache && userDevicesCache.close) {
916
- userDevicesCache.close();
917
- }
648
+ if (!config.userDevicesCache && userDevicesCache.close) userDevicesCache.close();
918
649
  mediaConn = undefined;
919
- if (messageRetryManager) {
920
- messageRetryManager.clear();
921
- }
650
+ if (messageRetryManager) messageRetryManager.clear();
922
651
  });
652
+
923
653
  return {
924
654
  ...sock,
925
655
  userDevicesCache,
@@ -931,7 +661,6 @@ export const makeMessagesSocket = (config) => {
931
661
  sendReceipts,
932
662
  readMessages,
933
663
  refreshMediaConn,
934
- // Function (not getter) so the spread in chats.ts preserves the live closure binding.
935
664
  getMediaHost: () => mediaHost,
936
665
  waUploadToServer,
937
666
  fetchPrivacySettings,
@@ -940,113 +669,95 @@ export const makeMessagesSocket = (config) => {
940
669
  getUSyncDevices,
941
670
  messageRetryManager,
942
671
  updateMemberLabel,
672
+
943
673
  updateMediaMessage: async (message) => {
944
674
  const content = assertMediaContent(message.message);
945
675
  const mediaKey = content.mediaKey;
946
676
  const meId = authState.creds.me.id;
947
677
  const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
948
- let error = undefined;
678
+ let error;
949
679
  await Promise.all([
950
680
  sendNode(node),
951
681
  waitForMsgMediaUpdate(async (update) => {
952
682
  const result = update.find(c => c.key.id === message.key.id);
953
683
  if (result) {
954
- if (result.error) {
955
- error = result.error;
956
- }
684
+ if (result.error) { error = result.error; }
957
685
  else {
958
686
  try {
959
687
  const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
960
688
  if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
961
689
  const resultStr = proto.MediaRetryNotification.ResultType[media.result];
962
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
963
- data: media,
964
- statusCode: getStatusCodeForMediaRetry(media.result) || 404
965
- });
690
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: getStatusCodeForMediaRetry(media.result) || 404 });
966
691
  }
967
692
  content.directPath = media.directPath;
968
693
  content.url = getUrlFromDirectPath(content.directPath, mediaHost);
969
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
970
- }
971
- catch (err) {
972
- error = err;
973
- }
694
+ } catch (err) { error = err; }
974
695
  }
975
696
  return true;
976
697
  }
977
698
  })
978
699
  ]);
979
- if (error) {
980
- throw error;
981
- }
700
+ if (error) throw error;
982
701
  ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
983
702
  return message;
984
703
  },
704
+
985
705
  sendMessage: async (jid, content, options = {}) => {
986
706
  const userJid = authState.creds.me.id;
987
- const luki = new imup(Utils_1, waUploadToServer, relayMessage)
707
+ const luki = new imup(Utils_1, waUploadToServer, relayMessage);
988
708
  const { quoted } = options;
989
709
  const messageType = luki.detectType(content);
710
+
990
711
  if (typeof content === 'object' &&
991
712
  'disappearingMessagesInChat' in content &&
992
713
  typeof content['disappearingMessagesInChat'] !== 'undefined' &&
993
714
  isJidGroup(jid)) {
994
715
  const { disappearingMessagesInChat } = content;
995
716
  const value = typeof disappearingMessagesInChat === 'boolean'
996
- ? disappearingMessagesInChat
997
- ? WA_DEFAULT_EPHEMERAL
998
- : 0
717
+ ? (disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0)
999
718
  : disappearingMessagesInChat;
1000
719
  await groupToggleEphemeral(jid, value);
1001
- }
1002
- else {
720
+ } else {
1003
721
  if (messageType) {
1004
- switch(messageType) {
1005
- case 'PAYMENT':
722
+ switch (messageType) {
723
+ case 'PAYMENT': {
1006
724
  const paymentContent = await luki.handlePayment(content, quoted);
1007
- return await relayMessage(jid, paymentContent, {
1008
- messageId: Utils_1.generateMessageID()
1009
- });
1010
- case 'PRODUCT':
725
+ return await relayMessage(jid, paymentContent, { messageId: Utils_1.generateMessageID() });
726
+ }
727
+ case 'PRODUCT': {
1011
728
  const productContent = await luki.handleProduct(content, jid, quoted);
1012
729
  const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
1013
- return await relayMessage(jid, productMsg.message, {
1014
- messageId: productMsg.key.id,
1015
- });
1016
-
1017
- case 'INTERACTIVE':
730
+ return await relayMessage(jid, productMsg.message, { messageId: productMsg.key.id });
731
+ }
732
+ case 'INTERACTIVE': {
1018
733
  const interactiveContent = await luki.handleInteractive(content, jid, quoted);
1019
734
  const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
1020
- return await relayMessage(jid, interactiveMsg.message, {
1021
- messageId: interactiveMsg.key.id
1022
- });
735
+ return await relayMessage(jid, interactiveMsg.message, { messageId: interactiveMsg.key.id });
736
+ }
1023
737
  case 'ALBUM':
1024
- return await luki.handleAlbum(content, jid, quoted)
738
+ return await luki.handleAlbum(content, jid, quoted);
1025
739
  case 'EVENT':
1026
- return await luki.handleEvent(content, jid, quoted)
740
+ return await luki.handleEvent(content, jid, quoted);
1027
741
  case 'POLL_RESULT':
1028
- return await luki.handlePollResult(content, jid, quoted)
742
+ return await luki.handlePollResult(content, jid, quoted);
1029
743
  case 'ORDER':
1030
- return await luki.handleOrderMessage(content, jid, quoted)
744
+ return await luki.handleOrderMessage(content, jid, quoted);
1031
745
  case 'GROUP_STATUS':
1032
- return await luki.handleGroupStory(content, jid, quoted)
746
+ return await luki.handleGroupStory(content, jid, quoted);
1033
747
  case 'GROUP_LABEL':
1034
- return await luki.handleGbLabel(content, jid)
748
+ return await luki.handleGbLabel(content, jid);
1035
749
  }
1036
750
  }
751
+
1037
752
  const fullMsg = await generateWAMessage(jid, content, {
1038
753
  logger,
1039
754
  userJid,
1040
755
  getUrlInfo: text => getUrlInfo(text, {
1041
756
  thumbnailWidth: linkPreviewImageThumbnailWidth,
1042
- fetchOpts: {
1043
- timeout: 3000,
1044
- ...(httpRequestOptions || {})
1045
- },
757
+ fetchOpts: { timeout: 3000, ...(httpRequestOptions || {}) },
1046
758
  logger,
1047
759
  uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1048
760
  }),
1049
- //TODO: CACHE
1050
761
  getProfilePicUrl: sock.profilePictureUrl,
1051
762
  getCallLink: sock.createCallLink,
1052
763
  upload: waUploadToServer,
@@ -1055,6 +766,7 @@ export const makeMessagesSocket = (config) => {
1055
766
  messageId: generateMessageIDV2(sock.user?.id),
1056
767
  ...options
1057
768
  });
769
+
1058
770
  const isEventMsg = 'event' in content && !!content.event;
1059
771
  const isDeleteMsg = 'delete' in content && !!content.delete;
1060
772
  const isEditMsg = 'edit' in content && !!content.edit;
@@ -1062,38 +774,19 @@ export const makeMessagesSocket = (config) => {
1062
774
  const isPollMessage = 'poll' in content && !!content.poll;
1063
775
  const additionalAttributes = {};
1064
776
  const additionalNodes = [];
1065
- // required for delete
777
+
1066
778
  if (isDeleteMsg) {
1067
- // if the chat is a group, and I am not the author, then delete the message as an admin
1068
- if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1069
- additionalAttributes.edit = '8';
1070
- }
1071
- else {
1072
- additionalAttributes.edit = '7';
1073
- }
1074
- }
1075
- else if (isEditMsg) {
779
+ additionalAttributes.edit = (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) ? '8' : '7';
780
+ } else if (isEditMsg) {
1076
781
  additionalAttributes.edit = '1';
1077
- }
1078
- else if (isPinMsg) {
782
+ } else if (isPinMsg) {
1079
783
  additionalAttributes.edit = '2';
784
+ } else if (isPollMessage) {
785
+ additionalNodes.push({ tag: 'meta', attrs: { polltype: 'creation' } });
786
+ } else if (isEventMsg) {
787
+ additionalNodes.push({ tag: 'meta', attrs: { event_type: 'creation' } });
1080
788
  }
1081
- else if (isPollMessage) {
1082
- additionalNodes.push({
1083
- tag: 'meta',
1084
- attrs: {
1085
- polltype: 'creation'
1086
- }
1087
- });
1088
- }
1089
- else if (isEventMsg) {
1090
- additionalNodes.push({
1091
- tag: 'meta',
1092
- attrs: {
1093
- event_type: 'creation'
1094
- }
1095
- });
1096
- }
789
+
1097
790
  await relayMessage(jid, fullMsg.message, {
1098
791
  messageId: fullMsg.key.id,
1099
792
  useCachedGroupMetadata: options.useCachedGroupMetadata,
@@ -1101,14 +794,134 @@ export const makeMessagesSocket = (config) => {
1101
794
  statusJidList: options.statusJidList,
1102
795
  additionalNodes: aiLabel ? additionalNodes : options.additionalNodes
1103
796
  });
797
+
1104
798
  if (config.emitOwnEvents) {
1105
799
  process.nextTick(async () => {
1106
800
  await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1107
801
  });
1108
802
  }
803
+
1109
804
  return fullMsg;
1110
805
  }
1111
806
  },
807
+
808
+ // ─── SHORTHAND HELPERS ────────────────────────────────────────────────────
809
+
810
+ /** Send plain text */
811
+ sendText: async (jid, text, options = {}) => {
812
+ return sock.sendMessage(jid, { text }, options);
813
+ },
814
+
815
+ /** Send image with optional caption */
816
+ sendImage: async (jid, media, caption = '', options = {}) => {
817
+ return sock.sendMessage(jid, { image: media, caption }, options);
818
+ },
819
+
820
+ /** Send video with optional caption */
821
+ sendVideo: async (jid, media, caption = '', options = {}) => {
822
+ return sock.sendMessage(jid, { video: media, caption }, options);
823
+ },
824
+
825
+ /** Send audio file */
826
+ sendAudio: async (jid, media, options = {}) => {
827
+ return sock.sendMessage(jid, { audio: media, mimetype: 'audio/mp4' }, options);
828
+ },
829
+
830
+ /** Send voice note (PTT) */
831
+ sendVoiceNote: async (jid, media, options = {}) => {
832
+ return sock.sendMessage(jid, { audio: media, mimetype: 'audio/ogg; codecs=opus', ptt: true }, options);
833
+ },
834
+
835
+ /** Send document/file */
836
+ sendDocument: async (jid, media, filename, mimetype = 'application/octet-stream', options = {}) => {
837
+ return sock.sendMessage(jid, { document: media, fileName: filename, mimetype }, options);
838
+ },
839
+
840
+ /** Send sticker */
841
+ sendSticker: async (jid, media, options = {}) => {
842
+ return sock.sendMessage(jid, { sticker: media }, options);
843
+ },
844
+
845
+ /** Send GIF */
846
+ sendGif: async (jid, media, caption = '', options = {}) => {
847
+ return sock.sendMessage(jid, { video: media, caption, gifPlayback: true }, options);
848
+ },
849
+
850
+ /** Send poll */
851
+ sendPoll: async (jid, name, values, selectableCount = 1, options = {}) => {
852
+ return sock.sendMessage(jid, { poll: { name, values, selectableCount } }, options);
853
+ },
854
+
855
+ /** Send reaction to a message */
856
+ sendReaction: async (key, emoji) => {
857
+ return sock.sendMessage(key.remoteJid, { react: { text: emoji, key } });
858
+ },
859
+
860
+ /** Send contact card */
861
+ sendContact: async (jid, name, number, options = {}) => {
862
+ const vcard = `BEGIN:VCARD\nVERSION:3.0\nFN:${name}\nTEL;type=CELL;type=VOICE;waid=${number}:+${number}\nEND:VCARD`;
863
+ return sock.sendMessage(jid, { contacts: { displayName: name, contacts: [{ vcard }] } }, options);
864
+ },
865
+
866
+ /** Send location */
867
+ sendLocation: async (jid, lat, long, name = '', address = '', options = {}) => {
868
+ return sock.sendMessage(jid, {
869
+ location: { degreesLatitude: lat, degreesLongitude: long, name, address }
870
+ }, options);
871
+ },
872
+
873
+ /** Send interactive buttons */
874
+ sendButtons: async (jid, text, buttons, options = {}) => {
875
+ const btns = buttons.map((b, i) => ({
876
+ name: 'quick_reply',
877
+ buttonParamsJson: JSON.stringify({ display_text: b.text, id: b.id || `btn_${i}` })
878
+ }));
879
+ return sock.sendMessage(jid, {
880
+ interactiveMessage: { body: { text }, nativeFlowMessage: { buttons: btns } }
881
+ }, options);
882
+ },
883
+
884
+ /** Send list message */
885
+ sendList: async (jid, title, text, buttonText, sections, options = {}) => {
886
+ return sock.sendMessage(jid, {
887
+ listMessage: { title, description: text, buttonText, listType: 1, sections }
888
+ }, options);
889
+ },
890
+
891
+ /** Forward message, optionally remove forwarded label */
892
+ forwardMessage: async (jid, message, removeLabel = false, options = {}) => {
893
+ const msg = message.message;
894
+ if (!msg) throw new Boom('Message content not found');
895
+ const content = normalizeMessageContent(msg);
896
+ if (removeLabel && content?.contextInfo) {
897
+ delete content.contextInfo.forwardingScore;
898
+ delete content.contextInfo.isForwarded;
899
+ }
900
+ const fullMsg = await Utils_1.generateWAMessageFromContent(jid, msg, {
901
+ messageId: Utils_1.generateMessageID(),
902
+ userJid: authState.creds.me.id,
903
+ ...options
904
+ });
905
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id });
906
+ return fullMsg;
907
+ },
908
+
909
+ /** Simulate typing for a duration (ms) */
910
+ simulateTyping: async (jid, duration = 3000) => {
911
+ await sock.sendPresenceUpdate('composing', jid);
912
+ await new Promise(r => setTimeout(r, duration));
913
+ await sock.sendPresenceUpdate('paused', jid);
914
+ },
915
+
916
+ /** Simulate voice recording for a duration (ms) */
917
+ simulateRecording: async (jid, duration = 3000) => {
918
+ await sock.sendPresenceUpdate('recording', jid);
919
+ await new Promise(r => setTimeout(r, duration));
920
+ await sock.sendPresenceUpdate('paused', jid);
921
+ },
922
+
923
+ // ─── ORIGINAL sendMessageMembers ─────────────────────────────────────────
924
+
1112
925
  sendMessageMembers: async (jid, message, options = {}) => {
1113
926
  const {
1114
927
  messageId: idm,
@@ -1121,40 +934,25 @@ export const makeMessagesSocket = (config) => {
1121
934
  const { server } = jidDecode(jid);
1122
935
  if (server !== "g.us") throw new Error("@g.us server required");
1123
936
  const meId = authState.creds.me.id;
1124
- const messages = Utils_1.normalizeMessageContent(message);
1125
- const groupData = cachedGroupMetadata? await cachedGroupMetadata(jid) : await groupMetadata(jid);
1126
- const isLid = groupData.addressingMode === "lid";
1127
- const isAdmin = groupData.participants.filter((x) => x.admin !== null).map((y) => y.id)
937
+ const groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : await groupMetadata(jid);
938
+ const isAdmin = groupData.participants.filter(x => x.admin !== null).map(y => y.id);
1128
939
  let participantJids = groupData.participants.map(z => z.id);
1129
- if (onlyMember) {
1130
- participantJids = isAdmin ? isAdmin : participantJids;
1131
- }
940
+ if (onlyMember) participantJids = isAdmin.length ? isAdmin : participantJids;
1132
941
  logger.info(`Sending message to ${participantJids.length} members from ${jid}`);
1133
942
  for (let i = 0; i < participantJids.length; i++) {
1134
- const jid = participantJids[i];
1135
- if (areJidsSameUser(jid, meId)) continue;
943
+ const memberJid = participantJids[i];
944
+ if (areJidsSameUser(memberJid, meId)) continue;
1136
945
  try {
1137
946
  const msgId = `${idm || Utils_1.generateMessageID()}_${i}`;
1138
- const fullMsg = await Utils_1.generateWAMessageFromContent(jid, message, {
1139
- messageId: msgId,
1140
- quoted
1141
- })
1142
- await relayMessage(jid, fullMsg.message, {
1143
- messageId: fullMsg.key.id
1144
- });
1145
- logger.debug(`Message successfully sent to ${jid}`);
1146
- if (delayMs && i < participantJids.length - 1) {
1147
- await new Promise(z => setTimeout(z, delayMs));
1148
- }
947
+ const fullMsg = await Utils_1.generateWAMessageFromContent(memberJid, message, { messageId: msgId, quoted });
948
+ await relayMessage(memberJid, fullMsg.message, { messageId: fullMsg.key.id });
949
+ if (delayMs && i < participantJids.length - 1) await new Promise(r => setTimeout(r, delayMs));
1149
950
  } catch (e) {
1150
- logger.error({ jid, e }, "Error sending message to");
951
+ logger.error({ jid: memberJid, e }, "Error sending message to member");
1151
952
  }
1152
953
  }
1153
- return JSON.stringify({
1154
- members_total: participantJids.length,
1155
- message
1156
- }, null, 4);
954
+ return JSON.stringify({ members_total: participantJids.length, message }, null, 4);
1157
955
  }
1158
956
  };
1159
957
  };
1160
- //# sourceMappingURL=messages-send.js.map
958
+