@skyzopedia/baileys-mod 3.0.8 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1082 +1,1070 @@
1
- //=======================================================//
2
- import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from "../Utils/index.js";
3
- import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from "../WABinary/index.js";
4
- import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from "../Defaults/index.js";
5
- import { USyncQuery, USyncUser } from "../WAUSync/index.js";
6
- import { makeKeyedMutex } from "../Utils/make-mutex.js";
7
- import { makeNewsletterSocket } from "./newsletter.js";
8
- import { getUrlInfo } from "../Utils/link-preview.js";
9
- import { proto } from "../../WAProto/index.js";
10
- import NodeCache from "@cacheable/node-cache";
11
- import { Boom } from "@hapi/boom";
12
- import crypto from "crypto";
13
- //=======================================================//
1
+
2
+ /**
3
+ * Copyright © 2025 [ KyuuRzy ]
4
+ * All rights reserved. This source code is the property of [ ANU Team ].
5
+ *
6
+ * GitHub: https://github.com/kiuur
7
+ * Telegram: https://t.me/tskiofc
8
+ * Note: button?
9
+ */
10
+
11
+ import NodeCache from '@cacheable/node-cache';
12
+ import { Boom } from '@hapi/boom';
13
+ import { proto } from '../../WAProto/index.js';
14
+ import {
15
+ DEFAULT_CACHE_TTLS,
16
+ WA_DEFAULT_EPHEMERAL
17
+ } from '../Defaults/index.js';
18
+ import {
19
+ aggregateMessageKeysNotFromMe,
20
+ assertMediaContent,
21
+ bindWaitForEvent,
22
+ decryptMediaRetryData,
23
+ encodeNewsletterMessage,
24
+ encodeSignedDeviceIdentity,
25
+ encodeWAMessage,
26
+ encryptMediaRetryRequest,
27
+ extractDeviceJids,
28
+ generateMessageIDV2,
29
+ generateParticipantHashV2,
30
+ generateWAMessage,
31
+ getStatusCodeForMediaRetry,
32
+ getUrlFromDirectPath,
33
+ getWAUploadToServer,
34
+ MessageRetryManager,
35
+ normalizeMessageContent,
36
+ parseAndInjectE2ESessions,
37
+ unixTimestampSeconds
38
+ } from '../Utils/index.js';
39
+ import {
40
+ areJidsSameUser,
41
+ getBinaryNodeChild,
42
+ getBinaryNodeChildren,
43
+ getAdditionalNode,
44
+ getBinaryNodeFilter,
45
+ isHostedLidUser,
46
+ isHostedPnUser,
47
+ isJidGroup,
48
+ isLidUser,
49
+ isPnUser,
50
+ jidDecode,
51
+ jidEncode,
52
+ jidNormalizedUser,
53
+ S_WHATSAPP_NET
54
+ } from '../WABinary/index.js';
55
+ import { getUrlInfo } from '../Utils/link-preview.js';
56
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
57
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
58
+ import { makeNewsletterSocket } from './newsletter.js';
14
59
  export const makeMessagesSocket = (config) => {
15
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
16
- const sock = makeNewsletterSocket(config);
17
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
18
- const userDevicesCache = config.userDevicesCache ||
19
- new NodeCache({
20
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
21
- useClones: false
22
- });
23
- const peerSessionsCache = new NodeCache({
24
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
25
- useClones: false
26
- });
27
- const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
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: {} }]
60
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
61
+ const sock = makeNewsletterSocket(config);
62
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
63
+ const userDevicesCache = config.userDevicesCache ||
64
+ new NodeCache({
65
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
66
+ useClones: false
42
67
  });
43
- const mediaConnNode = getBinaryNodeChild(result, "media_conn");
68
+ const peerSessionsCache = new NodeCache({
69
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
70
+ useClones: false
71
+ });
72
+ // Initialize message retry manager if enabled
73
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
74
+ // Prevent race conditions in Signal session encryption by user
75
+ const encryptionMutex = makeKeyedMutex();
76
+ let mediaConn;
77
+ const refreshMediaConn = async (forceGet = false) => {
78
+ const media = await mediaConn;
79
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
80
+ mediaConn = (async () => {
81
+ const result = await query({
82
+ tag: 'iq',
83
+ attrs: {
84
+ type: 'set',
85
+ xmlns: 'w:m',
86
+ to: S_WHATSAPP_NET
87
+ },
88
+ content: [{ tag: 'media_conn', attrs: {} }]
89
+ });
90
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
91
+ // TODO: explore full length of data that whatsapp provides
92
+ const node = {
93
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
94
+ hostname: attrs.hostname,
95
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
96
+ })),
97
+ auth: mediaConnNode.attrs.auth,
98
+ ttl: +mediaConnNode.attrs.ttl,
99
+ fetchDate: new Date()
100
+ };
101
+ logger.debug('fetched media conn');
102
+ return node;
103
+ })();
104
+ }
105
+ return mediaConn;
106
+ };
107
+ /**
108
+ * generic send receipt function
109
+ * used for receipts of phone call, read, delivery etc.
110
+ * */
111
+ const sendReceipt = async (jid, participant, messageIds, type) => {
112
+ if (!messageIds || messageIds.length === 0) {
113
+ throw new Boom('missing ids in receipt');
114
+ }
44
115
  const node = {
45
- hosts: getBinaryNodeChildren(mediaConnNode, "host").map(({ attrs }) => ({
46
- hostname: attrs.hostname,
47
- maxContentLengthBytes: +attrs.maxContentLengthBytes
48
- })),
49
- auth: mediaConnNode.attrs.auth,
50
- ttl: +mediaConnNode.attrs.ttl,
51
- fetchDate: new Date()
116
+ tag: 'receipt',
117
+ attrs: {
118
+ id: messageIds[0]
119
+ }
52
120
  };
53
- logger.debug("fetched media conn");
54
- return node;
55
- })();
56
- }
57
- return mediaConn;
58
- };
59
- const sendReceipt = async (jid, participant, messageIds, type) => {
60
- if (!messageIds || messageIds.length === 0) {
61
- throw new Boom("missing ids in receipt");
62
- }
63
- const node = {
64
- tag: "receipt",
65
- attrs: {
66
- id: messageIds[0]
67
- }
68
- };
69
- const isReadReceipt = type === "read" || type === "read-self";
70
- if (isReadReceipt) {
71
- node.attrs.t = unixTimestampSeconds().toString();
72
- }
73
- if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
74
- node.attrs.recipient = jid;
75
- node.attrs.to = participant;
76
- }
77
- else {
78
- node.attrs.to = jid;
79
- if (participant) {
80
- node.attrs.participant = participant;
81
- }
82
- }
83
- if (type) {
84
- node.attrs.type = type;
85
- }
86
- const remainingMessageIds = messageIds.slice(1);
87
- if (remainingMessageIds.length) {
88
- node.content = [
89
- {
90
- tag: "list",
91
- attrs: {},
92
- content: remainingMessageIds.map(id => ({
93
- tag: "item",
94
- attrs: { id }
95
- }))
121
+ const isReadReceipt = type === 'read' || type === 'read-self';
122
+ if (isReadReceipt) {
123
+ node.attrs.t = unixTimestampSeconds().toString();
96
124
  }
97
- ];
98
- }
99
- logger.debug({ attrs: node.attrs, messageIds }, "sending receipt for messages");
100
- await sendNode(node);
101
- };
102
- const sendReceipts = async (keys, type) => {
103
- const recps = aggregateMessageKeysNotFromMe(keys);
104
- for (const { jid, participant, messageIds } of recps) {
105
- await sendReceipt(jid, participant, messageIds, type);
106
- }
107
- };
108
- const readMessages = async (keys) => {
109
- const privacySettings = await fetchPrivacySettings();
110
- const readType = privacySettings.readreceipts === "all" ? "read" : "read-self";
111
- await sendReceipts(keys, readType);
112
- };
113
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
114
- const deviceResults = [];
115
- if (!useCache) {
116
- logger.debug("not using cache for devices");
117
- }
118
- const toFetch = [];
119
- const jidsWithUser = jids
120
- .map(jid => {
121
- const decoded = jidDecode(jid);
122
- const user = decoded?.user;
123
- const device = decoded?.device;
124
- const isExplicitDevice = typeof device === "number" && device >= 0;
125
- if (isExplicitDevice && user) {
126
- deviceResults.push({
127
- user,
128
- device,
129
- jid
130
- });
131
- return null;
132
- }
133
- jid = jidNormalizedUser(jid);
134
- return { jid, user };
135
- })
136
- .filter(jid => jid !== null);
137
- let mgetDevices;
138
- if (useCache && userDevicesCache.mget) {
139
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
140
- mgetDevices = await userDevicesCache.mget(usersToFetch);
141
- }
142
- for (const { jid, user } of jidsWithUser) {
143
- if (useCache) {
144
- const devices = mgetDevices?.[user] ||
145
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
146
- if (devices) {
147
- const devicesWithJid = devices.map(d => ({
148
- ...d,
149
- jid: jidEncode(d.user, d.server, d.device)
150
- }));
151
- deviceResults.push(...devicesWithJid);
152
- logger.trace({ user }, "using cache for devices");
125
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
126
+ node.attrs.recipient = jid;
127
+ node.attrs.to = participant;
153
128
  }
154
129
  else {
155
- toFetch.push(jid);
130
+ node.attrs.to = jid;
131
+ if (participant) {
132
+ node.attrs.participant = participant;
133
+ }
156
134
  }
157
- }
158
- else {
159
- toFetch.push(jid);
160
- }
161
- }
162
- if (!toFetch.length) {
163
- return deviceResults;
164
- }
165
- const requestedLidUsers = new Set();
166
- for (const jid of toFetch) {
167
- if (isLidUser(jid) || isHostedLidUser(jid)) {
168
- const user = jidDecode(jid)?.user;
169
- if (user)
170
- requestedLidUsers.add(user);
171
- }
172
- }
173
- const query = new USyncQuery().withContext("message").withDeviceProtocol().withLIDProtocol();
174
- for (const jid of toFetch) {
175
- query.withUser(new USyncUser().withId(jid));
176
- }
177
- const result = await sock.executeUSyncQuery(query);
178
- if (result) {
179
- const lidResults = result.list.filter(a => !!a.lid);
180
- if (lidResults.length > 0) {
181
- logger.trace("Storing LID maps from device call");
182
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
183
- }
184
- const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
185
- const deviceMap = {};
186
- for (const item of extracted) {
187
- deviceMap[item.user] = deviceMap[item.user] || [];
188
- deviceMap[item.user]?.push(item);
189
- }
190
- for (const [user, userDevices] of Object.entries(deviceMap)) {
191
- const isLidUser = requestedLidUsers.has(user);
192
- for (const item of userDevices) {
193
- const finalJid = isLidUser
194
- ? jidEncode(user, item.server, item.device)
195
- : jidEncode(item.user, item.server, item.device);
196
- deviceResults.push({
197
- ...item,
198
- jid: finalJid
199
- });
200
- logger.debug({
201
- user: item.user,
202
- device: item.device,
203
- finalJid,
204
- usedLid: isLidUser
205
- }, "Processed device with LID priority");
135
+ if (type) {
136
+ node.attrs.type = type;
206
137
  }
207
- }
208
- if (userDevicesCache.mset) {
209
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
210
- }
211
- else {
212
- for (const key in deviceMap) {
213
- if (deviceMap[key])
214
- await userDevicesCache.set(key, deviceMap[key]);
138
+ const remainingMessageIds = messageIds.slice(1);
139
+ if (remainingMessageIds.length) {
140
+ node.content = [
141
+ {
142
+ tag: 'list',
143
+ attrs: {},
144
+ content: remainingMessageIds.map(id => ({
145
+ tag: 'item',
146
+ attrs: { id }
147
+ }))
148
+ }
149
+ ];
215
150
  }
216
- }
217
- const userDeviceUpdates = {};
218
- for (const [userId, devices] of Object.entries(deviceMap)) {
219
- if (devices && devices.length > 0) {
220
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || "0");
151
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
152
+ await sendNode(node);
153
+ };
154
+ /** Correctly bulk send receipts to multiple chats, participants */
155
+ const sendReceipts = async (keys, type) => {
156
+ const recps = aggregateMessageKeysNotFromMe(keys);
157
+ for (const { jid, participant, messageIds } of recps) {
158
+ await sendReceipt(jid, participant, messageIds, type);
221
159
  }
222
- }
223
- if (Object.keys(userDeviceUpdates).length > 0) {
224
- try {
225
- await authState.keys.set({ "device-list": userDeviceUpdates });
226
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, "stored user device lists for bulk migration");
160
+ };
161
+ /** Bulk read messages. Keys can be from different chats & participants */
162
+ const readMessages = async (keys) => {
163
+ const privacySettings = await fetchPrivacySettings();
164
+ // based on privacy settings, we have to change the read type
165
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
166
+ await sendReceipts(keys, readType);
167
+ };
168
+ /** Fetch all the devices we've to send a message to */
169
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
170
+ const deviceResults = [];
171
+ if (!useCache) {
172
+ logger.debug('not using cache for devices');
227
173
  }
228
- catch (error) {
229
- logger.warn({ error }, "failed to store user device lists");
174
+ const toFetch = [];
175
+ const jidsWithUser = jids
176
+ .map(jid => {
177
+ const decoded = jidDecode(jid);
178
+ const user = decoded?.user;
179
+ const device = decoded?.device;
180
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
181
+ if (isExplicitDevice && user) {
182
+ deviceResults.push({
183
+ user,
184
+ device,
185
+ jid
186
+ });
187
+ return null;
188
+ }
189
+ jid = jidNormalizedUser(jid);
190
+ return { jid, user };
191
+ })
192
+ .filter(jid => jid !== null);
193
+ let mgetDevices;
194
+ if (useCache && userDevicesCache.mget) {
195
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
196
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
230
197
  }
231
- }
232
- }
233
- return deviceResults;
234
- };
235
- const assertSessions = async (jids) => {
236
- let didFetchNewSession = false;
237
- const uniqueJids = [...new Set(jids)];
238
- const jidsRequiringFetch = [];
239
- logger.debug({ jids }, "assertSessions call with jids");
240
- for (const jid of uniqueJids) {
241
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
242
- const cachedSession = peerSessionsCache.get(signalId);
243
- if (cachedSession !== undefined) {
244
- if (cachedSession) {
245
- continue;
198
+ for (const { jid, user } of jidsWithUser) {
199
+ if (useCache) {
200
+ const devices = mgetDevices?.[user] ||
201
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
202
+ if (devices) {
203
+ const devicesWithJid = devices.map(d => ({
204
+ ...d,
205
+ jid: jidEncode(d.user, d.server, d.device)
206
+ }));
207
+ deviceResults.push(...devicesWithJid);
208
+ logger.trace({ user }, 'using cache for devices');
209
+ }
210
+ else {
211
+ toFetch.push(jid);
212
+ }
213
+ }
214
+ else {
215
+ toFetch.push(jid);
216
+ }
246
217
  }
247
- }
248
- else {
249
- const sessionValidation = await signalRepository.validateSession(jid);
250
- const hasSession = sessionValidation.exists;
251
- peerSessionsCache.set(signalId, hasSession);
252
- if (hasSession) {
253
- continue;
218
+ if (!toFetch.length) {
219
+ return deviceResults;
254
220
  }
255
- }
256
- jidsRequiringFetch.push(jid);
257
- }
258
- if (jidsRequiringFetch.length) {
259
- const wireJids = [
260
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
261
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
262
- ];
263
- logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
264
- const result = await query({
265
- tag: "iq",
266
- attrs: {
267
- xmlns: "encrypt",
268
- type: "get",
269
- to: S_WHATSAPP_NET
270
- },
271
- content: [
272
- {
273
- tag: "key",
274
- attrs: {},
275
- content: wireJids.map(jid => ({
276
- tag: "user",
277
- attrs: { jid }
278
- }))
279
- }
280
- ]
281
- });
282
- await parseAndInjectE2ESessions(result, signalRepository);
283
- didFetchNewSession = true;
284
- for (const wireJid of wireJids) {
285
- const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
286
- peerSessionsCache.set(signalId, true);
287
- }
288
- }
289
- return didFetchNewSession;
290
- };
291
- const sendPeerDataOperationMessage = async (pdoMessage) => {
292
- if (!authState.creds.me?.id) {
293
- throw new Boom("Not authenticated");
294
- }
295
- const protocolMessage = {
296
- protocolMessage: {
297
- peerDataOperationRequestMessage: pdoMessage,
298
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
299
- }
300
- };
301
- const meJid = jidNormalizedUser(authState.creds.me.id);
302
- const msgId = await relayMessage(meJid, protocolMessage, {
303
- additionalAttributes: {
304
- category: "peer",
305
- push_priority: "high_force"
306
- },
307
- additionalNodes: [
308
- {
309
- tag: "meta",
310
- attrs: { appdata: "default" }
221
+ const requestedLidUsers = new Set();
222
+ for (const jid of toFetch) {
223
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
224
+ const user = jidDecode(jid)?.user;
225
+ if (user)
226
+ requestedLidUsers.add(user);
227
+ }
311
228
  }
312
- ]
313
- });
314
- return msgId;
315
- };
316
- const offerCall = async (toJid, isVideo = false) => {
317
- const callId = crypto
318
- .randomBytes(16)
319
- .toString("hex")
320
- .toUpperCase()
321
- .substring(0, 64);
322
- const offerContent = [];
323
- offerContent.push({
324
- tag: "audio",
325
- attrs: { enc: "opus", rate: "16000" },
326
- content: undefined,
327
- });
328
- offerContent.push({
329
- tag: "audio",
330
- attrs: { enc: "opus", rate: "8000" },
331
- content: undefined,
332
- });
333
- if (isVideo) {
334
- offerContent.push({
335
- tag: "video",
336
- attrs: {
337
- enc: "vp8",
338
- dec: "vp8",
339
- orientation: "0",
340
- screen_width: "1920",
341
- screen_height: "1080",
342
- device_orientation: "0",
343
- },
344
- content: undefined,
345
- });
346
- }
347
- offerContent.push({
348
- tag: "net",
349
- attrs: { medium: "3" },
350
- content: undefined,
351
- });
352
- offerContent.push({
353
- tag: "capability",
354
- attrs: { ver: "1" },
355
- content: new Uint8Array([1, 4, 255, 131, 207, 4]),
356
- });
357
- offerContent.push({
358
- tag: "encopt",
359
- attrs: { keygen: "2" },
360
- content: undefined,
361
- });
362
- const encKey = crypto.randomBytes(32);
363
- const rawDevices = await getUSyncDevices([toJid], true, false);
364
- const devices = rawDevices.map(({ user, device }) =>
365
- jidEncode(user, "s.whatsapp.net", device)
366
- );
367
- await assertSessions(devices, true);
368
- const { nodes: destinations, shouldIncludeDeviceIdentity } =
369
- await createParticipantNodes(
370
- devices,
371
- { call: { callKey: new Uint8Array(encKey) } },
372
- { count: "0" }
373
- );
374
- offerContent.push({ tag: "destination", attrs: {}, content: destinations });
375
- if (shouldIncludeDeviceIdentity) {
376
- offerContent.push({
377
- tag: "device-identity",
378
- attrs: {},
379
- content: encodeSignedDeviceIdentity(
380
- authState.creds.account,
381
- true
382
- ),
383
- });
384
- }
385
- const stanza = {
386
- tag: "call",
387
- attrs: {
388
- id: generateMessageIDV2(),
389
- to: toJid,
390
- },
391
- content: [
392
- {
393
- tag: "offer",
394
- attrs: {
395
- "call-id": callId,
396
- "call-creator": authState.creds.me.id,
397
- },
398
- content: offerContent,
399
- },
400
- ],
401
- };
402
- await query(stanza);
403
- return {
404
- id: callId,
405
- to: toJid,
229
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
230
+ for (const jid of toFetch) {
231
+ 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
232
+ }
233
+ const result = await sock.executeUSyncQuery(query);
234
+ if (result) {
235
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
236
+ const lidResults = result.list.filter(a => !!a.lid);
237
+ if (lidResults.length > 0) {
238
+ logger.trace('Storing LID maps from device call');
239
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
240
+ }
241
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
242
+ const deviceMap = {};
243
+ for (const item of extracted) {
244
+ deviceMap[item.user] = deviceMap[item.user] || [];
245
+ deviceMap[item.user]?.push(item);
246
+ }
247
+ // Process each user's devices as a group for bulk LID migration
248
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
249
+ const isLidUser = requestedLidUsers.has(user);
250
+ // Process all devices for this user
251
+ for (const item of userDevices) {
252
+ const finalJid = isLidUser
253
+ ? jidEncode(user, item.server, item.device)
254
+ : jidEncode(item.user, item.server, item.device);
255
+ deviceResults.push({
256
+ ...item,
257
+ jid: finalJid
258
+ });
259
+ logger.debug({
260
+ user: item.user,
261
+ device: item.device,
262
+ finalJid,
263
+ usedLid: isLidUser
264
+ }, 'Processed device with LID priority');
265
+ }
266
+ }
267
+ if (userDevicesCache.mset) {
268
+ // if the cache supports mset, we can set all devices in one go
269
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
270
+ }
271
+ else {
272
+ for (const key in deviceMap) {
273
+ if (deviceMap[key])
274
+ await userDevicesCache.set(key, deviceMap[key]);
275
+ }
276
+ }
277
+ const userDeviceUpdates = {};
278
+ for (const [userId, devices] of Object.entries(deviceMap)) {
279
+ if (devices && devices.length > 0) {
280
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
281
+ }
282
+ }
283
+ if (Object.keys(userDeviceUpdates).length > 0) {
284
+ try {
285
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
286
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
287
+ }
288
+ catch (error) {
289
+ logger.warn({ error }, 'failed to store user device lists');
290
+ }
291
+ }
292
+ }
293
+ return deviceResults;
406
294
  };
407
- };
408
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
409
- if (!recipientJids.length) {
410
- return { nodes: [], shouldIncludeDeviceIdentity: false };
411
- }
412
- const patched = await patchMessageBeforeSending(message, recipientJids);
413
- const patchedMessages = Array.isArray(patched)
414
- ? patched
415
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
416
- let shouldIncludeDeviceIdentity = false;
417
- const meId = authState.creds.me.id;
418
- const meLid = authState.creds.me?.lid;
419
- const meLidUser = meLid ? jidDecode(meLid)?.user : null;
420
- const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
421
- if (!jid)
422
- return null;
423
- let msgToEncrypt = patchedMessage;
424
- if (dsmMessage) {
425
- const { user: targetUser } = jidDecode(jid);
426
- const { user: ownPnUser } = jidDecode(meId);
427
- const ownLidUser = meLidUser;
428
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
429
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
430
- if (isOwnUser && !isExactSenderDevice) {
431
- msgToEncrypt = dsmMessage;
432
- logger.debug({ jid, targetUser }, "Using DSM for own device");
295
+ const assertSessions = async (jids) => {
296
+ let didFetchNewSession = false;
297
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
298
+ const jidsRequiringFetch = [];
299
+ logger.debug({ jids }, 'assertSessions call with jids');
300
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
301
+ for (const jid of uniqueJids) {
302
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
303
+ const cachedSession = peerSessionsCache.get(signalId);
304
+ if (cachedSession !== undefined) {
305
+ if (cachedSession) {
306
+ continue; // Session exists in cache
307
+ }
308
+ }
309
+ else {
310
+ const sessionValidation = await signalRepository.validateSession(jid);
311
+ const hasSession = sessionValidation.exists;
312
+ peerSessionsCache.set(signalId, hasSession);
313
+ if (hasSession) {
314
+ continue;
315
+ }
316
+ }
317
+ jidsRequiringFetch.push(jid);
433
318
  }
434
- }
435
- const bytes = encodeWAMessage(msgToEncrypt);
436
- const mutexKey = jid;
437
- const node = await encryptionMutex.mutex(mutexKey, async () => {
438
- const { type, ciphertext } = await signalRepository.encryptMessage({
439
- jid,
440
- data: bytes
441
- });
442
- if (type === "pkmsg") {
443
- shouldIncludeDeviceIdentity = true;
319
+ if (jidsRequiringFetch.length) {
320
+ // LID if mapped, otherwise original
321
+ const wireJids = [
322
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
323
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
324
+ ];
325
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
326
+ const result = await query({
327
+ tag: 'iq',
328
+ attrs: {
329
+ xmlns: 'encrypt',
330
+ type: 'get',
331
+ to: S_WHATSAPP_NET
332
+ },
333
+ content: [
334
+ {
335
+ tag: 'key',
336
+ attrs: {},
337
+ content: wireJids.map(jid => ({
338
+ tag: 'user',
339
+ attrs: { jid }
340
+ }))
341
+ }
342
+ ]
343
+ });
344
+ await parseAndInjectE2ESessions(result, signalRepository);
345
+ didFetchNewSession = true;
346
+ // Cache fetched sessions using wire JIDs
347
+ for (const wireJid of wireJids) {
348
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
349
+ peerSessionsCache.set(signalId, true);
350
+ }
351
+ }
352
+ return didFetchNewSession;
353
+ };
354
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
355
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
356
+ if (!authState.creds.me?.id) {
357
+ throw new Boom('Not authenticated');
444
358
  }
445
- return {
446
- tag: "to",
447
- attrs: { jid },
448
- content: [
449
- {
450
- tag: "enc",
451
- attrs: {
452
- v: "2",
453
- type,
454
- ...(extraAttrs || {})
455
- },
456
- content: ciphertext
359
+ const protocolMessage = {
360
+ protocolMessage: {
361
+ peerDataOperationRequestMessage: pdoMessage,
362
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
457
363
  }
458
- ]
459
364
  };
460
- });
461
- return node;
462
- });
463
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
464
- return { nodes, shouldIncludeDeviceIdentity };
465
- };
466
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
467
- const meId = authState.creds.me.id;
468
- const meLid = authState.creds.me?.lid;
469
- const isRetryResend = Boolean(participant?.jid);
470
- let shouldIncludeDeviceIdentity = isRetryResend;
471
- const statusJid = "status@broadcast";
472
- const { user, server } = jidDecode(jid);
473
- const isGroup = server === "g.us";
474
- const isStatus = jid === statusJid;
475
- const isLid = server === "lid";
476
- const isNewsletter = server === "newsletter";
477
- const finalJid = jid;
478
- msgId = msgId || generateMessageIDV2(meId);
479
- useUserDevicesCache = useUserDevicesCache !== false;
480
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
481
- const participants = [];
482
- const destinationJid = !isStatus ? finalJid : statusJid;
483
- const binaryNodeContent = [];
484
- const devices = [];
485
- const meMsg = {
486
- deviceSentMessage: {
487
- destinationJid,
488
- message
489
- },
490
- messageContextInfo: message.messageContextInfo
365
+ const meJid = jidNormalizedUser(authState.creds.me.id);
366
+ const msgId = await relayMessage(meJid, protocolMessage, {
367
+ additionalAttributes: {
368
+ category: 'peer',
369
+ push_priority: 'high_force'
370
+ },
371
+ additionalNodes: [
372
+ {
373
+ tag: 'meta',
374
+ attrs: { appdata: 'default' }
375
+ }
376
+ ]
377
+ });
378
+ return msgId;
491
379
  };
492
- const extraAttrs = {};
493
- if (participant) {
494
- if (!isGroup && !isStatus) {
495
- additionalAttributes = { ...additionalAttributes, device_fanout: "false" };
496
- }
497
- const { user, device } = jidDecode(participant.jid);
498
- devices.push({
499
- user,
500
- device,
501
- jid: participant.jid
502
- });
503
- }
504
- await authState.keys.transaction(async () => {
505
- const mediaType = getMediaType(message);
506
- if (mediaType) {
507
- extraAttrs["mediatype"] = mediaType;
508
- }
509
- if (isNewsletter) {
510
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
511
- const bytes = encodeNewsletterMessage(patched);
512
- binaryNodeContent.push({
513
- tag: "plaintext",
514
- attrs: {},
515
- content: bytes
380
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
381
+ if (!recipientJids.length) {
382
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
383
+ }
384
+ const patched = await patchMessageBeforeSending(message, recipientJids);
385
+ const patchedMessages = Array.isArray(patched)
386
+ ? patched
387
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
388
+ let shouldIncludeDeviceIdentity = false;
389
+ const meId = authState.creds.me.id;
390
+ const meLid = authState.creds.me?.lid;
391
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
392
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
393
+ if (!jid)
394
+ return null;
395
+ let msgToEncrypt = patchedMessage;
396
+ if (dsmMessage) {
397
+ const { user: targetUser } = jidDecode(jid);
398
+ const { user: ownPnUser } = jidDecode(meId);
399
+ const ownLidUser = meLidUser;
400
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
401
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
402
+ if (isOwnUser && !isExactSenderDevice) {
403
+ msgToEncrypt = dsmMessage;
404
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
405
+ }
406
+ }
407
+ const bytes = encodeWAMessage(msgToEncrypt);
408
+ const mutexKey = jid;
409
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
410
+ const { type, ciphertext } = await signalRepository.encryptMessage({
411
+ jid,
412
+ data: bytes
413
+ });
414
+ if (type === 'pkmsg') {
415
+ shouldIncludeDeviceIdentity = true;
416
+ }
417
+ return {
418
+ tag: 'to',
419
+ attrs: { jid },
420
+ content: [
421
+ {
422
+ tag: 'enc',
423
+ attrs: {
424
+ v: '2',
425
+ type,
426
+ ...(extraAttrs || {})
427
+ },
428
+ content: ciphertext
429
+ }
430
+ ]
431
+ };
432
+ });
433
+ return node;
516
434
  });
517
- const stanza = {
518
- tag: "message",
519
- attrs: {
520
- to: jid,
521
- id: msgId,
522
- type: getMessageType(message),
523
- ...(additionalAttributes || {})
524
- },
525
- content: binaryNodeContent
435
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
436
+ return { nodes, shouldIncludeDeviceIdentity };
437
+ };
438
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = true }) => {
439
+ // let shouldIncludeDeviceIdentity = false;
440
+ let didPushAdditional = false
441
+ const meId = authState.creds.me.id;
442
+ const meLid = authState.creds.me?.lid;
443
+ const isRetryResend = Boolean(participant?.jid);
444
+ let shouldIncludeDeviceIdentity = isRetryResend;
445
+ const statusJid = 'status@broadcast';
446
+ const { user, server } = jidDecode(jid);
447
+ const isGroup = server === 'g.us';
448
+ const isStatus = jid === statusJid;
449
+ const isLid = server === 'lid';
450
+ const isNewsletter = server === 'newsletter';
451
+ const isPrivate = server === 's.whatsapp.net'
452
+ const finalJid = jid;
453
+ msgId = msgId || generateMessageIDV2(meId);
454
+ useUserDevicesCache = useUserDevicesCache !== false;
455
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
456
+ const participants = [];
457
+ const destinationJid = !isStatus ? finalJid : statusJid;
458
+ const binaryNodeContent = [];
459
+ const devices = [];
460
+ const meMsg = {
461
+ deviceSentMessage: {
462
+ destinationJid,
463
+ message
464
+ },
465
+ messageContextInfo: message.messageContextInfo
526
466
  };
527
- logger.debug({ msgId }, `sending newsletter message to ${jid}`);
528
- await sendNode(stanza);
529
- return;
530
- }
531
- if (normalizeMessageContent(message)?.pinInChatMessage) {
532
- extraAttrs["decrypt-fail"] = "hide";
533
- }
534
- if (isGroup || isStatus) {
535
- const [groupData, senderKeyMap] = await Promise.all([
536
- (async () => {
537
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
538
- if (groupData && Array.isArray(groupData?.participants)) {
539
- logger.trace({ jid, participants: groupData.participants.length }, "using cached group metadata");
467
+ const extraAttrs = {};
468
+ const messages = normalizeMessageContent(message)
469
+ const buttonType = getButtonType(messages);
470
+ if (participant) {
471
+ if (!isGroup && !isStatus) {
472
+ additionalAttributes = {
473
+ ...additionalAttributes,
474
+ device_fanout: 'false'
475
+ };
540
476
  }
541
- else if (!isStatus) {
542
- groupData = await groupMetadata(jid);
477
+ const { user, device } = jidDecode(participant.jid);
478
+ devices.push({
479
+ user,
480
+ device,
481
+ jid: participant.jid
482
+ });
483
+ }
484
+ await authState.keys.transaction(async () => {
485
+ const mediaType = getMediaType(message);
486
+ if (mediaType) {
487
+ extraAttrs['mediatype'] = mediaType;
543
488
  }
544
- return groupData;
545
- })(),
546
- (async () => {
547
- if (!participant && !isStatus) {
548
- const result = await authState.keys.get("sender-key-memory", [jid]);
549
- return result[jid] || {};
489
+
490
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
491
+ extraAttrs['decrypt-fail'] = 'hide'
492
+ }
493
+
494
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
495
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
550
496
  }
551
- return {};
552
- })()
553
- ]);
554
- if (!participant) {
555
- const participantsList = [];
556
- if (isStatus) {
557
- if (statusJidList?.length)
558
- participantsList.push(...statusJidList);
559
- }
560
- else {
561
- let groupAddressingMode = "lid";
562
- if (groupData) {
563
- participantsList.push(...groupData.participants.map(p => p.id));
564
- groupAddressingMode = groupData?.addressingMode || groupAddressingMode;
497
+
498
+ if (isGroup || isStatus) {
499
+ const [groupData, senderKeyMap] = await Promise.all([
500
+ (async () => {
501
+ 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?
502
+ if (groupData && Array.isArray(groupData?.participants)) {
503
+ logger.trace({
504
+ jid,
505
+ participants: groupData.participants.length
506
+ }, 'using cached group metadata');
507
+ }
508
+ else if (!isStatus) {
509
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
510
+ }
511
+ return groupData;
512
+ })(),
513
+ (async () => {
514
+ if (!participant && !isStatus) {
515
+ // what if sender memory is less accurate than the cached metadata
516
+ // on participant change in group, we should do sender memory manipulation
517
+ 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?
518
+ return result[jid] || {};
519
+ }
520
+ return {};
521
+ })()
522
+ ]);
523
+ if (!participant) {
524
+ const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
525
+ if (isStatus && statusJidList) {
526
+ participantsList.push(...statusJidList);
527
+ }
528
+ // if (!isStatus) {
529
+ // additionalAttributes = {
530
+ // ...additionalAttributes,
531
+ // addressing_mode: groupData?.addressingMode || 'pn'
532
+ // };
533
+ // }
534
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
535
+ devices.push(...additionalDevices);
536
+ }
537
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
538
+ additionalAttributes = {
539
+ ...additionalAttributes,
540
+ expiration: groupData.ephemeralDuration.toString()
541
+ };
542
+ }
543
+ const patched = await patchMessageBeforeSending(message);
544
+ if (Array.isArray(patched)) {
545
+ throw new Boom('Per-jid patching is not supported in groups');
546
+ }
547
+ const bytes = encodeWAMessage(patched);
548
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
549
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
550
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
551
+ group: destinationJid,
552
+ data: bytes,
553
+ meId: groupSenderIdentity
554
+ });
555
+ const senderKeyRecipients = [];
556
+ for (const device of devices) {
557
+ const deviceJid = device.jid;
558
+ const hasKey = !!senderKeyMap[deviceJid];
559
+ if ((!hasKey || !!participant) &&
560
+ !isHostedLidUser(deviceJid) &&
561
+ !isHostedPnUser(deviceJid) &&
562
+ device.device !== 99) {
563
+ //todo: revamp all this logic
564
+ // 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
565
+ senderKeyRecipients.push(deviceJid);
566
+ senderKeyMap[deviceJid] = true;
567
+ }
568
+ }
569
+ if (senderKeyRecipients.length) {
570
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
571
+ const senderKeyMsg = {
572
+ senderKeyDistributionMessage: {
573
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
574
+ groupId: destinationJid
575
+ }
576
+ };
577
+ const senderKeySessionTargets = senderKeyRecipients;
578
+ await assertSessions(senderKeySessionTargets);
579
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
580
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
581
+ participants.push(...result.nodes);
582
+ }
583
+ if (isRetryResend) {
584
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
585
+ data: bytes,
586
+ jid: participant?.jid
587
+ });
588
+ binaryNodeContent.push({
589
+ tag: 'enc',
590
+ attrs: {
591
+ v: '2',
592
+ type,
593
+ count: participant.count.toString()
594
+ },
595
+ content: encryptedContent
596
+ });
597
+ }
598
+ else {
599
+ binaryNodeContent.push({
600
+ tag: 'enc',
601
+ attrs: {
602
+ v: '2',
603
+ type: 'skmsg',
604
+ ...extraAttrs
605
+ },
606
+ content: ciphertext
607
+ });
608
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
609
+ }
565
610
  }
566
- additionalAttributes = {
567
- ...additionalAttributes,
568
- addressing_mode: groupAddressingMode
611
+ else {
612
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
613
+ // TODO: investigate if this is true
614
+ let ownId = meId;
615
+ if (isLid && meLid) {
616
+ ownId = meLid;
617
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
618
+ }
619
+ else {
620
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
621
+ }
622
+ const { user: ownUser } = jidDecode(ownId);
623
+ if (!participant) {
624
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
625
+ devices.push({
626
+ user,
627
+ device: 0,
628
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
629
+ });
630
+ if (user !== ownUser) {
631
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
632
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
633
+ devices.push({
634
+ user: ownUserForAddressing,
635
+ device: 0,
636
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
637
+ });
638
+ }
639
+ if (additionalAttributes?.['category'] !== 'peer') {
640
+ // Clear placeholders and enumerate actual devices
641
+ devices.length = 0;
642
+ // Use conversation-appropriate sender identity
643
+ const senderIdentity = isLid && meLid
644
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
645
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
646
+ // Enumerate devices for sender and target with consistent addressing
647
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
648
+ devices.push(...sessionDevices);
649
+ logger.debug({
650
+ deviceCount: devices.length,
651
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
652
+ }, 'Device enumeration complete with unified addressing');
653
+ }
654
+ }
655
+ const allRecipients = [];
656
+ const meRecipients = [];
657
+ const otherRecipients = [];
658
+ const { user: mePnUser } = jidDecode(meId);
659
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
660
+ for (const { user, jid } of devices) {
661
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
662
+ if (isExactSenderDevice) {
663
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
664
+ continue;
665
+ }
666
+ // Check if this is our device (could match either PN or LID user)
667
+ const isMe = user === mePnUser || user === meLidUser;
668
+ if (isMe) {
669
+ meRecipients.push(jid);
670
+ }
671
+ else {
672
+ otherRecipients.push(jid);
673
+ }
674
+ allRecipients.push(jid);
675
+ }
676
+ await assertSessions(allRecipients);
677
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
678
+ // For own devices: use DSM if available (1:1 chats only)
679
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
680
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
681
+ ]);
682
+ participants.push(...meNodes);
683
+ participants.push(...otherNodes);
684
+ /* if (meRecipients.length > 0 || otherRecipients.length > 0) {
685
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
686
+ }*/
687
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
688
+ }
689
+ if (participants.length) {
690
+ if (additionalAttributes?.['category'] === 'peer') {
691
+ const peerNode = participants[0]?.content?.[0];
692
+ if (peerNode) {
693
+ binaryNodeContent.push(peerNode); // push only enc
694
+ }
695
+ }
696
+ else {
697
+ binaryNodeContent.push({
698
+ tag: 'participants',
699
+ attrs: {},
700
+ content: participants
701
+ });
702
+ }
703
+ }
704
+ const stanza = {
705
+ tag: 'message',
706
+ attrs: {
707
+ id: msgId,
708
+ to: destinationJid,
709
+ type: getTypeMessage(messages),
710
+ ...(additionalAttributes || {})
711
+ },
712
+ content: binaryNodeContent
569
713
  };
570
- }
571
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
572
- devices.push(...additionalDevices);
714
+ // if the participant to send to is explicitly specified (generally retry recp)
715
+ // ensure the message is only sent to that person
716
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
717
+ if (participant) {
718
+ if (isJidGroup(destinationJid)) {
719
+ stanza.attrs.to = destinationJid;
720
+ stanza.attrs.participant = participant.jid;
721
+ }
722
+ else if (areJidsSameUser(participant.jid, meId)) {
723
+ stanza.attrs.to = participant.jid;
724
+ stanza.attrs.recipient = destinationJid;
725
+ }
726
+ else {
727
+ stanza.attrs.to = participant.jid;
728
+ }
729
+ }
730
+ else {
731
+ stanza.attrs.to = destinationJid;
732
+ }
733
+ if (shouldIncludeDeviceIdentity) {
734
+ ;
735
+ stanza.content.push({
736
+ tag: 'device-identity',
737
+ attrs: {},
738
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
739
+ });
740
+ logger.debug({ jid }, 'adding device identity');
741
+ }
742
+ if (AI && isPrivate) {
743
+ const botNode = {
744
+ tag: 'bot',
745
+ attrs: {
746
+ biz_bot: '1'
747
+ }
748
+ }
749
+
750
+ const filteredBizBot = getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
751
+
752
+ if (filteredBizBot) {
753
+ stanza.content.push(...additionalNodes)
754
+ didPushAdditional = true
755
+ }
756
+
757
+ else {
758
+ stanza.content.push(botNode)
759
+ }
760
+ }
761
+
762
+ if(!isNewsletter && buttonType && !isStatus) {
763
+ const content = getAdditionalNode(buttonType)
764
+ const filteredNode = getBinaryNodeFilter(additionalNodes)
765
+
766
+ if (filteredNode) {
767
+ didPushAdditional = true
768
+ stanza.content.push(...additionalNodes)
769
+ }
770
+ else {
771
+ stanza.content.push(...content)
772
+ }
773
+ logger.debug({ jid }, 'adding business node')
774
+ }
775
+
776
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
777
+ stanza.content.push(...additionalNodes);
778
+ }
779
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
780
+ await sendNode(stanza);
781
+ // Add message to retry cache if enabled
782
+ if (messageRetryManager && !participant) {
783
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
784
+ }
785
+ }, meId);
786
+ return msgId;
787
+ };
788
+ const getTypeMessage = (msg) => {
789
+ const message = normalizeMessageContent(msg)
790
+ if (message.reactionMessage) {
791
+ return 'reaction'
792
+ }
793
+ else if (getMediaType(message)) {
794
+ return 'media'
795
+ }
796
+ else {
797
+ return 'text'
573
798
  }
574
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
575
- additionalAttributes = {
576
- ...additionalAttributes,
577
- expiration: groupData.ephemeralDuration.toString()
578
- };
799
+ }
800
+ const getMediaType = (message) => {
801
+ if (message.imageMessage) {
802
+ return 'image'
579
803
  }
580
- const patched = await patchMessageBeforeSending(message);
581
- if (Array.isArray(patched)) {
582
- throw new Boom("Per-jid patching is not supported in groups");
804
+ else if (message.videoMessage) {
805
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
583
806
  }
584
- const bytes = encodeWAMessage(patched);
585
- const groupAddressingMode = additionalAttributes?.["addressing_mode"] || groupData?.addressingMode || "lid";
586
- const groupSenderIdentity = groupAddressingMode === "lid" && meLid ? meLid : meId;
587
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
588
- group: destinationJid,
589
- data: bytes,
590
- meId: groupSenderIdentity
591
- });
592
- const senderKeyRecipients = [];
593
- for (const device of devices) {
594
- const deviceJid = device.jid;
595
- const hasKey = !!senderKeyMap[deviceJid];
596
- if ((!hasKey || !!participant) &&
597
- !isHostedLidUser(deviceJid) &&
598
- !isHostedPnUser(deviceJid) &&
599
- device.device !== 99) {
600
- senderKeyRecipients.push(deviceJid);
601
- senderKeyMap[deviceJid] = true;
602
- }
807
+ else if (message.audioMessage) {
808
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
603
809
  }
604
- if (senderKeyRecipients.length) {
605
- logger.debug({ senderKeyJids: senderKeyRecipients }, "sending new sender key");
606
- const senderKeyMsg = {
607
- senderKeyDistributionMessage: {
608
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
609
- groupId: destinationJid
610
- }
611
- };
612
- const senderKeySessionTargets = senderKeyRecipients;
613
- await assertSessions(senderKeySessionTargets);
614
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
615
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
616
- participants.push(...result.nodes);
810
+ else if (message.contactMessage) {
811
+ return 'vcard'
617
812
  }
618
- if (isRetryResend) {
619
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
620
- data: bytes,
621
- jid: participant?.jid
622
- });
623
- binaryNodeContent.push({
624
- tag: "enc",
625
- attrs: {
626
- v: "2",
627
- type,
628
- count: participant.count.toString()
629
- },
630
- content: encryptedContent
631
- });
813
+ else if (message.documentMessage) {
814
+ return 'document'
632
815
  }
633
- else {
634
- binaryNodeContent.push({
635
- tag: "enc",
636
- attrs: { v: "2", type: "skmsg", ...extraAttrs },
637
- content: ciphertext
638
- });
639
- await authState.keys.set({ "sender-key-memory": { [jid]: senderKeyMap } });
816
+ else if (message.contactsArrayMessage) {
817
+ return 'contact_array'
640
818
  }
641
- }
642
- else {
643
- let ownId = meId;
644
- if (isLid && meLid) {
645
- ownId = meLid;
646
- logger.debug({ to: jid, ownId }, "Using LID identity for @lid conversation");
819
+ else if (message.liveLocationMessage) {
820
+ return 'livelocation'
647
821
  }
648
- else {
649
- logger.debug({ to: jid, ownId }, "Using PN identity for @s.whatsapp.net conversation");
822
+ else if (message.stickerMessage) {
823
+ return 'sticker'
650
824
  }
651
- const { user: ownUser } = jidDecode(ownId);
652
- if (!participant) {
653
- const targetUserServer = isLid ? "lid" : "s.whatsapp.net";
654
- devices.push({
655
- user,
656
- device: 0,
657
- jid: jidEncode(user, targetUserServer, 0)
658
- });
659
- if (user !== ownUser) {
660
- const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
661
- const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
662
- devices.push({
663
- user: ownUserForAddressing,
664
- device: 0,
665
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
666
- });
667
- }
668
- if (additionalAttributes?.["category"] !== "peer") {
669
- devices.length = 0;
670
- const senderIdentity = isLid && meLid
671
- ? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
672
- : jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
673
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
674
- devices.push(...sessionDevices);
675
- logger.debug({
676
- deviceCount: devices.length,
677
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
678
- }, "Device enumeration complete with unified addressing");
679
- }
825
+ else if (message.listMessage) {
826
+ return 'list'
680
827
  }
681
- const allRecipients = [];
682
- const meRecipients = [];
683
- const otherRecipients = [];
684
- const { user: mePnUser } = jidDecode(meId);
685
- const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
686
- for (const { user, jid } of devices) {
687
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
688
- if (isExactSenderDevice) {
689
- logger.debug({ jid, meId, meLid }, "Skipping exact sender device (whatsmeow pattern)");
690
- continue;
691
- }
692
- const isMe = user === mePnUser || user === meLidUser;
693
- if (isMe) {
694
- meRecipients.push(jid);
695
- }
696
- else {
697
- otherRecipients.push(jid);
698
- }
699
- allRecipients.push(jid);
828
+ else if (message.listResponseMessage) {
829
+ return 'list_response'
700
830
  }
701
- await assertSessions(allRecipients);
702
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
703
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
704
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
705
- ]);
706
- participants.push(...meNodes);
707
- participants.push(...otherNodes);
708
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
709
- extraAttrs["phash"] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
831
+ else if (message.buttonsResponseMessage) {
832
+ return 'buttons_response'
710
833
  }
711
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
712
- }
713
- if (participants.length) {
714
- if (additionalAttributes?.["category"] === "peer") {
715
- const peerNode = participants[0]?.content?.[0];
716
- if (peerNode) {
717
- binaryNodeContent.push(peerNode);
718
- }
834
+ else if (message.orderMessage) {
835
+ return 'order'
719
836
  }
720
- else {
721
- binaryNodeContent.push({
722
- tag: "participants",
723
- attrs: {},
724
- content: participants
725
- });
837
+ else if (message.productMessage) {
838
+ return 'product'
726
839
  }
727
- }
728
- const stanza = {
729
- tag: "message",
730
- attrs: {
731
- id: msgId,
732
- to: destinationJid,
733
- type: getMessageType(message),
734
- ...(additionalAttributes || {})
735
- },
736
- content: binaryNodeContent
737
- };
738
- if (participant) {
739
- if (isJidGroup(destinationJid)) {
740
- stanza.attrs.to = destinationJid;
741
- stanza.attrs.participant = participant.lid;
742
- }
743
- else if (areJidsSameUser(participant.lid, meId)) {
744
- stanza.attrs.to = participant.lid;
745
- stanza.attrs.recipient = destinationJid;
746
- }
747
- else {
748
- stanza.attrs.to = participant.lid;
749
- }
750
- }
751
- else {
752
- stanza.attrs.to = destinationJid;
753
- }
754
-
755
- if (shouldIncludeDeviceIdentity) {
756
- stanza.content.push({
757
- tag: "device-identity",
758
- attrs: {},
759
- content: encodeSignedDeviceIdentity(authState.creds.account, true)
760
- });
761
- logger.debug({ destinationJid }, "adding device identity");
762
- }
763
-
764
- if (additionalNodes && additionalNodes.length > 0) {
765
- stanza.content.push(...additionalNodes);
766
- }
767
- else {
768
- if ((isJidGroup(destinationJid) || isLidUser(destinationJid)) &&
769
- (message?.viewOnceMessage ? message?.viewOnceMessage :
770
- (message?.viewOnceMessageV2 ? message?.viewOnceMessageV2 :
771
- (message?.viewOnceMessageV2Extension ? message?.viewOnceMessageV2Extension :
772
- (message?.ephemeralMessage ? message?.ephemeralMessage :
773
- (message?.templateMessage ? message?.templateMessage :
774
- (message?.interactiveMessage ? message?.interactiveMessage :
775
- message?.buttonsMessage))))))) {
776
- stanza.content.push({
777
- tag: "biz",
778
- attrs: {},
779
- content: [{
780
- tag: "interactive",
781
- attrs: {
782
- type: "native_flow",
783
- v: "1"
784
- },
785
- content: [{
786
- tag: "native_flow",
787
- attrs: { name: "quick_reply" }
788
- }]
789
- }]
790
- });
791
- }
792
- }
793
- const buttonType = getButtonType(message);
794
- if (buttonType) {
795
- stanza.content.push({
796
- tag: "biz",
797
- attrs: {},
798
- content: [
799
- {
800
- tag: buttonType,
801
- attrs: getButtonArgs(message),
802
- }
803
- ]
804
- });
805
- logger.debug({ jid }, "adding business node");
806
- }
807
-
808
- logger.debug({ msgId }, `sending message to ${participants.length} devices`);
809
- await sendNode(stanza);
810
- });
811
- return msgId;
812
- };
813
- const getMessageType = (message) => {
814
- if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
815
- return "poll";
816
- }
817
- if (message.eventMessage) {
818
- return "event";
819
- }
820
- if (getMediaType(message) !== "") {
821
- return "media";
822
- }
823
- return "text";
824
- };
825
- const getMediaType = (message) => {
826
- if (message.imageMessage) {
827
- return "image";
828
- }
829
- else if (message.videoMessage) {
830
- return message.videoMessage.gifPlayback ? "gif" : "video";
831
- }
832
- else if (message.audioMessage) {
833
- return message.audioMessage.ptt ? "ptt" : "audio";
834
- }
835
- else if (message.contactMessage) {
836
- return "vcard";
837
- }
838
- else if (message.documentMessage) {
839
- return "document";
840
- }
841
- else if (message.contactsArrayMessage) {
842
- return "contact_array";
843
- }
844
- else if (message.liveLocationMessage) {
845
- return "livelocation";
846
- }
847
- else if (message.stickerMessage) {
848
- return "sticker";
849
- }
850
- else if (message.listMessage) {
851
- return "list";
852
- }
853
- else if (message.listResponseMessage) {
854
- return "list_response";
855
- }
856
- else if (message.buttonsResponseMessage) {
857
- return "buttons_response";
858
- }
859
- else if (message.orderMessage) {
860
- return "order";
861
- }
862
- else if (message.productMessage) {
863
- return "product";
864
- }
865
- else if (message.interactiveResponseMessage) {
866
- return "native_flow_response";
867
- }
868
- else if (message.groupInviteMessage) {
869
- return "url";
870
- }
871
- return "";
872
- };
873
- const getButtonType = (message) => {
874
- if (message.buttonsMessage) {
875
- return "buttons";
876
- }
877
- else if (message.buttonsResponseMessage) {
878
- return "buttons_response";
879
- }
880
- else if (message.interactiveResponseMessage) {
881
- return "interactive_response";
882
- }
883
- else if (message.listMessage) {
884
- return "list";
885
- }
886
- else if (message.listResponseMessage) {
887
- return "list_response";
888
- }
889
- };
890
- const getButtonArgs = (message) => {
891
- if (message.templateMessage) {
892
- return {};
893
- }
894
- else if (message.listMessage) {
895
- const type = message.listMessage.listType;
896
- if (!type) {
897
- throw new Boom("Expected list type inside message");
898
- }
899
- return { v: "2", type: proto.ListMessage.ListType[type].toLowerCase() };
900
- }
901
- else {
902
- return {};
903
- }
904
- };
905
- const getPrivacyTokens = async (jids) => {
906
- const t = unixTimestampSeconds().toString();
907
- const result = await query({
908
- tag: "iq",
909
- attrs: {
910
- to: S_WHATSAPP_NET,
911
- type: "set",
912
- xmlns: "privacy"
913
- },
914
- content: [
915
- {
916
- tag: "tokens",
917
- attrs: {},
918
- content: jids.map(jid => ({
919
- tag: "token",
920
- attrs: {
921
- jid: jidNormalizedUser(jid),
922
- t,
923
- type: "trusted_contact"
924
- }
925
- }))
840
+ else if (message.interactiveResponseMessage) {
841
+ return 'native_flow_response'
926
842
  }
927
- ]
928
- });
929
- return result;
930
- };
931
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
932
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
933
- return {
934
- ...sock,
935
- offerCall,
936
- getButtonType,
937
- getButtonArgs,
938
- getPrivacyTokens,
939
- assertSessions,
940
- relayMessage,
941
- sendReceipt,
942
- sendReceipts,
943
- readMessages,
944
- refreshMediaConn,
945
- waUploadToServer,
946
- fetchPrivacySettings,
947
- sendPeerDataOperationMessage,
948
- createParticipantNodes,
949
- getUSyncDevices,
950
- messageRetryManager,
951
- updateMediaMessage: async (message) => {
952
- const content = assertMediaContent(message.message);
953
- const mediaKey = content.mediaKey;
954
- const meId = authState.creds.me.id;
955
- const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
956
- let error = undefined;
957
- await Promise.all([
958
- sendNode(node),
959
- waitForMsgMediaUpdate(async (update) => {
960
- const result = update.find(c => c.key.id === message.key.id);
961
- if (result) {
962
- if (result.error) {
963
- error = result.error;
964
- }
965
- else {
966
- try {
967
- const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
968
- if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
969
- const resultStr = proto.MediaRetryNotification.ResultType[media.result];
970
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
971
- data: media,
972
- statusCode: getStatusCodeForMediaRetry(media.result) || 404
973
- });
974
- }
975
- content.directPath = media.directPath;
976
- content.url = getUrlFromDirectPath(content.directPath);
977
- logger.debug({ directPath: media.directPath, key: result.key }, "media update successful");
978
- }
979
- catch (err) {
980
- error = err;
981
- }
982
- }
983
- return true;
984
- }
985
- })
986
- ]);
987
- if (error) {
988
- throw error;
989
- }
990
- ev.emit("messages.update", [{ key: message.key, update: { message: message.message } }]);
991
- return message;
992
- },
993
- sendMessage: async (jid, content, options = {}) => {
994
- const userJid = authState.creds.me.id;
995
- if (typeof content === "object" &&
996
- "disappearingMessagesInChat" in content &&
997
- typeof content["disappearingMessagesInChat"] !== "undefined" &&
998
- isJidGroup(jid)) {
999
- const { disappearingMessagesInChat } = content;
1000
- const value = typeof disappearingMessagesInChat === "boolean"
1001
- ? disappearingMessagesInChat
1002
- ? WA_DEFAULT_EPHEMERAL
1003
- : 0
1004
- : disappearingMessagesInChat;
1005
- await groupToggleEphemeral(jid, value);
1006
- }
1007
- else {
1008
- const fullMsg = await generateWAMessage(jid, content, {
1009
- logger,
1010
- userJid,
1011
- getUrlInfo: text => getUrlInfo(text, {
1012
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1013
- fetchOpts: {
1014
- timeout: 3000,
1015
- ...(httpRequestOptions || {})
1016
- },
1017
- logger,
1018
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1019
- }),
1020
- getProfilePicUrl: sock.profilePictureUrl,
1021
- getCallLink: sock.createCallLink,
1022
- upload: waUploadToServer,
1023
- mediaCache: config.mediaCache,
1024
- options: config.options,
1025
- messageId: generateMessageIDV2(sock.user?.id),
1026
- ...options
1027
- });
1028
- const isEventMsg = "event" in content && !!content.event;
1029
- const isDeleteMsg = "delete" in content && !!content.delete;
1030
- const isEditMsg = "edit" in content && !!content.edit;
1031
- const isPinMsg = "pin" in content && !!content.pin;
1032
- const isPollMessage = "poll" in content && !!content.poll;
1033
- const additionalAttributes = {};
1034
- const additionalNodes = [];
1035
- if (isDeleteMsg) {
1036
- if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1037
- additionalAttributes.edit = "8";
1038
- }
1039
- else {
1040
- additionalAttributes.edit = "7";
1041
- }
843
+ else if (message.groupInviteMessage) {
844
+ return 'url'
1042
845
  }
1043
- else if (isEditMsg) {
1044
- additionalAttributes.edit = "1";
846
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
847
+ return 'productlink'
1045
848
  }
1046
- else if (isPinMsg) {
1047
- additionalAttributes.edit = "2";
849
+ }
850
+ const getButtonType = (message) => {
851
+ if (message.listMessage) {
852
+ return 'list'
1048
853
  }
1049
- else if (isPollMessage) {
1050
- additionalNodes.push({
1051
- tag: "meta",
1052
- attrs: {
1053
- polltype: "creation"
1054
- }
1055
- });
854
+ else if (message.buttonsMessage) {
855
+ return 'buttons'
1056
856
  }
1057
- else if (isEventMsg) {
1058
- additionalNodes.push({
1059
- tag: "meta",
1060
- attrs: {
1061
- event_type: "creation"
1062
- }
1063
- });
857
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
858
+ return 'review_and_pay'
1064
859
  }
1065
- await relayMessage(jid, fullMsg.message, {
1066
- messageId: fullMsg.key.id,
1067
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1068
- additionalAttributes,
1069
- statusJidList: options.statusJidList,
1070
- additionalNodes
1071
- });
1072
- if (config.emitOwnEvents) {
1073
- process.nextTick(() => {
1074
- processingMutex.mutex(() => upsertMessage(fullMsg, "append"));
1075
- });
860
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
861
+ return 'review_order'
862
+ }
863
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
864
+ return 'payment_info'
865
+ }
866
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
867
+ return 'payment_status'
868
+ }
869
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
870
+ return 'payment_method'
871
+ }
872
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
873
+ return 'interactive'
874
+ }
875
+ else if (message.interactiveMessage?.nativeFlowMessage) {
876
+ return 'native_flow'
1076
877
  }
1077
- return fullMsg;
1078
- }
1079
878
  }
1080
- };
879
+ const getPrivacyTokens = async (jids) => {
880
+ const t = unixTimestampSeconds().toString();
881
+ const result = await query({
882
+ tag: 'iq',
883
+ attrs: {
884
+ to: S_WHATSAPP_NET,
885
+ type: 'set',
886
+ xmlns: 'privacy'
887
+ },
888
+ content: [
889
+ {
890
+ tag: 'tokens',
891
+ attrs: {},
892
+ content: jids.map(jid => ({
893
+ tag: 'token',
894
+ attrs: {
895
+ jid: jidNormalizedUser(jid),
896
+ t,
897
+ type: 'trusted_contact'
898
+ }
899
+ }))
900
+ }
901
+ ]
902
+ });
903
+ return result;
904
+ };
905
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
906
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
907
+ return {
908
+ ...sock,
909
+ getPrivacyTokens,
910
+ assertSessions,
911
+ relayMessage,
912
+ sendReceipt,
913
+ sendReceipts,
914
+ readMessages,
915
+ refreshMediaConn,
916
+ waUploadToServer,
917
+ fetchPrivacySettings,
918
+ sendPeerDataOperationMessage,
919
+ createParticipantNodes,
920
+ getUSyncDevices,
921
+ messageRetryManager,
922
+ updateMediaMessage: async (message) => {
923
+ const content = assertMediaContent(message.message);
924
+ const mediaKey = content.mediaKey;
925
+ const meId = authState.creds.me.id;
926
+ const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
927
+ let error = undefined;
928
+ await Promise.all([
929
+ sendNode(node),
930
+ waitForMsgMediaUpdate(async (update) => {
931
+ const result = update.find(c => c.key.id === message.key.id);
932
+ if (result) {
933
+ if (result.error) {
934
+ error = result.error;
935
+ }
936
+ else {
937
+ try {
938
+ const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
939
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
940
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
941
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
942
+ data: media,
943
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
944
+ });
945
+ }
946
+ content.directPath = media.directPath;
947
+ content.url = getUrlFromDirectPath(content.directPath);
948
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
949
+ }
950
+ catch (err) {
951
+ error = err;
952
+ }
953
+ }
954
+ return true;
955
+ }
956
+ })
957
+ ]);
958
+ if (error) {
959
+ throw error;
960
+ }
961
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
962
+ return message;
963
+ },
964
+ sendMessage: async (jid, content, options = {}) => {
965
+ const userJid = authState.creds.me.id;
966
+ if (typeof content === 'object' &&
967
+ 'disappearingMessagesInChat' in content &&
968
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
969
+ isJidGroup(jid)) {
970
+ const { disappearingMessagesInChat } = content;
971
+ const value = typeof disappearingMessagesInChat === 'boolean'
972
+ ? disappearingMessagesInChat
973
+ ? WA_DEFAULT_EPHEMERAL
974
+ : 0
975
+ : disappearingMessagesInChat;
976
+ await groupToggleEphemeral(jid, value);
977
+ }
978
+ else {
979
+ const fullMsg = await generateWAMessage(jid, content, {
980
+ logger,
981
+ userJid,
982
+ getUrlInfo: text => getUrlInfo(text, {
983
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
984
+ fetchOpts: {
985
+ timeout: 3000,
986
+ ...(httpRequestOptions || {})
987
+ },
988
+ logger,
989
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
990
+ }),
991
+ //TODO: CACHE
992
+ getProfilePicUrl: sock.profilePictureUrl,
993
+ getCallLink: sock.createCallLink,
994
+ upload: async (readStream, opts) => {
995
+ const up = await waUploadToServer(readStream, {
996
+ ...opts,
997
+ newsletter: isJidNewsletter(jid)
998
+ });
999
+ return up;
1000
+ },
1001
+ mediaCache: config.mediaCache,
1002
+ options: config.options,
1003
+ messageId: generateMessageIDV2(sock.user?.id),
1004
+ ...options
1005
+ });
1006
+ const isAiMsg = 'ai' in content && !!content.ai;
1007
+ const isEventMsg = 'event' in content && !!content.event;
1008
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1009
+ const isEditMsg = 'edit' in content && !!content.edit;
1010
+ const isPinMsg = 'pin' in content && !!content.pin;
1011
+ const isPollMessage = 'poll' in content && !!content.poll;
1012
+ const additionalAttributes = {};
1013
+ const additionalNodes = [];
1014
+ // required for delete
1015
+ if (isDeleteMsg) {
1016
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1017
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1018
+ additionalAttributes.edit = '8';
1019
+ }
1020
+ else {
1021
+ additionalAttributes.edit = '7';
1022
+ }
1023
+ }
1024
+ else if (isEditMsg) {
1025
+ additionalAttributes.edit = '1';
1026
+ }
1027
+ else if (isAiMsg) {
1028
+ additionalNodes.push({
1029
+ attrs: {
1030
+ biz_bot: '1'
1031
+ }, tag: "bot"
1032
+ });
1033
+ }
1034
+ else if (isPinMsg) {
1035
+ additionalAttributes.edit = '2';
1036
+ }
1037
+ else if (isPollMessage) {
1038
+ additionalNodes.push({
1039
+ tag: 'meta',
1040
+ attrs: {
1041
+ polltype: 'creation'
1042
+ }
1043
+ });
1044
+ }
1045
+ else if (isEventMsg) {
1046
+ additionalNodes.push({
1047
+ tag: 'meta',
1048
+ attrs: {
1049
+ event_type: 'creation'
1050
+ }
1051
+ });
1052
+ }
1053
+ await relayMessage(jid, fullMsg.message, {
1054
+ messageId: fullMsg.key.id,
1055
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1056
+ additionalAttributes,
1057
+ statusJidList: options.statusJidList,
1058
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes
1059
+ });
1060
+ if (config.emitOwnEvents) {
1061
+ process.nextTick(() => {
1062
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1063
+ });
1064
+ }
1065
+ return fullMsg;
1066
+ }
1067
+ }
1068
+ };
1081
1069
  };
1082
- //=======================================================//
1070
+ //# sourceMappingURL=messages-send.js.map