@skyzopedia/baileys-mod 3.0.9 → 4.0.1

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