vinzzsync-wacli 1.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.
Files changed (49) hide show
  1. package/c.js +2 -0
  2. package/func.js +3263 -0
  3. package/index.js +2416 -0
  4. package/index2.js +3611 -0
  5. package/lib/sqlAuth.js +109 -0
  6. package/package.json +21 -0
  7. package/plugins/_loader.js +191 -0
  8. package/plugins/addplugins.js +93 -0
  9. package/plugins/backup.js +91 -0
  10. package/plugins/cekch.js +157 -0
  11. package/plugins/cekgb.js +105 -0
  12. package/plugins/clear.js +12 -0
  13. package/plugins/cmd.js +69 -0
  14. package/plugins/cmfil.js +110 -0
  15. package/plugins/cms.js +474 -0
  16. package/plugins/delplugins.js +57 -0
  17. package/plugins/dmsg.js +112 -0
  18. package/plugins/eval.js +175 -0
  19. package/plugins/evfil.js +86 -0
  20. package/plugins/exit.js +11 -0
  21. package/plugins/fadm.js +107 -0
  22. package/plugins/fakemsg.js +154 -0
  23. package/plugins/fakesize.js +204 -0
  24. package/plugins/fclick.js +111 -0
  25. package/plugins/fitnah.js +87 -0
  26. package/plugins/getfile.js +169 -0
  27. package/plugins/getplugins.js +71 -0
  28. package/plugins/getquoted.js +76 -0
  29. package/plugins/getusn.js +92 -0
  30. package/plugins/groups.js +62 -0
  31. package/plugins/help.js +19 -0
  32. package/plugins/ht.js +45 -0
  33. package/plugins/ht2.js +59 -0
  34. package/plugins/ht3.js +66 -0
  35. package/plugins/isbot.js +177 -0
  36. package/plugins/listplugins.js +103 -0
  37. package/plugins/me.js +95 -0
  38. package/plugins/minigames.js +144 -0
  39. package/plugins/ping.js +124 -0
  40. package/plugins/quoted.js +102 -0
  41. package/plugins/rvo.js +88 -0
  42. package/plugins/savefile.js +334 -0
  43. package/plugins/send.js +52 -0
  44. package/plugins/session.js +18 -0
  45. package/plugins/smsg.js +204 -0
  46. package/plugins/status.js +18 -0
  47. package/plugins/typing_troll.js +91 -0
  48. package/pp.jpg +0 -0
  49. package/vkazee-send-message.js +1238 -0
@@ -0,0 +1,1238 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
6
+ import { getUrlInfo } from '../Utils/link-preview.js';
7
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
8
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
10
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
11
+ import { makeNewsletterSocket } from './newsletter.js';
12
+ export const makeMessagesSocket = (config) => {
13
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
14
+ const sock = makeNewsletterSocket(config);
15
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
16
+ const userDevicesCache = config.userDevicesCache ||
17
+ new NodeCache({
18
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
19
+ useClones: false
20
+ });
21
+ const peerSessionsCache = new NodeCache({
22
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
23
+ useClones: false
24
+ });
25
+ // Initialize message retry manager if enabled
26
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
27
+ // Prevent race conditions in Signal session encryption by user
28
+ const encryptionMutex = makeKeyedMutex();
29
+ let mediaConn;
30
+ const refreshMediaConn = async (forceGet = false) => {
31
+ const media = await mediaConn;
32
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
33
+ mediaConn = (async () => {
34
+ const result = await query({
35
+ tag: 'iq',
36
+ attrs: {
37
+ type: 'set',
38
+ xmlns: 'w:m',
39
+ to: S_WHATSAPP_NET
40
+ },
41
+ content: [{ tag: 'media_conn', attrs: {} }]
42
+ });
43
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
44
+ // TODO: explore full length of data that whatsapp provides
45
+ const node = {
46
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
47
+ hostname: attrs.hostname,
48
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
49
+ })),
50
+ auth: mediaConnNode.attrs.auth,
51
+ ttl: +mediaConnNode.attrs.ttl,
52
+ fetchDate: new Date()
53
+ };
54
+ logger.debug('fetched media conn');
55
+ return node;
56
+ })();
57
+ }
58
+ return mediaConn;
59
+ };
60
+ /**
61
+ * generic send receipt function
62
+ * used for receipts of phone call, read, delivery etc.
63
+ * */
64
+ const sendReceipt = async (jid, participant, messageIds, type) => {
65
+ if (!messageIds || messageIds.length === 0) {
66
+ throw new Boom('missing ids in receipt');
67
+ }
68
+ const node = {
69
+ tag: 'receipt',
70
+ attrs: {
71
+ id: messageIds[0]
72
+ }
73
+ };
74
+ const isReadReceipt = type === 'read' || type === 'read-self';
75
+ if (isReadReceipt) {
76
+ node.attrs.t = unixTimestampSeconds().toString();
77
+ }
78
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
79
+ node.attrs.recipient = jid;
80
+ node.attrs.to = participant;
81
+ }
82
+ else {
83
+ node.attrs.to = jid;
84
+ if (participant) {
85
+ node.attrs.participant = participant;
86
+ }
87
+ }
88
+ if (type) {
89
+ node.attrs.type = type;
90
+ }
91
+ const remainingMessageIds = messageIds.slice(1);
92
+ if (remainingMessageIds.length) {
93
+ node.content = [
94
+ {
95
+ tag: 'list',
96
+ attrs: {},
97
+ content: remainingMessageIds.map(id => ({
98
+ tag: 'item',
99
+ attrs: { id }
100
+ }))
101
+ }
102
+ ];
103
+ }
104
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
105
+ await sendNode(node);
106
+ };
107
+ /** Correctly bulk send receipts to multiple chats, participants */
108
+ const sendReceipts = async (keys, type) => {
109
+ const recps = aggregateMessageKeysNotFromMe(keys);
110
+ for (const { jid, participant, messageIds } of recps) {
111
+ await sendReceipt(jid, participant, messageIds, type);
112
+ }
113
+ };
114
+ /** Bulk read messages. Keys can be from different chats & participants */
115
+ const readMessages = async (keys) => {
116
+ const privacySettings = await fetchPrivacySettings();
117
+ // based on privacy settings, we have to change the read type
118
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
119
+ await sendReceipts(keys, readType);
120
+ };
121
+ /** Fetch all the devices we've to send a message to */
122
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
123
+ const deviceResults = [];
124
+ if (!useCache) {
125
+ logger.debug('not using cache for devices');
126
+ }
127
+ const toFetch = [];
128
+ const jidsWithUser = jids
129
+ .map(jid => {
130
+ const decoded = jidDecode(jid);
131
+ const user = decoded?.user;
132
+ const device = decoded?.device;
133
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
134
+ if (isExplicitDevice && user) {
135
+ deviceResults.push({
136
+ user,
137
+ device,
138
+ jid
139
+ });
140
+ return null;
141
+ }
142
+ jid = jidNormalizedUser(jid);
143
+ return { jid, user };
144
+ })
145
+ .filter(jid => jid !== null);
146
+ let mgetDevices;
147
+ if (useCache && userDevicesCache.mget) {
148
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
149
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
150
+ }
151
+ for (const { jid, user } of jidsWithUser) {
152
+ if (useCache) {
153
+ const devices = mgetDevices?.[user] ||
154
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
155
+ if (devices) {
156
+ const devicesWithJid = devices.map(d => ({
157
+ ...d,
158
+ jid: jidEncode(d.user, d.server, d.device)
159
+ }));
160
+ deviceResults.push(...devicesWithJid);
161
+ logger.trace({ user }, 'using cache for devices');
162
+ }
163
+ else {
164
+ toFetch.push(jid);
165
+ }
166
+ }
167
+ else {
168
+ toFetch.push(jid);
169
+ }
170
+ }
171
+ if (!toFetch.length) {
172
+ return deviceResults;
173
+ }
174
+ const requestedLidUsers = new Set();
175
+ for (const jid of toFetch) {
176
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
177
+ const user = jidDecode(jid)?.user;
178
+ if (user)
179
+ requestedLidUsers.add(user);
180
+ }
181
+ }
182
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
183
+ for (const jid of toFetch) {
184
+ 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
185
+ }
186
+ const result = await sock.executeUSyncQuery(query);
187
+ if (result) {
188
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
189
+ const lidResults = result.list.filter(a => !!a.lid);
190
+ if (lidResults.length > 0) {
191
+ logger.trace('Storing LID maps from device call');
192
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
193
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
194
+ try {
195
+ const lids = lidResults.map(a => a.lid);
196
+ if (lids.length) {
197
+ await assertSessions(lids, true);
198
+ }
199
+ }
200
+ catch (e) {
201
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
202
+ }
203
+ }
204
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
205
+ const deviceMap = {};
206
+ for (const item of extracted) {
207
+ deviceMap[item.user] = deviceMap[item.user] || [];
208
+ deviceMap[item.user]?.push(item);
209
+ }
210
+ // Process each user's devices as a group for bulk LID migration
211
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
212
+ const isLidUser = requestedLidUsers.has(user);
213
+ // Process all devices for this user
214
+ for (const item of userDevices) {
215
+ const finalJid = isLidUser
216
+ ? jidEncode(user, item.server, item.device)
217
+ : jidEncode(item.user, item.server, item.device);
218
+ deviceResults.push({
219
+ ...item,
220
+ jid: finalJid
221
+ });
222
+ logger.debug({
223
+ user: item.user,
224
+ device: item.device,
225
+ finalJid,
226
+ usedLid: isLidUser
227
+ }, 'Processed device with LID priority');
228
+ }
229
+ }
230
+ if (userDevicesCache.mset) {
231
+ // if the cache supports mset, we can set all devices in one go
232
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
233
+ }
234
+ else {
235
+ for (const key in deviceMap) {
236
+ if (deviceMap[key])
237
+ await userDevicesCache.set(key, deviceMap[key]);
238
+ }
239
+ }
240
+ const userDeviceUpdates = {};
241
+ for (const [userId, devices] of Object.entries(deviceMap)) {
242
+ if (devices && devices.length > 0) {
243
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
244
+ }
245
+ }
246
+ if (Object.keys(userDeviceUpdates).length > 0) {
247
+ try {
248
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
249
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
250
+ }
251
+ catch (error) {
252
+ logger.warn({ error }, 'failed to store user device lists');
253
+ }
254
+ }
255
+ }
256
+ return deviceResults;
257
+ };
258
+ /**
259
+ * Update Member Label
260
+ */
261
+ const updateMemberLabel = (jid, memberLabel) => {
262
+ return relayMessage(jid, {
263
+ protocolMessage: {
264
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
265
+ memberLabel: {
266
+ label: memberLabel?.slice(0, 30),
267
+ labelTimestamp: unixTimestampSeconds()
268
+ }
269
+ }
270
+ }, {
271
+ additionalNodes: [
272
+ {
273
+ tag: 'meta',
274
+ attrs: {
275
+ tag_reason: 'user_update',
276
+ appdata: 'member_tag'
277
+ },
278
+ content: undefined
279
+ }
280
+ ]
281
+ });
282
+ };
283
+ const assertSessions = async (jids, force) => {
284
+ let didFetchNewSession = false;
285
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
286
+ const jidsRequiringFetch = [];
287
+ logger.debug({ jids }, 'assertSessions call with jids');
288
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
289
+ for (const jid of uniqueJids) {
290
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
291
+ const cachedSession = peerSessionsCache.get(signalId);
292
+ if (cachedSession !== undefined) {
293
+ if (cachedSession && !force) {
294
+ continue; // Session exists in cache
295
+ }
296
+ }
297
+ else {
298
+ const sessionValidation = await signalRepository.validateSession(jid);
299
+ const hasSession = sessionValidation.exists;
300
+ peerSessionsCache.set(signalId, hasSession);
301
+ if (hasSession && !force) {
302
+ continue;
303
+ }
304
+ }
305
+ jidsRequiringFetch.push(jid);
306
+ }
307
+ if (jidsRequiringFetch.length) {
308
+ // LID if mapped, otherwise original
309
+ const wireJids = [
310
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
311
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
312
+ ];
313
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
314
+ const result = await query({
315
+ tag: 'iq',
316
+ attrs: {
317
+ xmlns: 'encrypt',
318
+ type: 'get',
319
+ to: S_WHATSAPP_NET
320
+ },
321
+ content: [
322
+ {
323
+ tag: 'key',
324
+ attrs: {},
325
+ content: wireJids.map(jid => {
326
+ const attrs = { jid };
327
+ if (force)
328
+ attrs.reason = 'identity';
329
+ return { tag: 'user', attrs };
330
+ })
331
+ }
332
+ ]
333
+ });
334
+ await parseAndInjectE2ESessions(result, signalRepository);
335
+ didFetchNewSession = true;
336
+ // Cache fetched sessions using wire JIDs
337
+ for (const wireJid of wireJids) {
338
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
339
+ peerSessionsCache.set(signalId, true);
340
+ }
341
+ }
342
+ return didFetchNewSession;
343
+ };
344
+ 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
+ }
349
+ const protocolMessage = {
350
+ protocolMessage: {
351
+ peerDataOperationRequestMessage: pdoMessage,
352
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
353
+ }
354
+ };
355
+ 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
+ ]
367
+ });
368
+ return msgId;
369
+ };
370
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
371
+ if (!recipientJids.length) {
372
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
373
+ }
374
+ const patched = await patchMessageBeforeSending(message, recipientJids);
375
+ const patchedMessages = Array.isArray(patched)
376
+ ? patched
377
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
378
+ let shouldIncludeDeviceIdentity = false;
379
+ const meId = authState.creds.me.id;
380
+ const meLid = authState.creds.me?.lid;
381
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
382
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
383
+ try {
384
+ if (!jid)
385
+ return null;
386
+ let msgToEncrypt = patchedMessage;
387
+ if (dsmMessage) {
388
+ const { user: targetUser } = jidDecode(jid);
389
+ const { user: ownPnUser } = jidDecode(meId);
390
+ const ownLidUser = meLidUser;
391
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
392
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
393
+ if (isOwnUser && !isExactSenderDevice) {
394
+ msgToEncrypt = dsmMessage;
395
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
396
+ }
397
+ }
398
+ const bytes = encodeWAMessage(msgToEncrypt);
399
+ const mutexKey = jid;
400
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
401
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
402
+ if (type === 'pkmsg') {
403
+ shouldIncludeDeviceIdentity = true;
404
+ }
405
+ return {
406
+ tag: 'to',
407
+ attrs: { jid },
408
+ content: [
409
+ {
410
+ tag: 'enc',
411
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
412
+ content: ciphertext
413
+ }
414
+ ]
415
+ };
416
+ });
417
+ return node;
418
+ }
419
+ catch (err) {
420
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
421
+ return null;
422
+ }
423
+ });
424
+ 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
+ }
428
+ return { nodes, shouldIncludeDeviceIdentity };
429
+ };
430
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, onTarget }) => {
431
+ const meId = authState.creds.me.id;
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
+ // Ensure groupStatusMessageV2 always has messageContextInfo.messageSecret
447
+ if (message?.groupStatusMessageV2 && !message?.messageContextInfo?.messageSecret) {
448
+ const { randomBytes } = await import('node:crypto');
449
+ message = {
450
+ ...message,
451
+ messageContextInfo: {
452
+ ...(message.messageContextInfo || {}),
453
+ messageSecret: randomBytes(32)
454
+ },
455
+ groupStatusMessageV2: {
456
+ ...message.groupStatusMessageV2,
457
+ message: {
458
+ ...(message.groupStatusMessageV2.message || {}),
459
+ messageContextInfo: {
460
+ ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
461
+ messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
462
+ }
463
+ }
464
+ }
465
+ };
466
+ }
467
+ const participants = [];
468
+ const destinationJid = !isStatus ? finalJid : statusJid;
469
+ const binaryNodeContent = [];
470
+ const devices = [];
471
+ const targetMode = onTarget === true;
472
+ let reportingMessage;
473
+ const meMsg = {
474
+ deviceSentMessage: {
475
+ destinationJid,
476
+ message
477
+ },
478
+ messageContextInfo: message.messageContextInfo
479
+ };
480
+ const extraAttrs = {};
481
+ if (participant) {
482
+ if (!isGroup && !isStatus) {
483
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
484
+ }
485
+ const { user, device } = jidDecode(participant.jid);
486
+ devices.push({
487
+ user,
488
+ device,
489
+ jid: participant.jid
490
+ });
491
+ }
492
+ await authState.keys.transaction(async () => {
493
+ const mediaType = getMediaType(message);
494
+ if (mediaType) {
495
+ extraAttrs['mediatype'] = mediaType;
496
+ }
497
+ if (isNewsletter) {
498
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
499
+ const bytes = encodeNewsletterMessage(patched);
500
+ binaryNodeContent.push({
501
+ tag: 'plaintext',
502
+ attrs: {},
503
+ content: bytes
504
+ });
505
+ const stanza = {
506
+ tag: 'message',
507
+ attrs: {
508
+ to: jid,
509
+ id: msgId,
510
+ type: getMessageType(message),
511
+ ...(additionalAttributes || {})
512
+ },
513
+ content: binaryNodeContent
514
+ };
515
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
516
+ await sendNode(stanza);
517
+ return;
518
+ }
519
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
520
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
521
+ }
522
+ if (isGroupOrStatus && !isRetryResend) {
523
+ const [groupData, senderKeyMap] = await Promise.all([
524
+ (async () => {
525
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
526
+ if (groupData && Array.isArray(groupData?.participants)) {
527
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
528
+ }
529
+ else if (!isStatus) {
530
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
531
+ }
532
+ return groupData;
533
+ })(),
534
+ (async () => {
535
+ if (!participant && !isStatus) {
536
+ // what if sender memory is less accurate than the cached metadata
537
+ // on participant change in group, we should do sender memory manipulation
538
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
539
+ return result[jid] || {};
540
+ }
541
+ return {};
542
+ })()
543
+ ]);
544
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
545
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
546
+ additionalAttributes = {
547
+ ...additionalAttributes,
548
+ expiration: groupData.ephemeralDuration.toString()
549
+ };
550
+ }
551
+ if (isStatus && statusJidList) {
552
+ participantsList.push(...statusJidList);
553
+ }
554
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
555
+ devices.push(...additionalDevices);
556
+ if (isGroup) {
557
+ additionalAttributes = {
558
+ ...additionalAttributes,
559
+ addressing_mode: groupData?.addressingMode || 'lid'
560
+ };
561
+ }
562
+ const patched = await patchMessageBeforeSending(message);
563
+ if (Array.isArray(patched)) {
564
+ throw new Boom('Per-jid patching is not supported in groups');
565
+ }
566
+ const bytes = encodeWAMessage(patched);
567
+ reportingMessage = patched;
568
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
569
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
570
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
571
+ group: destinationJid,
572
+ data: bytes,
573
+ meId: groupSenderIdentity
574
+ });
575
+ const senderKeyRecipients = [];
576
+ for (const device of devices) {
577
+ const deviceJid = device.jid;
578
+ const hasKey = !!senderKeyMap[deviceJid];
579
+ if ((!hasKey || !!participant) &&
580
+ !isHostedLidUser(deviceJid) &&
581
+ !isHostedPnUser(deviceJid) &&
582
+ device.device !== 99) {
583
+ //todo: revamp all this logic
584
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
585
+ senderKeyRecipients.push(deviceJid);
586
+ senderKeyMap[deviceJid] = true;
587
+ }
588
+ }
589
+ if (senderKeyRecipients.length) {
590
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
591
+ const senderKeyMsg = {
592
+ senderKeyDistributionMessage: {
593
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
594
+ groupId: destinationJid
595
+ }
596
+ };
597
+ const senderKeySessionTargets = senderKeyRecipients;
598
+
599
+ await assertSessions(senderKeySessionTargets);
600
+
601
+ const result = await createParticipantNodes(
602
+ senderKeySessionTargets,
603
+ senderKeyMsg,
604
+ extraAttrs
605
+ );
606
+
607
+ shouldIncludeDeviceIdentity =
608
+ shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
609
+
610
+ participants.push(...result.nodes);
611
+ }
612
+ binaryNodeContent.push({
613
+ tag: 'enc',
614
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
615
+ content: ciphertext
616
+ });
617
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
618
+ }
619
+ else {
620
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
621
+ // TODO: investigate if this is true
622
+ let ownId = meId;
623
+ if (isLid && meLid) {
624
+ ownId = meLid;
625
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
626
+ }
627
+ else {
628
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
629
+ }
630
+ const { user: ownUser } = jidDecode(ownId);
631
+ if (!participant) {
632
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
633
+ reportingMessage = Array.isArray(patchedForReporting)
634
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
635
+ : patchedForReporting;
636
+ }
637
+ if (!isRetryResend) {
638
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
639
+ devices.push({
640
+ user,
641
+ device: 0,
642
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
643
+ });
644
+ if (user !== ownUser) {
645
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
646
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
647
+ devices.push({
648
+ user: ownUserForAddressing,
649
+ device: 0,
650
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
651
+ });
652
+ }
653
+ if (additionalAttributes?.['category'] !== 'peer') {
654
+ // Clear placeholders and enumerate actual devices
655
+ devices.length = 0;
656
+ // Use conversation-appropriate sender identity
657
+ const senderIdentity = isLid && meLid
658
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
659
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
660
+ // Enumerate devices for sender and target with consistent addressing
661
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
662
+ devices.push(...sessionDevices);
663
+ logger.debug({
664
+ deviceCount: devices.length,
665
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
666
+ }, 'Device enumeration complete with unified addressing');
667
+ }
668
+ }
669
+ const allRecipients = [];
670
+ const meRecipients = [];
671
+ const otherRecipients = [];
672
+
673
+ for (const jid of allRecipients) {
674
+ const { user } = jidDecode(jid);
675
+
676
+ const isMe =
677
+ user === meUser ||
678
+ user === meLidUser;
679
+
680
+ if (
681
+ targetMode &&
682
+ isMe &&
683
+ jid !== authState.creds.me.id
684
+ ) {
685
+ continue;
686
+ }
687
+
688
+ if (isMe) {
689
+ meRecipients.push(jid);
690
+ } else {
691
+ otherRecipients.push(jid);
692
+ }
693
+ }
694
+ const { user: mePnUser } = jidDecode(meId);
695
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
696
+ for (const { user, jid } of devices) {
697
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
698
+ if (isExactSenderDevice) {
699
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
700
+ continue;
701
+ }
702
+ // Check if this is our device (could match either PN or LID user)
703
+ const isMe = user === mePnUser || user === meLidUser;
704
+ if (isMe) {
705
+ meRecipients.push(jid);
706
+ }
707
+ else {
708
+ otherRecipients.push(jid);
709
+ }
710
+ allRecipients.push(jid);
711
+ }
712
+ await assertSessions(allRecipients);
713
+ const [
714
+ meResult,
715
+ otherResult
716
+ ] = await Promise.all([
717
+ meRecipients.length
718
+ ? createParticipantNodes(
719
+ meRecipients,
720
+ message,
721
+ extraAttrs,
722
+ targetMode ? meMsg : undefined
723
+ )
724
+ : { nodes: [], shouldIncludeDeviceIdentity: false },
725
+
726
+ otherRecipients.length
727
+ ? createParticipantNodes(
728
+ otherRecipients,
729
+ message,
730
+ extraAttrs
731
+ )
732
+ : { nodes: [], shouldIncludeDeviceIdentity: false }
733
+ ]);
734
+
735
+
736
+ const meNodes = meResult?.nodes || [];
737
+ const otherNodes = otherResult?.nodes || [];
738
+
739
+ const s1 = meResult?.shouldIncludeDeviceIdentity || false;
740
+ const s2 = otherResult?.shouldIncludeDeviceIdentity || false;
741
+ participants.push(...meNodes);
742
+ participants.push(...otherNodes);
743
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
744
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
745
+ }
746
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
747
+ }
748
+ if (isRetryResend) {
749
+ const isParticipantLid = isLidUser(participant.jid);
750
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
751
+ const encodedMessageToSend = isMe
752
+ ? encodeWAMessage({
753
+ deviceSentMessage: {
754
+ destinationJid,
755
+ message
756
+ }
757
+ })
758
+ : encodeWAMessage(message);
759
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
760
+ data: encodedMessageToSend,
761
+ jid: participant.jid
762
+ });
763
+ binaryNodeContent.push({
764
+ tag: 'enc',
765
+ attrs: {
766
+ v: '2',
767
+ type,
768
+ count: participant.count.toString()
769
+ },
770
+ content: encryptedContent
771
+ });
772
+ }
773
+ if (participants.length) {
774
+ if (additionalAttributes?.['category'] === 'peer') {
775
+ const peerNode = participants[0]?.content?.[0];
776
+ if (peerNode) {
777
+ binaryNodeContent.push(peerNode); // push only enc
778
+ }
779
+ }
780
+ else {
781
+ binaryNodeContent.push({
782
+ tag: 'participants',
783
+ attrs: {},
784
+ content: participants
785
+ });
786
+ }
787
+ }
788
+ const stanza = {
789
+ tag: 'message',
790
+ attrs: {
791
+ id: msgId,
792
+ to: destinationJid,
793
+ type: getMessageType(message),
794
+ ...(additionalAttributes || {})
795
+ },
796
+ content: binaryNodeContent
797
+ };
798
+ // if the participant to send to is explicitly specified (generally retry recp)
799
+ // ensure the message is only sent to that person
800
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
801
+ if (participant) {
802
+ if (isJidGroup(destinationJid)) {
803
+ stanza.attrs.to = destinationJid;
804
+ stanza.attrs.participant = participant.jid;
805
+ }
806
+ else if (areJidsSameUser(participant.jid, meId)) {
807
+ stanza.attrs.to = participant.jid;
808
+ stanza.attrs.recipient = destinationJid;
809
+ }
810
+ else {
811
+ stanza.attrs.to = participant.jid;
812
+ }
813
+ }
814
+ else {
815
+ stanza.attrs.to = destinationJid;
816
+ }
817
+ if (shouldIncludeDeviceIdentity) {
818
+ ;
819
+ stanza.content.push({
820
+ tag: 'device-identity',
821
+ attrs: {},
822
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
823
+ });
824
+ logger.debug({ jid }, 'adding device identity');
825
+ }
826
+ if (!isNewsletter &&
827
+ !isRetryResend &&
828
+ reportingMessage?.messageContextInfo?.messageSecret &&
829
+ shouldIncludeReportingToken(reportingMessage)) {
830
+ try {
831
+ const encoded = encodeWAMessage(reportingMessage);
832
+ const reportingKey = {
833
+ id: msgId,
834
+ fromMe: true,
835
+ remoteJid: destinationJid,
836
+ participant: participant?.jid
837
+ };
838
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
839
+ if (reportingNode) {
840
+ ;
841
+ stanza.content.push(reportingNode);
842
+ logger.trace({ jid }, 'added reporting token to message');
843
+ }
844
+ }
845
+ catch (error) {
846
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
847
+ }
848
+ }
849
+ const contactTcTokenData = !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {};
850
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
851
+ if (tcTokenBuffer) {
852
+ ;
853
+ stanza.content.push({
854
+ tag: 'tctoken',
855
+ attrs: {},
856
+ content: tcTokenBuffer
857
+ });
858
+ }
859
+ if (additionalNodes && additionalNodes.length > 0) {
860
+ ;
861
+ stanza.content.push(...additionalNodes);
862
+ }
863
+ // Inject biz node for interactive, button, and list messages
864
+ if (!isNewsletter) {
865
+ const normalizedMsg = normalizeMessageContent(message);
866
+ const hasButton = normalizedMsg?.interactiveMessage ||
867
+ normalizedMsg?.buttonsMessage ||
868
+ normalizedMsg?.listMessage;
869
+ if (hasButton) {
870
+ const buttonsNode = getButtonArgs(normalizedMsg);
871
+ if (buttonsNode) {
872
+ ;
873
+ stanza.content.push(buttonsNode);
874
+ }
875
+ }
876
+ }
877
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
878
+ await sendNode(stanza);
879
+ // Add message to retry cache if enabled
880
+ if (messageRetryManager && !participant) {
881
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
882
+ }
883
+ }, meId);
884
+ return msgId;
885
+ };
886
+ const getMessageType = (message) => {
887
+ // groupStatusMessageV2 must be checked BEFORE normalizeMessageContent
888
+ // because normalizeMessageContent will unwrap it into the inner message
889
+ if (message?.groupStatusMessageV2 || message?.groupStatusMessage) {
890
+ return 'text';
891
+ }
892
+ const normalizedMessage = normalizeMessageContent(message);
893
+ if (!normalizedMessage)
894
+ return 'text';
895
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
896
+ return 'reaction';
897
+ }
898
+ if (normalizedMessage.pollCreationMessage ||
899
+ normalizedMessage.pollCreationMessageV2 ||
900
+ normalizedMessage.pollCreationMessageV3 ||
901
+ normalizedMessage.pollUpdateMessage) {
902
+ return 'poll';
903
+ }
904
+ if (normalizedMessage.eventMessage) {
905
+ return 'event';
906
+ }
907
+ if (getMediaType(normalizedMessage) !== '') {
908
+ return 'media';
909
+ }
910
+ return 'text';
911
+ };
912
+ const getMediaType = (message) => {
913
+ if (message.imageMessage) {
914
+ return 'image';
915
+ }
916
+ else if (message.videoMessage) {
917
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
918
+ }
919
+ else if (message.audioMessage) {
920
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
921
+ }
922
+ else if (message.contactMessage) {
923
+ return 'vcard';
924
+ }
925
+ else if (message.documentMessage) {
926
+ return 'document';
927
+ }
928
+ else if (message.contactsArrayMessage) {
929
+ return 'contact_array';
930
+ }
931
+ else if (message.liveLocationMessage) {
932
+ return 'livelocation';
933
+ }
934
+ else if (message.stickerMessage) {
935
+ return 'sticker';
936
+ }
937
+ else if (message.listMessage) {
938
+ return 'list';
939
+ }
940
+ else if (message.listResponseMessage) {
941
+ return 'list_response';
942
+ }
943
+ else if (message.buttonsResponseMessage) {
944
+ return 'buttons_response';
945
+ }
946
+ else if (message.orderMessage) {
947
+ return 'order';
948
+ }
949
+ else if (message.productMessage) {
950
+ return 'product';
951
+ }
952
+ else if (message.interactiveResponseMessage) {
953
+ return 'native_flow_response';
954
+ }
955
+ else if (message.groupInviteMessage) {
956
+ return 'url';
957
+ }
958
+ return '';
959
+ };
960
+ const getButtonArgs = (message) => {
961
+ const nativeFlow = message?.interactiveMessage?.nativeFlowMessage;
962
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name;
963
+ const nativeFlowSpecials = [
964
+ 'mpm', 'cta_catalog', 'send_location',
965
+ 'call_permission_request', 'wa_payment_transaction_details',
966
+ 'automated_greeting_message_view_catalog'
967
+ ];
968
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
969
+ return {
970
+ tag: 'biz',
971
+ attrs: {
972
+ native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
973
+ }
974
+ };
975
+ }
976
+ else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
977
+ return {
978
+ tag: 'biz',
979
+ attrs: {
980
+ actual_actors: '2',
981
+ host_storage: '2',
982
+ privacy_mode_ts: unixTimestampSeconds().toString()
983
+ },
984
+ content: [
985
+ {
986
+ tag: 'interactive',
987
+ attrs: { type: 'native_flow', v: '1' },
988
+ content: [
989
+ {
990
+ tag: 'native_flow',
991
+ attrs: { v: '2', name: firstButtonName }
992
+ }
993
+ ]
994
+ },
995
+ {
996
+ tag: 'quality_control',
997
+ attrs: { source_type: 'third_party' }
998
+ }
999
+ ]
1000
+ };
1001
+ }
1002
+ else if (nativeFlow || message?.buttonsMessage) {
1003
+ return {
1004
+ tag: 'biz',
1005
+ attrs: {
1006
+ actual_actors: '2',
1007
+ host_storage: '2',
1008
+ privacy_mode_ts: unixTimestampSeconds().toString()
1009
+ },
1010
+ content: [
1011
+ {
1012
+ tag: 'interactive',
1013
+ attrs: { type: 'native_flow', v: '1' },
1014
+ content: [
1015
+ {
1016
+ tag: 'native_flow',
1017
+ attrs: { v: '9', name: 'mixed' }
1018
+ }
1019
+ ]
1020
+ },
1021
+ {
1022
+ tag: 'quality_control',
1023
+ attrs: { source_type: 'third_party' }
1024
+ }
1025
+ ]
1026
+ };
1027
+ }
1028
+ else if (message?.listMessage) {
1029
+ return {
1030
+ tag: 'biz',
1031
+ attrs: {
1032
+ actual_actors: '2',
1033
+ host_storage: '2',
1034
+ privacy_mode_ts: unixTimestampSeconds().toString()
1035
+ },
1036
+ content: [
1037
+ {
1038
+ tag: 'list',
1039
+ attrs: { v: '2', type: 'product_list' }
1040
+ },
1041
+ {
1042
+ tag: 'quality_control',
1043
+ attrs: { source_type: 'third_party' }
1044
+ }
1045
+ ]
1046
+ };
1047
+ }
1048
+ else {
1049
+ return {
1050
+ tag: 'biz',
1051
+ attrs: {
1052
+ actual_actors: '2',
1053
+ host_storage: '2',
1054
+ privacy_mode_ts: unixTimestampSeconds().toString()
1055
+ }
1056
+ };
1057
+ }
1058
+ };
1059
+ const getPrivacyTokens = async (jids) => {
1060
+ const t = unixTimestampSeconds().toString();
1061
+ const result = await query({
1062
+ tag: 'iq',
1063
+ attrs: {
1064
+ to: S_WHATSAPP_NET,
1065
+ type: 'set',
1066
+ xmlns: 'privacy'
1067
+ },
1068
+ content: [
1069
+ {
1070
+ tag: 'tokens',
1071
+ attrs: {},
1072
+ content: jids.map(jid => ({
1073
+ tag: 'token',
1074
+ attrs: {
1075
+ jid: jidNormalizedUser(jid),
1076
+ t,
1077
+ type: 'trusted_contact'
1078
+ }
1079
+ }))
1080
+ }
1081
+ ]
1082
+ });
1083
+ return result;
1084
+ };
1085
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1086
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1087
+ return {
1088
+ ...sock,
1089
+ getPrivacyTokens,
1090
+ assertSessions,
1091
+ relayMessage,
1092
+ sendReceipt,
1093
+ sendReceipts,
1094
+ readMessages,
1095
+ refreshMediaConn,
1096
+ waUploadToServer,
1097
+ fetchPrivacySettings,
1098
+ sendPeerDataOperationMessage,
1099
+ createParticipantNodes,
1100
+ getUSyncDevices,
1101
+ messageRetryManager,
1102
+ updateMemberLabel,
1103
+ updateMediaMessage: async (message) => {
1104
+ const content = assertMediaContent(message.message);
1105
+ const mediaKey = content.mediaKey;
1106
+ const meId = authState.creds.me.id;
1107
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1108
+ let error = undefined;
1109
+ await Promise.all([
1110
+ sendNode(node),
1111
+ waitForMsgMediaUpdate(async (update) => {
1112
+ const result = update.find(c => c.key.id === message.key.id);
1113
+ if (result) {
1114
+ if (result.error) {
1115
+ error = result.error;
1116
+ }
1117
+ else {
1118
+ try {
1119
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1120
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1121
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1122
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1123
+ data: media,
1124
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1125
+ });
1126
+ }
1127
+ content.directPath = media.directPath;
1128
+ content.url = getUrlFromDirectPath(content.directPath);
1129
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1130
+ }
1131
+ catch (err) {
1132
+ error = err;
1133
+ }
1134
+ }
1135
+ return true;
1136
+ }
1137
+ })
1138
+ ]);
1139
+ if (error) {
1140
+ throw error;
1141
+ }
1142
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1143
+ return message;
1144
+ },
1145
+ sendMessage: async (jid, content, options = {}) => {
1146
+ const userJid = authState.creds.me.id;
1147
+ if (typeof content === 'object' &&
1148
+ 'disappearingMessagesInChat' in content &&
1149
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1150
+ isJidGroup(jid)) {
1151
+ const { disappearingMessagesInChat } = content;
1152
+ const value = typeof disappearingMessagesInChat === 'boolean'
1153
+ ? disappearingMessagesInChat
1154
+ ? WA_DEFAULT_EPHEMERAL
1155
+ : 0
1156
+ : disappearingMessagesInChat;
1157
+ await groupToggleEphemeral(jid, value);
1158
+ }
1159
+ else {
1160
+ const fullMsg = await generateWAMessage(jid, content, {
1161
+ logger,
1162
+ userJid,
1163
+ getUrlInfo: text => getUrlInfo(text, {
1164
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1165
+ fetchOpts: {
1166
+ timeout: 3000,
1167
+ ...(httpRequestOptions || {})
1168
+ },
1169
+ logger,
1170
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1171
+ }),
1172
+ //TODO: CACHE
1173
+ getProfilePicUrl: sock.profilePictureUrl,
1174
+ getCallLink: sock.createCallLink,
1175
+ upload: waUploadToServer,
1176
+ mediaCache: config.mediaCache,
1177
+ options: config.options,
1178
+ messageId: generateMessageIDV2(sock.user?.id),
1179
+ ...options
1180
+ });
1181
+ const isEventMsg = 'event' in content && !!content.event;
1182
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1183
+ const isEditMsg = 'edit' in content && !!content.edit;
1184
+ const isPinMsg = 'pin' in content && !!content.pin;
1185
+ const isPollMessage = 'poll' in content && !!content.poll;
1186
+ const additionalAttributes = {};
1187
+ const additionalNodes = [];
1188
+ // required for delete
1189
+ if (isDeleteMsg) {
1190
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1191
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1192
+ additionalAttributes.edit = '8';
1193
+ }
1194
+ else {
1195
+ additionalAttributes.edit = '7';
1196
+ }
1197
+ }
1198
+ else if (isEditMsg) {
1199
+ additionalAttributes.edit = '1';
1200
+ }
1201
+ else if (isPinMsg) {
1202
+ additionalAttributes.edit = '2';
1203
+ }
1204
+ else if (isPollMessage) {
1205
+ additionalNodes.push({
1206
+ tag: 'meta',
1207
+ attrs: {
1208
+ polltype: 'creation'
1209
+ }
1210
+ });
1211
+ }
1212
+ else if (isEventMsg) {
1213
+ additionalNodes.push({
1214
+ tag: 'meta',
1215
+ attrs: {
1216
+ event_type: 'creation'
1217
+ }
1218
+ });
1219
+ }
1220
+ await relayMessage(jid, fullMsg.message, {
1221
+ messageId: fullMsg.key.id,
1222
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1223
+ additionalAttributes,
1224
+ statusJidList: options.statusJidList,
1225
+ additionalNodes,
1226
+ onTarget: options.onTarget
1227
+ });
1228
+ if (config.emitOwnEvents) {
1229
+ process.nextTick(async () => {
1230
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1231
+ });
1232
+ }
1233
+ return fullMsg;
1234
+ }
1235
+ }
1236
+ };
1237
+ };
1238
+ //# sourceMappingURL=messages-send.js.map