vinnleys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +108 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +6922 -0
  4. package/WAProto/fix-imports.js +85 -0
  5. package/WAProto/index.d.ts +79257 -0
  6. package/WAProto/index.js +242946 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +131 -0
  9. package/lib/Signal/Group/ciphertext-message.js +12 -0
  10. package/lib/Signal/Group/group-session-builder.js +30 -0
  11. package/lib/Signal/Group/group_cipher.js +82 -0
  12. package/lib/Signal/Group/index.js +12 -0
  13. package/lib/Signal/Group/keyhelper.js +18 -0
  14. package/lib/Signal/Group/sender-chain-key.js +26 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  16. package/lib/Signal/Group/sender-key-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-name.js +48 -0
  18. package/lib/Signal/Group/sender-key-record.js +41 -0
  19. package/lib/Signal/Group/sender-key-state.js +84 -0
  20. package/lib/Signal/Group/sender-message-key.js +26 -0
  21. package/lib/Signal/libsignal.js +431 -0
  22. package/lib/Signal/lid-mapping.js +277 -0
  23. package/lib/Socket/Client/index.js +3 -0
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +54 -0
  26. package/lib/Socket/MessageBuilder.js +3728 -0
  27. package/lib/Socket/business.js +379 -0
  28. package/lib/Socket/chats.js +1198 -0
  29. package/lib/Socket/communities.js +431 -0
  30. package/lib/Socket/graphql.js +716 -0
  31. package/lib/Socket/groups.js +374 -0
  32. package/lib/Socket/index.js +24 -0
  33. package/lib/Socket/interop.js +463 -0
  34. package/lib/Socket/luxu.js +387 -0
  35. package/lib/Socket/message-builder.js +521 -0
  36. package/lib/Socket/messages-recv.js +1916 -0
  37. package/lib/Socket/messages-send.js +1511 -0
  38. package/lib/Socket/mex.js +54 -0
  39. package/lib/Socket/newsletter.js +636 -0
  40. package/lib/Socket/privacy.js +318 -0
  41. package/lib/Socket/socket.js +1114 -0
  42. package/lib/Socket/username.js +236 -0
  43. package/lib/Store/index.js +10 -0
  44. package/lib/Store/keyed-db.js +108 -0
  45. package/lib/Store/make-cache-manager-store.js +85 -0
  46. package/lib/Store/make-in-memory-store.js +244 -0
  47. package/lib/Store/make-ordered-dictionary.js +75 -0
  48. package/lib/Store/object-repository.js +32 -0
  49. package/lib/Types/Auth.js +2 -0
  50. package/lib/Types/Bussines.js +2 -0
  51. package/lib/Types/Call.js +2 -0
  52. package/lib/Types/Chat.js +8 -0
  53. package/lib/Types/Contact.js +2 -0
  54. package/lib/Types/Events.js +2 -0
  55. package/lib/Types/GroupMetadata.js +2 -0
  56. package/lib/Types/Label.js +25 -0
  57. package/lib/Types/LabelAssociation.js +7 -0
  58. package/lib/Types/Message.js +11 -0
  59. package/lib/Types/Mex.js +111 -0
  60. package/lib/Types/Product.js +2 -0
  61. package/lib/Types/Signal.js +2 -0
  62. package/lib/Types/Socket.js +3 -0
  63. package/lib/Types/State.js +56 -0
  64. package/lib/Types/USync.js +2 -0
  65. package/lib/Types/index.js +26 -0
  66. package/lib/Utils/auth-utils.js +302 -0
  67. package/lib/Utils/browser-utils.js +48 -0
  68. package/lib/Utils/business.js +231 -0
  69. package/lib/Utils/chat-utils.js +872 -0
  70. package/lib/Utils/companion-reg-client-utils.js +35 -0
  71. package/lib/Utils/crypto.js +118 -0
  72. package/lib/Utils/decode-wa-message.js +350 -0
  73. package/lib/Utils/event-buffer.js +622 -0
  74. package/lib/Utils/generics.js +403 -0
  75. package/lib/Utils/history.js +134 -0
  76. package/lib/Utils/identity-change-handler.js +50 -0
  77. package/lib/Utils/index.js +24 -0
  78. package/lib/Utils/link-preview.js +85 -0
  79. package/lib/Utils/logger.js +3 -0
  80. package/lib/Utils/lt-hash.js +8 -0
  81. package/lib/Utils/make-mutex.js +33 -0
  82. package/lib/Utils/message-composer.js +273 -0
  83. package/lib/Utils/message-retry-manager.js +265 -0
  84. package/lib/Utils/messages-media.js +870 -0
  85. package/lib/Utils/messages.js +1394 -0
  86. package/lib/Utils/noise-handler.js +201 -0
  87. package/lib/Utils/offline-node-processor.js +40 -0
  88. package/lib/Utils/pre-key-manager.js +106 -0
  89. package/lib/Utils/process-message.js +630 -0
  90. package/lib/Utils/reporting-utils.js +258 -0
  91. package/lib/Utils/signal.js +201 -0
  92. package/lib/Utils/stanza-ack.js +38 -0
  93. package/lib/Utils/sticker.js +133 -0
  94. package/lib/Utils/sync-action-utils.js +49 -0
  95. package/lib/Utils/tc-token-utils.js +163 -0
  96. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  97. package/lib/Utils/use-sqlite-auth-state.js +162 -0
  98. package/lib/Utils/validate-connection.js +203 -0
  99. package/lib/WABinary/constants.js +1301 -0
  100. package/lib/WABinary/decode.js +262 -0
  101. package/lib/WABinary/encode.js +220 -0
  102. package/lib/WABinary/generic-utils.js +204 -0
  103. package/lib/WABinary/index.js +6 -0
  104. package/lib/WABinary/jid-utils.js +98 -0
  105. package/lib/WABinary/types.js +2 -0
  106. package/lib/WAM/BinaryInfo.js +10 -0
  107. package/lib/WAM/constants.js +22853 -0
  108. package/lib/WAM/encode.js +150 -0
  109. package/lib/WAM/index.js +4 -0
  110. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  111. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  112. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  113. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  114. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  115. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  116. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  117. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  118. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  119. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  120. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  121. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  122. package/lib/WAUSync/Protocols/index.js +12 -0
  123. package/lib/WAUSync/USyncQuery.js +151 -0
  124. package/lib/WAUSync/USyncUser.js +56 -0
  125. package/lib/WAUSync/index.js +3 -0
  126. package/lib/index.js +33 -0
  127. package/package.json +135 -0
@@ -0,0 +1,1511 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateIOSMessageID, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds, setBotMessageSecret } from '../Utils/index.js';
6
+ import { getUrlInfo } from '../Utils/link-preview.js';
7
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET, getAdditionalNode, getBinaryNodeFilter, getBinaryFilteredBizBot, isInteropUser } from '../WABinary/index.js';
11
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
+ import { makeUsernameSocket } from './username.js';
13
+ import imup from './luxu.js';
14
+ import * as Utils_1 from '../Utils/index.js';
15
+ import { randomBytes, createHmac } from 'crypto';
16
+ export const makeMessagesSocket = (config) => {
17
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount, aiLabel } = config;
18
+ const sock = makeUsernameSocket(config);
19
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
20
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
21
+ /**
22
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
23
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
24
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
25
+ */
26
+ const inFlightTcTokenIssuance = new Set();
27
+ const userDevicesCache = config.userDevicesCache ||
28
+ new NodeCache({
29
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
30
+ useClones: false
31
+ });
32
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
33
+ const devicesMutex = makeMutex();
34
+ // Initialize message retry manager if enabled
35
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
36
+ // Prevent race conditions in Signal session encryption by user
37
+ const encryptionMutex = makeKeyedMutex();
38
+ let mediaConn;
39
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
40
+ let mediaHost = DEF_MEDIA_HOST;
41
+ const refreshMediaConn = async (forceGet = false) => {
42
+ const media = await mediaConn;
43
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
44
+ mediaConn = (async () => {
45
+ const result = await query({
46
+ tag: 'iq',
47
+ attrs: {
48
+ type: 'set',
49
+ xmlns: 'w:m',
50
+ to: S_WHATSAPP_NET
51
+ },
52
+ content: [{ tag: 'media_conn', attrs: {} }]
53
+ });
54
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
55
+ // TODO: explore full length of data that whatsapp provides
56
+ const node = {
57
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
58
+ hostname: attrs.hostname,
59
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
60
+ })),
61
+ auth: mediaConnNode.attrs.auth,
62
+ ttl: +mediaConnNode.attrs.ttl,
63
+ fetchDate: new Date()
64
+ };
65
+ logger.debug('fetched media conn');
66
+ if (node.hosts[0]) {
67
+ mediaHost = node.hosts[0].hostname;
68
+ }
69
+ return node;
70
+ })();
71
+ }
72
+ return mediaConn;
73
+ };
74
+ /**
75
+ * generic send receipt function
76
+ * used for receipts of phone call, read, delivery etc.
77
+ * */
78
+ const sendReceipt = async (jid, participant, messageIds, type) => {
79
+ if (!messageIds || messageIds.length === 0) {
80
+ throw new Boom('missing ids in receipt');
81
+ }
82
+ const node = {
83
+ tag: 'receipt',
84
+ attrs: {
85
+ id: messageIds[0]
86
+ }
87
+ };
88
+ const isReadReceipt = type === 'read' || type === 'read-self';
89
+ if (isReadReceipt) {
90
+ node.attrs.t = unixTimestampSeconds().toString();
91
+ }
92
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
93
+ node.attrs.recipient = jid;
94
+ node.attrs.to = participant;
95
+ }
96
+ else {
97
+ node.attrs.to = jid;
98
+ if (participant) {
99
+ node.attrs.participant = participant;
100
+ }
101
+ }
102
+ if (type) {
103
+ node.attrs.type = type;
104
+ }
105
+ const remainingMessageIds = messageIds.slice(1);
106
+ if (remainingMessageIds.length) {
107
+ node.content = [
108
+ {
109
+ tag: 'list',
110
+ attrs: {},
111
+ content: remainingMessageIds.map(id => ({
112
+ tag: 'item',
113
+ attrs: { id }
114
+ }))
115
+ }
116
+ ];
117
+ }
118
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
119
+ await sendNode(node);
120
+ };
121
+ /** Correctly bulk send receipts to multiple chats, participants */
122
+ const sendReceipts = async (keys, type) => {
123
+ const recps = aggregateMessageKeysNotFromMe(keys);
124
+ for (const { jid, participant, messageIds } of recps) {
125
+ await sendReceipt(jid, participant, messageIds, type);
126
+ }
127
+ };
128
+ /** Bulk read messages. Keys can be from different chats & participants */
129
+ const readMessages = async (keys) => {
130
+ const privacySettings = await fetchPrivacySettings();
131
+ // based on privacy settings, we have to change the read type
132
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
133
+ await sendReceipts(keys, readType);
134
+ };
135
+ /** Fetch all the devices we've to send a message to */
136
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
137
+ const deviceResults = [];
138
+ if (!useCache) {
139
+ logger.debug('not using cache for devices');
140
+ }
141
+ const toFetch = [];
142
+ const jidsWithUser = jids
143
+ .map(jid => {
144
+ const decoded = jidDecode(jid);
145
+ const user = decoded?.user;
146
+ const device = decoded?.device;
147
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
148
+ if (isExplicitDevice && user) {
149
+ deviceResults.push({
150
+ user,
151
+ device,
152
+ jid
153
+ });
154
+ return null;
155
+ }
156
+ jid = jidNormalizedUser(jid);
157
+ return { jid, user };
158
+ })
159
+ .filter(jid => jid !== null);
160
+ let mgetDevices;
161
+ if (useCache && userDevicesCache.mget) {
162
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
163
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
164
+ }
165
+ for (const { jid, user } of jidsWithUser) {
166
+ if (useCache) {
167
+ const devices = mgetDevices?.[user] ||
168
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
169
+ if (devices) {
170
+ const devicesWithJid = devices.map(d => ({
171
+ ...d,
172
+ jid: jidEncode(d.user, d.server, d.device)
173
+ }));
174
+ deviceResults.push(...devicesWithJid);
175
+ logger.trace({ user }, 'using cache for devices');
176
+ }
177
+ else {
178
+ toFetch.push(jid);
179
+ }
180
+ }
181
+ else {
182
+ toFetch.push(jid);
183
+ }
184
+ }
185
+ if (!toFetch.length) {
186
+ return deviceResults;
187
+ }
188
+ const requestedLidUsers = new Set();
189
+ for (const jid of toFetch) {
190
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
191
+ const user = jidDecode(jid)?.user;
192
+ if (user)
193
+ requestedLidUsers.add(user);
194
+ }
195
+ }
196
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
197
+ for (const jid of toFetch) {
198
+ 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
199
+ }
200
+ const result = await sock.executeUSyncQuery(query);
201
+ if (result) {
202
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
203
+ const lidResults = result.list.filter(a => !!a.lid);
204
+ if (lidResults.length > 0) {
205
+ logger.trace('Storing LID maps from device call');
206
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
207
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
208
+ try {
209
+ const lids = lidResults.map(a => a.lid);
210
+ if (lids.length) {
211
+ await assertSessions(lids, true);
212
+ }
213
+ }
214
+ catch (e) {
215
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
216
+ }
217
+ }
218
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
219
+ const deviceMap = {};
220
+ for (const item of extracted) {
221
+ deviceMap[item.user] = deviceMap[item.user] || [];
222
+ deviceMap[item.user]?.push(item);
223
+ }
224
+ // Process each user's devices as a group for bulk LID migration
225
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
226
+ const isLidUser = requestedLidUsers.has(user);
227
+ // Process all devices for this user
228
+ for (const item of userDevices) {
229
+ const finalJid = isLidUser
230
+ ? jidEncode(user, item.server, item.device)
231
+ : jidEncode(item.user, item.server, item.device);
232
+ deviceResults.push({
233
+ ...item,
234
+ jid: finalJid
235
+ });
236
+ logger.debug({
237
+ user: item.user,
238
+ device: item.device,
239
+ finalJid,
240
+ usedLid: isLidUser
241
+ }, 'Processed device with LID priority');
242
+ }
243
+ }
244
+ await devicesMutex.mutex(async () => {
245
+ if (userDevicesCache.mset) {
246
+ // if the cache supports mset, we can set all devices in one go
247
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
248
+ }
249
+ else {
250
+ for (const key in deviceMap) {
251
+ if (deviceMap[key])
252
+ await userDevicesCache.set(key, deviceMap[key]);
253
+ }
254
+ }
255
+ });
256
+ const userDeviceUpdates = {};
257
+ for (const [userId, devices] of Object.entries(deviceMap)) {
258
+ if (devices && devices.length > 0) {
259
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
260
+ }
261
+ }
262
+ if (Object.keys(userDeviceUpdates).length > 0) {
263
+ try {
264
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
265
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
266
+ }
267
+ catch (error) {
268
+ logger.warn({ error }, 'failed to store user device lists');
269
+ }
270
+ }
271
+ }
272
+ return deviceResults;
273
+ };
274
+ /**
275
+ * Update Member Label
276
+ */
277
+ const updateMemberLabel = (jid, memberLabel) => {
278
+ return relayMessage(jid, {
279
+ protocolMessage: {
280
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
281
+ memberLabel: {
282
+ label: memberLabel?.slice(0, 30),
283
+ labelTimestamp: unixTimestampSeconds()
284
+ }
285
+ }
286
+ }, {
287
+ additionalNodes: [
288
+ {
289
+ tag: 'meta',
290
+ attrs: {
291
+ tag_reason: 'user_update',
292
+ appdata: 'member_tag'
293
+ },
294
+ content: undefined
295
+ }
296
+ ]
297
+ });
298
+ };
299
+ const assertSessions = async (jids, force) => {
300
+ let didFetchNewSession = false;
301
+ const uniqueJids = [...new Set(jids)];
302
+ const jidsRequiringFetch = [];
303
+ logger.debug({ jids }, 'assertSessions call with jids');
304
+ for (const jid of uniqueJids) {
305
+ if (!force) {
306
+ const sessionValidation = await signalRepository.validateSession(jid);
307
+ if (sessionValidation.exists) {
308
+ continue;
309
+ }
310
+ }
311
+ jidsRequiringFetch.push(jid);
312
+ }
313
+ if (jidsRequiringFetch.length) {
314
+ // LID if mapped, otherwise original
315
+ const wireJids = [
316
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
317
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
318
+ ];
319
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
320
+ const result = await query({
321
+ tag: 'iq',
322
+ attrs: {
323
+ xmlns: 'encrypt',
324
+ type: 'get',
325
+ to: S_WHATSAPP_NET
326
+ },
327
+ content: [
328
+ {
329
+ tag: 'key',
330
+ attrs: {},
331
+ content: wireJids.map(jid => {
332
+ const attrs = { jid };
333
+ if (force)
334
+ attrs.reason = 'identity';
335
+ return { tag: 'user', attrs };
336
+ })
337
+ }
338
+ ]
339
+ });
340
+ await parseAndInjectE2ESessions(result, signalRepository);
341
+ didFetchNewSession = true;
342
+ }
343
+ return didFetchNewSession;
344
+ };
345
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
346
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
347
+ if (!authState.creds.me?.id) {
348
+ throw new Boom('Not authenticated');
349
+ }
350
+ const protocolMessage = {
351
+ protocolMessage: {
352
+ peerDataOperationRequestMessage: pdoMessage,
353
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
354
+ }
355
+ };
356
+ const meJid = jidNormalizedUser(authState.creds.me.id);
357
+ const msgId = await relayMessage(meJid, protocolMessage, {
358
+ additionalAttributes: {
359
+ category: 'peer',
360
+ push_priority: 'high_force'
361
+ },
362
+ additionalNodes: [
363
+ {
364
+ tag: 'meta',
365
+ attrs: { appdata: 'default' }
366
+ }
367
+ ]
368
+ });
369
+ return msgId;
370
+ };
371
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
372
+ if (!recipientJids.length) {
373
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
374
+ }
375
+ const patched = await patchMessageBeforeSending(message, recipientJids);
376
+ const patchedMessages = Array.isArray(patched)
377
+ ? patched
378
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
379
+ let shouldIncludeDeviceIdentity = false;
380
+ const meId = authState.creds.me.id;
381
+ const meLid = authState.creds.me?.lid;
382
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
383
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
384
+ try {
385
+ if (!jid)
386
+ return null;
387
+ let msgToEncrypt = patchedMessage;
388
+ if (dsmMessage) {
389
+ const { user: targetUser } = jidDecode(jid);
390
+ const { user: ownPnUser } = jidDecode(meId);
391
+ const ownLidUser = meLidUser;
392
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
393
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
394
+ if (isOwnUser && !isExactSenderDevice) {
395
+ msgToEncrypt = dsmMessage;
396
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
397
+ }
398
+ }
399
+ const bytes = encodeWAMessage(msgToEncrypt);
400
+ const mutexKey = jid;
401
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
402
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
403
+ if (type === 'pkmsg') {
404
+ shouldIncludeDeviceIdentity = true;
405
+ }
406
+ return {
407
+ tag: 'to',
408
+ attrs: { jid },
409
+ content: [
410
+ {
411
+ tag: 'enc',
412
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
413
+ content: ciphertext
414
+ }
415
+ ]
416
+ };
417
+ });
418
+ return node;
419
+ }
420
+ catch (err) {
421
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
422
+ return null;
423
+ }
424
+ });
425
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
426
+ if (recipientJids.length > 0 && nodes.length === 0) {
427
+ throw new Boom('All encryptions failed', { statusCode: 500 });
428
+ }
429
+ return { nodes, shouldIncludeDeviceIdentity };
430
+ };
431
+ const relayMessage = async (
432
+ jid,
433
+ message,
434
+ {
435
+ messageId: msgId,
436
+ participant,
437
+ participants: retryParticipants,
438
+ ptcp,
439
+ protected: protectedSend,
440
+ additionalAttributes,
441
+ additionalNodes,
442
+ useUserDevicesCache,
443
+ useCachedGroupMetadata,
444
+ statusJidList,
445
+ cstoken = true
446
+ }
447
+ ) => {
448
+ const meId = authState.creds.me.id
449
+ const meLid = authState.creds.me?.lid
450
+ const isRetryResend = Boolean(retryParticipants?.jid && retryParticipants?.count != null)
451
+ const isRecipientOnly = Boolean(participant?.jid)
452
+ let shouldIncludeDeviceIdentity = isRetryResend
453
+ const statusJid = 'status@broadcast'
454
+ const { user, server } = jidDecode(jid)
455
+ const isGroup = server === 'g.us'
456
+ const isStatus = jid === statusJid
457
+ const isLid = server === 'lid'
458
+ const isNewsletter = server === 'newsletter'
459
+ const isInterop = isInteropUser(jid)
460
+ const isGroupOrStatus = isGroup || isStatus
461
+ const finalJid = jid
462
+ const iosBros = config.browser[0] === "iOS" || config.browser[1] === "Safari";
463
+ msgId = iosBros ? generateIOSMessageID() : msgId ?? generateMessageIDV2(meId)
464
+ useUserDevicesCache = useUserDevicesCache!== false
465
+ useCachedGroupMetadata = useCachedGroupMetadata!== false &&!isStatus
466
+ const participants = []
467
+ const destinationJid =!isStatus? finalJid : statusJid
468
+ const binaryNodeContent = []
469
+ const devices = []
470
+ let reportingMessage
471
+ const meMsg = {
472
+ deviceSentMessage: { destinationJid, message },
473
+ messageContextInfo: message.messageContextInfo
474
+ }
475
+ const extraAttrs = {}
476
+ if (isRetryResend) {
477
+ if (!isGroup &&!isStatus) {
478
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' }
479
+ }
480
+ const { user: retryUser, device: retryDevice } = jidDecode(retryParticipants.jid)
481
+ devices.push({ user: retryUser, device: retryDevice, jid: retryParticipants.jid })
482
+ }
483
+ if ((isRecipientOnly || ptcp || protectedSend) &&!isGroup &&!isStatus) {
484
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' }
485
+ }
486
+ const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
487
+ const messages = normalizeMessageContent(message)
488
+ const buttonType = getButtonType(messages)
489
+ const pollMessage =
490
+ messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
491
+ await authState.keys.transaction(async () => {
492
+ const mediaType = getMediaType(message)
493
+ if (mediaType) extraAttrs.mediatype = mediaType
494
+ if (isNewsletter) {
495
+ const patched = patchMessageBeforeSending? await patchMessageBeforeSending(message, []) : message
496
+ const bytes = encodeNewsletterMessage(patched)
497
+ binaryNodeContent.push({ tag: 'plaintext', attrs: {}, content: bytes })
498
+ const stanza = {
499
+ tag: 'message',
500
+ attrs: {
501
+ to: jid,
502
+ id: msgId,
503
+ type: getMessageType(message),
504
+ ...(additionalAttributes || {})
505
+ },
506
+ content: binaryNodeContent
507
+ }
508
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`)
509
+ await sendNode(stanza)
510
+ return
511
+ }
512
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
513
+ extraAttrs['decrypt-fail'] = 'hide'
514
+ }
515
+ if (isGroupOrStatus &&!isRetryResend) {
516
+ const [groupData, senderKeyMap] = await Promise.all([
517
+ (async () => {
518
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata? await cachedGroupMetadata(jid) : undefined
519
+ if (groupData && Array.isArray(groupData?.participants)) {
520
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
521
+ } else if (!isStatus) {
522
+ groupData = await groupMetadata(jid)
523
+ }
524
+ return groupData
525
+ })(),
526
+ (async () => {
527
+ if (!retryParticipants &&!isStatus) {
528
+ const result = await authState.keys.get('sender-key-memory', [jid])
529
+ return result[jid] || {}
530
+ }
531
+ return {}
532
+ })()
533
+ ])
534
+ const participantsList = groupData? groupData.participants.map(p => p.id) : []
535
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
536
+ additionalAttributes = {...additionalAttributes, expiration: groupData.ephemeralDuration.toString() }
537
+ }
538
+ if (isStatus && statusJidList) participantsList.push(...statusJidList)
539
+ const additionalDevices = await getUSyncDevices(participantsList,!!useUserDevicesCache, false)
540
+ devices.push(...additionalDevices)
541
+ if (isGroup) {
542
+ additionalAttributes = {
543
+ ...additionalAttributes,
544
+ addressing_mode: groupData?.addressingMode || 'lid'
545
+ }
546
+ }
547
+ if (message?.groupStatusMessageV2 &&!message?.messageContextInfo?.messageSecret) {
548
+ message = {
549
+ ...message,
550
+ messageContextInfo: {
551
+ ...(message.messageContextInfo || {}),
552
+ messageSecret: randomBytes(32)
553
+ },
554
+ groupStatusMessageV2: {
555
+ ...message.groupStatusMessageV2,
556
+ message: {
557
+ ...(message.groupStatusMessageV2.message || {}),
558
+ messageContextInfo: {
559
+ ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
560
+ messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
561
+ }
562
+ }
563
+ }
564
+ }
565
+ }
566
+ // list/buttons/template -> interactiveMessage
567
+ if (message.listMessage) {
568
+ const list = message.listMessage
569
+ message = {
570
+ interactiveMessage: {
571
+ nativeFlowMessage: {
572
+ buttons: [
573
+ {
574
+ name: 'single_select',
575
+ buttonParamsJson: JSON.stringify({
576
+ title: list.buttonText || 'Select',
577
+ sections: (list.sections || []).map(section => ({
578
+ title: section.title || '',
579
+ highlight_label: '',
580
+ rows: (section.rows || []).map(row => ({
581
+ header: '',
582
+ title: row.title || '',
583
+ description: row.description || '',
584
+ id: row.rowId || row.id || ''
585
+ }))
586
+ }))
587
+ })
588
+ }
589
+ ],
590
+ messageParamsJson: '',
591
+ messageVersion: 1
592
+ },
593
+ body: { text: list.description || '' },
594
+ footer: list.footerText? { text: list.footerText } : undefined,
595
+ header: list.title? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
596
+ contextInfo: list.contextInfo
597
+ }
598
+ }
599
+ } else if (message.buttonsMessage) {
600
+ const bMsg = message.buttonsMessage
601
+ const buttons = (bMsg.buttons || []).map(btn => ({
602
+ name: 'quick_reply',
603
+ buttonParamsJson: JSON.stringify({
604
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
605
+ id: btn.buttonId || btn.buttonText?.displayText || ''
606
+ })
607
+ }))
608
+ message = {
609
+ interactiveMessage: {
610
+ nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
611
+ body: { text: bMsg.contentText || bMsg.text || '' },
612
+ footer: bMsg.footerText? { text: bMsg.footerText } : undefined,
613
+ header: bMsg.text
614
+ ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
615
+ : bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
616
+ ? { hasMediaAttachment: true,...(bMsg.imageMessage? { imageMessage: bMsg.imageMessage } : {}),...(bMsg.videoMessage? { videoMessage: bMsg.videoMessage } : {}) }
617
+ : undefined,
618
+ contextInfo: bMsg.contextInfo
619
+ }
620
+ }
621
+ } else if (message.templateMessage) {
622
+ const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate
623
+ if (tmpl) {
624
+ const buttons = (tmpl.hydratedButtons || [])
625
+ .map(hBtn => {
626
+ if (hBtn.quickReplyButton) {
627
+ return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: hBtn.quickReplyButton.displayText || '', id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || '' }) }
628
+ } else if (hBtn.urlButton) {
629
+ return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: hBtn.urlButton.displayText || '', url: hBtn.urlButton.url || '', merchant_url: hBtn.urlButton.url || '' }) }
630
+ } else if (hBtn.callButton) {
631
+ return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: hBtn.callButton.displayText || '', phone_number: hBtn.callButton.phoneNumber || '' }) }
632
+ }
633
+ return null
634
+ })
635
+ .filter(Boolean)
636
+ message = {
637
+ interactiveMessage: {
638
+ nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
639
+ body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
640
+ footer: tmpl.hydratedFooterText? { text: tmpl.hydratedFooterText } : undefined,
641
+ header: tmpl.hydratedTitleText
642
+ ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
643
+ : tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
644
+ ? { hasMediaAttachment: true,...(tmpl.imageMessage? { imageMessage: tmpl.imageMessage } : {}),...(tmpl.videoMessage? { videoMessage: tmpl.videoMessage } : {}) }
645
+ : undefined,
646
+ contextInfo: tmpl.contextInfo
647
+ }
648
+ }
649
+ }
650
+ }
651
+
652
+ const patched = await patchMessageBeforeSending(message)
653
+ if (Array.isArray(patched)) throw new Boom('Per-jid patching is not supported in groups')
654
+ const bytes = encodeWAMessage(patched)
655
+ reportingMessage = patched
656
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
657
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid? meLid : meId
658
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
659
+ group: destinationJid,
660
+ data: bytes,
661
+ meId: groupSenderIdentity
662
+ })
663
+ const senderKeyRecipients = []
664
+ for (const device of devices) {
665
+ const deviceJid = device.jid
666
+ const hasKey =!!senderKeyMap[deviceJid]
667
+ if (!hasKey ||!!retryParticipants &&!isHostedLidUser(deviceJid) &&!isHostedPnUser(deviceJid) && device.device!== 99) {
668
+ senderKeyRecipients.push(deviceJid)
669
+ senderKeyMap[deviceJid] = true
670
+ }
671
+ }
672
+ if (senderKeyRecipients.length) {
673
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
674
+ const senderKeyMsg = {
675
+ senderKeyDistributionMessage: {
676
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
677
+ groupId: destinationJid
678
+ }
679
+ }
680
+ await assertSessions(senderKeyRecipients)
681
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
682
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
683
+ participants.push(...result.nodes)
684
+ }
685
+ binaryNodeContent.push({ tag: 'enc', attrs: { v: '2', type: 'skmsg',...extraAttrs }, content: ciphertext })
686
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
687
+ } else {
688
+ let ownId = meId
689
+ if (isLid && meLid) {
690
+ ownId = meLid
691
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
692
+ } else {
693
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
694
+ }
695
+ const { user: ownUser } = jidDecode(ownId)
696
+ if (!isRetryResend) {
697
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid])
698
+ reportingMessage = Array.isArray(patchedForReporting)
699
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
700
+ : patchedForReporting
701
+ }
702
+ if (!isRetryResend) {
703
+ const targetUserServer = isLid? 'lid' : isInterop? 'interop' : 's.whatsapp.net'
704
+ devices.push({ user, device: 0, jid: jidEncode(user, targetUserServer, 0) })
705
+ if (user!== ownUser &&!isInterop) {
706
+ const ownUserServer = isLid? 'lid' : 's.whatsapp.net'
707
+ const ownUserForAddressing = isLid && meLid? jidDecode(meLid).user : jidDecode(meId).user
708
+ devices.push({ user: ownUserForAddressing, device: 0, jid: jidEncode(ownUserForAddressing, ownUserServer, 0) })
709
+ }
710
+ if (additionalAttributes?.['category']!== 'peer' &&!isInterop) {
711
+ devices.length = 0
712
+ const senderIdentity = isLid && meLid
713
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
714
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined)
715
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
716
+ devices.push(...sessionDevices)
717
+ logger.debug({ deviceCount: devices.length, devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`) }, 'Device enumeration complete with unified addressing')
718
+ }
719
+ }
720
+ const allRecipients = []
721
+ const meRecipients = []
722
+ const otherRecipients = []
723
+ const { user: mePnUser } = jidDecode(meId)
724
+ const { user: meLidUser } = meLid? jidDecode(meLid) : { user: null }
725
+ for (const { user, jid } of devices) {
726
+ /** participant method by Xzc || Tsm, who's delete the credits = love BBC */
727
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
728
+ if (isExactSenderDevice) {
729
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
730
+ continue
731
+ }
732
+ const isMe = user === mePnUser || user === meLidUser
733
+ const hasDevice = jid.includes(':')
734
+ let isParticipantOnly = false
735
+ if (retryParticipants) {
736
+ if (!isJidGroup(jid) && !isStatus) {
737
+ if (!(!isMe)) isParticipantOnly = true
738
+ } else {
739
+ isParticipantOnly = false
740
+ }
741
+ }
742
+ if (isParticipantOnly) continue
743
+ if (isRecipientOnly && isMe) continue
744
+ if (ptcp && !(!isMe && !hasDevice)) continue
745
+ if (protectedSend && !isMe && hasDevice) continue
746
+ if (isMe) {
747
+ meRecipients.push(jid)
748
+ } else {
749
+ otherRecipients.push(jid)
750
+ }
751
+ allRecipients.push(jid)
752
+ }
753
+ await assertSessions(allRecipients)
754
+ const [
755
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
756
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
757
+ ] = await Promise.all([
758
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
759
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
760
+ ])
761
+ participants.push(...meNodes,...otherNodes)
762
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
763
+ extraAttrs.phash = generateParticipantHashV2([...meRecipients,...otherRecipients])
764
+ }
765
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
766
+ }
767
+ if (isRetryResend) {
768
+ const isParticipantLid = isLidUser(retryParticipants.jid)
769
+ const isMe = areJidsSameUser(retryParticipants.jid, isParticipantLid? meLid : meId)
770
+ let messageToSend = message
771
+ if (isGroupOrStatus) {
772
+ let groupSenderIdentity
773
+ try {
774
+ if (meLid && await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid })) {
775
+ groupSenderIdentity = meLid
776
+ } else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
777
+ groupSenderIdentity = meId
778
+ }
779
+ if (groupSenderIdentity) {
780
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({ group: destinationJid, meId: groupSenderIdentity })
781
+ messageToSend = {
782
+ ...message,
783
+ senderKeyDistributionMessage: { groupId: destinationJid, axolotlSenderKeyDistributionMessage: skdm }
784
+ }
785
+ }
786
+ } catch (err) {
787
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it')
788
+ }
789
+ }
790
+ const encodedMessageToSend = isMe
791
+ ? encodeWAMessage({ deviceSentMessage: { destinationJid, message: messageToSend } })
792
+ : encodeWAMessage(messageToSend)
793
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
794
+ data: encodedMessageToSend,
795
+ jid: retryParticipants.jid
796
+ })
797
+ binaryNodeContent.push({
798
+ tag: 'enc',
799
+ attrs: { v: '2', type, count: (retryParticipants.count?? 0).toString() },
800
+ content: encryptedContent
801
+ })
802
+ }
803
+ if (participants.length) {
804
+ if (additionalAttributes?.['category'] === 'peer') {
805
+ const peerNode = participants[0]?.content?.[0]
806
+ if (peerNode) binaryNodeContent.push(peerNode)
807
+ } else if (isInterop) {
808
+ const recipientNode = participants.find(p => isInteropUser(p?.attrs?.jid))
809
+ const encNode = (recipientNode?? participants[0])?.content?.[0]
810
+ if (encNode) binaryNodeContent.push(encNode)
811
+ } else {
812
+ binaryNodeContent.push({ tag: 'participants', attrs: {}, content: participants })
813
+ }
814
+ }
815
+ const stanza = {
816
+ tag: 'message',
817
+ attrs: { id: msgId, to: destinationJid, type: getMessageType(message),...(additionalAttributes || {}) },
818
+ content: binaryNodeContent
819
+ }
820
+ if (isRetryResend) {
821
+ if (isJidGroup(destinationJid)) {
822
+ stanza.attrs.to = destinationJid
823
+ stanza.attrs.participant = retryParticipants.jid
824
+ } else if (areJidsSameUser(retryParticipants.jid, meId)) {
825
+ stanza.attrs.to = retryParticipants.jid
826
+ stanza.attrs.recipient = destinationJid
827
+ } else {
828
+ stanza.attrs.to = retryParticipants.jid
829
+ }
830
+ }
831
+ if (shouldIncludeDeviceIdentity) {
832
+ stanza.content.push({ tag: 'device-identity', attrs: {}, content: encodeSignedDeviceIdentity(authState.creds.account, true) })
833
+ logger.debug({ jid }, 'adding device identity')
834
+ }
835
+
836
+ if (isGroup && regexGroupOld.test(jid) &&!message.reactionMessage) {
837
+ stanza.content.push({ tag: 'multicast', attrs: {} })
838
+ }
839
+ if (pollMessage || messages.eventMessage) {
840
+ stanza.content.push({
841
+ tag: 'meta',
842
+ attrs: messages.eventMessage
843
+ ? { event_type: 'creation' }
844
+ : isNewsletter
845
+ ? { polltype: 'creation', contenttype: pollMessage?.pollContentType === 2? 'image' : 'text' }
846
+ : { polltype: 'creation' }
847
+ })
848
+ }
849
+ if (!isNewsletter &&!isRetryResend && reportingMessage?.messageContextInfo?.messageSecret && shouldIncludeReportingToken(reportingMessage)) {
850
+ try {
851
+ const encoded = encodeWAMessage(reportingMessage)
852
+ const reportingKey = { id: msgId, fromMe: true, remoteJid: destinationJid, participant: retryParticipants?.jid }
853
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey)
854
+ if (reportingNode) {
855
+ stanza.content.push(reportingNode)
856
+ logger.trace({ jid }, 'added reporting token to message')
857
+ }
858
+ } catch (error) {
859
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token')
860
+ }
861
+ }
862
+ let didPushAdditional = false
863
+ if (!isNewsletter && buttonType) {
864
+ const buttonsNode = getButtonArgs(messages)
865
+ const filteredButtons = getBinaryNodeFilter(additionalNodes? additionalNodes : [])
866
+ if (filteredButtons) {
867
+ stanza.content.push(...additionalNodes)
868
+ didPushAdditional = true
869
+ } else {
870
+ stanza.content.push(buttonsNode)
871
+ }
872
+ }
873
+ if (!aiLabel && isPnUser(destinationJid)) {
874
+ const alreadyHasBizBot = getBinaryFilteredBizBot(additionalNodes || []) || getBinaryFilteredBizBot(stanza.content)
875
+ if (!alreadyHasBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
876
+ } else if (aiLabel &&!isGroup &&!isStatus &&!isNewsletter) {
877
+ const existingBizBot = getBinaryFilteredBizBot(additionalNodes || [])
878
+ if (!existingBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
879
+ }
880
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer'
881
+ const is1on1Send =!isGroup &&!isRetryResend &&!isStatus &&!isNewsletter &&!isPeerMessage
882
+ const tcTokenJid = is1on1Send? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid
883
+ const contactTcTokenData = is1on1Send? await authState.keys.get('tctoken', [tcTokenJid]) : {}
884
+ const existingTokenEntry = contactTcTokenData[tcTokenJid]
885
+ let tcTokenBuffer = existingTokenEntry?.token
886
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
887
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing')
888
+ tcTokenBuffer = undefined
889
+ const cleared = existingTokenEntry?.senderTimestamp!== undefined? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp } : null
890
+ try {
891
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } })
892
+ } catch (err) {
893
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup')
894
+ }
895
+ }
896
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
897
+ stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
898
+ }
899
+ if (cstoken && is1on1Send &&!tcTokenBuffer?.length) {
900
+ try {
901
+ const lidJid = await resolveTcTokenJid(destinationJid, getLIDForPN)
902
+ if (isLidUser(lidJid)) {
903
+ const saltRes = await authState.keys.get('nct-salt', ['default'])
904
+ const nctSalt = saltRes?.default
905
+ if (nctSalt?.length) {
906
+ const cs = createHmac('sha256', Buffer.from(nctSalt)).update(Buffer.from(lidJid, 'utf8')).digest()
907
+ stanza.content.push({ tag: 'cstoken', attrs: {}, content: cs })
908
+ logger.debug({ jid: destinationJid, lid: lidJid }, 'attached cstoken (nct fallback)')
909
+ } else {
910
+ logger.debug({ jid: destinationJid }, 'cstoken requested but no nct salt stored yet')
911
+ }
912
+ } else {
913
+ logger.debug({ jid: destinationJid }, 'cstoken requested but recipient has no LID')
914
+ }
915
+ } catch (err) {
916
+ logger.debug({ jid: destinationJid, err: err?.message }, 'cstoken attach failed')
917
+ }
918
+ }
919
+ if (additionalNodes && additionalNodes.length > 0 &&!didPushAdditional) {
920
+ stanza.content.push(...additionalNodes)
921
+ }
922
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`)
923
+ await sendNode(stanza)
924
+ if (message.messageContextInfo?.messageSecret) {
925
+ setBotMessageSecret(msgId, message.messageContextInfo.messageSecret, destinationJid)
926
+ }
927
+ const isProtocolMsg =!!normalizeMessageContent(message)?.protocolMessage
928
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid)
929
+ if (is1on1Send &&!isProtocolMsg &&!isBotOrPSA && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&!inFlightTcTokenIssuance.has(tcTokenJid)) {
930
+ inFlightTcTokenIssuance.add(tcTokenJid)
931
+ const issueTimestamp = unixTimestampSeconds()
932
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
933
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
934
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
935
+ .then(async result => {
936
+ await storeTcTokensFromIqResult({ result, fallbackJid: tcTokenJid, keys: authState.keys, getLIDForPN })
937
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid])
938
+ const currentEntry = currentData[tcTokenJid]
939
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
940
+ await authState.keys.set({
941
+ tctoken: {
942
+ [tcTokenJid]: { token: Buffer.alloc(0),...currentEntry, senderTimestamp: issueTimestamp },
943
+ ...indexWrite
944
+ }
945
+ })
946
+ })
947
+ .catch(err => logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed'))
948
+ .finally(() => inFlightTcTokenIssuance.delete(tcTokenJid))
949
+ }
950
+ if (messageRetryManager &&!retryParticipants) {
951
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message)
952
+ }
953
+ if (isInterop &&!isRetryResend) {
954
+ await trustInteropContact(destinationJid).catch(err => logger.debug({ err, jid: destinationJid }, 'failed to trust interop contact'))
955
+ }
956
+ }, meId)
957
+ return msgId
958
+ }
959
+ const getMessageType = (message) => {
960
+ const normalizedMessage = normalizeMessageContent(message);
961
+ if (!normalizedMessage)
962
+ return 'text';
963
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
964
+ return 'reaction';
965
+ }
966
+ if (normalizedMessage.pollCreationMessage ||
967
+ normalizedMessage.pollCreationMessageV2 ||
968
+ normalizedMessage.pollCreationMessageV3 ||
969
+ normalizedMessage.pollCreationMessageV4 ||
970
+ normalizedMessage.pollCreationMessageV5 ||
971
+ normalizedMessage.pollUpdateMessage) {
972
+ return 'poll';
973
+ }
974
+ if (normalizedMessage.eventMessage) {
975
+ return 'event';
976
+ }
977
+ if (getMediaType(normalizedMessage) !== '') {
978
+ return 'media';
979
+ }
980
+ return 'text';
981
+ };
982
+ const getMediaType = (message) => {
983
+ if (message.imageMessage) {
984
+ return 'image';
985
+ }
986
+ else if (message.videoMessage) {
987
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
988
+ }
989
+ else if (message.audioMessage) {
990
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
991
+ }
992
+ else if (message.contactMessage) {
993
+ return 'vcard';
994
+ }
995
+ else if (message.documentMessage) {
996
+ return 'document';
997
+ }
998
+ else if (message.contactsArrayMessage) {
999
+ return 'contact_array';
1000
+ }
1001
+ else if (message.liveLocationMessage) {
1002
+ return 'livelocation';
1003
+ }
1004
+ else if (message.stickerMessage) {
1005
+ return 'sticker';
1006
+ }
1007
+ else if (message.stickerPackMessage) {
1008
+ return 'sticker';
1009
+ }
1010
+ else if (message.listMessage) {
1011
+ return 'list';
1012
+ }
1013
+ else if (message.listResponseMessage) {
1014
+ return 'list_response';
1015
+ }
1016
+ else if (message.buttonsResponseMessage) {
1017
+ return 'buttons_response';
1018
+ }
1019
+ else if (message.orderMessage) {
1020
+ return 'order';
1021
+ }
1022
+ else if (message.productMessage) {
1023
+ return 'product';
1024
+ }
1025
+ else if (message.interactiveResponseMessage) {
1026
+ return 'native_flow_response';
1027
+ }
1028
+ else if (message.groupInviteMessage) {
1029
+ return 'url';
1030
+ }
1031
+ return '';
1032
+ };
1033
+ const getButtonType = (message) => {
1034
+ if (message.listMessage) {
1035
+ return 'list'
1036
+ }
1037
+ else if (message.buttonsMessage) {
1038
+ return 'buttons'
1039
+ }
1040
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
1041
+ return 'review_and_pay'
1042
+ }
1043
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
1044
+ return 'review_order'
1045
+ }
1046
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
1047
+ return 'payment_info'
1048
+ } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_key_info') {
1049
+ return 'payment_key_info'
1050
+ } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
1051
+ return 'payment_status'
1052
+ }
1053
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
1054
+ return 'payment_method'
1055
+ }
1056
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'catalog_message') {
1057
+ return 'catalog_message'
1058
+ }
1059
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
1060
+ return 'interactive'
1061
+ }
1062
+ else if (message.interactiveMessage?.nativeFlowMessage) {
1063
+ return 'native_flow'
1064
+ }
1065
+ };
1066
+ const getButtonArgs = (message) => {
1067
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage
1068
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name
1069
+ const nativeFlowSpecials = [
1070
+ 'mpm',
1071
+ 'cta_catalog',
1072
+ 'send_location',
1073
+ 'call_permission_request',
1074
+ 'wa_payment_transaction_details',
1075
+ 'automated_greeting_message_view_catalog'
1076
+ ]
1077
+
1078
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1079
+ return {
1080
+ tag: 'biz',
1081
+ attrs: {
1082
+ native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
1083
+ }
1084
+ }
1085
+ } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1086
+ // Only works for WhatsApp Original, not WhatsApp Business
1087
+ return {
1088
+ tag: 'biz',
1089
+ attrs: {
1090
+ actual_actors: '2',
1091
+ host_storage: '2',
1092
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1093
+ },
1094
+ content: [
1095
+ {
1096
+ tag: 'interactive',
1097
+ attrs: {
1098
+ type: 'native_flow',
1099
+ v: '1'
1100
+ },
1101
+ content: [
1102
+ {
1103
+ tag: 'native_flow',
1104
+ attrs: {
1105
+ v: '2',
1106
+ name: firstButtonName
1107
+ }
1108
+ }
1109
+ ]
1110
+ },
1111
+ {
1112
+ tag: 'quality_control',
1113
+ attrs: {
1114
+ source_type: 'third_party'
1115
+ }
1116
+ }
1117
+ ]
1118
+ }
1119
+ } else if (nativeFlow || message.buttonsMessage) {
1120
+ // It works for whatsapp original and whatsapp business
1121
+ return {
1122
+ tag: 'biz',
1123
+ attrs: {
1124
+ actual_actors: '2',
1125
+ host_storage: '2',
1126
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1127
+ },
1128
+ content: [
1129
+ {
1130
+ tag: 'interactive',
1131
+ attrs: {
1132
+ type: 'native_flow',
1133
+ v: '1'
1134
+ },
1135
+ content: [
1136
+ {
1137
+ tag: 'native_flow',
1138
+ attrs: {
1139
+ v: '9',
1140
+ name: 'mixed'
1141
+ }
1142
+ }
1143
+ ]
1144
+ },
1145
+ {
1146
+ tag: 'quality_control',
1147
+ attrs: {
1148
+ source_type: 'third_party'
1149
+ }
1150
+ }
1151
+ ]
1152
+ }
1153
+ } else if (message.listMessage) {
1154
+ return {
1155
+ tag: 'biz',
1156
+ attrs: {
1157
+ actual_actors: '2',
1158
+ host_storage: '2',
1159
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1160
+ },
1161
+ content: [
1162
+ {
1163
+ tag: 'list',
1164
+ attrs: {
1165
+ v: '2',
1166
+ type: 'product_list'
1167
+ }
1168
+ },
1169
+ {
1170
+ tag: 'quality_control',
1171
+ attrs: {
1172
+ source_type: 'third_party'
1173
+ }
1174
+ }
1175
+ ]
1176
+ }
1177
+ } else {
1178
+ return {
1179
+ tag: 'biz',
1180
+ attrs: {
1181
+ actual_actors: '2',
1182
+ host_storage: '2',
1183
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1184
+ }
1185
+ }
1186
+ }
1187
+ }
1188
+ const issuePrivacyTokens = async (jids, timestamp) => {
1189
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1190
+ const result = await query({
1191
+ tag: 'iq',
1192
+ attrs: {
1193
+ to: S_WHATSAPP_NET,
1194
+ type: 'set',
1195
+ xmlns: 'privacy'
1196
+ },
1197
+ content: [
1198
+ {
1199
+ tag: 'tokens',
1200
+ attrs: {},
1201
+ content: jids.map(jid => ({
1202
+ tag: 'token',
1203
+ attrs: {
1204
+ jid: jidNormalizedUser(jid),
1205
+ t,
1206
+ type: 'trusted_contact'
1207
+ }
1208
+ }))
1209
+ }
1210
+ ]
1211
+ });
1212
+ return result;
1213
+ };
1214
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1215
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1216
+ registerSocketEndHandler(() => {
1217
+ if (!config.userDevicesCache && userDevicesCache.close) {
1218
+ userDevicesCache.close();
1219
+ }
1220
+ mediaConn = undefined;
1221
+ if (messageRetryManager) {
1222
+ messageRetryManager.clear();
1223
+ }
1224
+ });
1225
+ return {
1226
+ ...sock,
1227
+ userDevicesCache,
1228
+ devicesMutex,
1229
+ issuePrivacyTokens,
1230
+ assertSessions,
1231
+ relayMessage,
1232
+ sendReceipt,
1233
+ sendReceipts,
1234
+ readMessages,
1235
+ refreshMediaConn,
1236
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1237
+ getMediaHost: () => mediaHost,
1238
+ waUploadToServer,
1239
+ fetchPrivacySettings,
1240
+ sendPeerDataOperationMessage,
1241
+ createParticipantNodes,
1242
+ getUSyncDevices,
1243
+ messageRetryManager,
1244
+ updateMemberLabel,
1245
+ updateMediaMessage: async (message) => {
1246
+ const content = assertMediaContent(message.message);
1247
+ const mediaKey = content.mediaKey;
1248
+ const meId = authState.creds.me.id;
1249
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1250
+ let error = undefined;
1251
+ await Promise.all([
1252
+ sendNode(node),
1253
+ waitForMsgMediaUpdate(async (update) => {
1254
+ const result = update.find(c => c.key.id === message.key.id);
1255
+ if (result) {
1256
+ if (result.error) {
1257
+ error = result.error;
1258
+ }
1259
+ else {
1260
+ try {
1261
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1262
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1263
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1264
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1265
+ data: media,
1266
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1267
+ });
1268
+ }
1269
+ content.directPath = media.directPath;
1270
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1271
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1272
+ }
1273
+ catch (err) {
1274
+ error = err;
1275
+ }
1276
+ }
1277
+ return true;
1278
+ }
1279
+ })
1280
+ ]);
1281
+ if (error) {
1282
+ throw error;
1283
+ }
1284
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1285
+ return message;
1286
+ },
1287
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1288
+ const { message, messageId } = Utils_1.generateTableContent(title, headers, rows, quoted, options)
1289
+ await relayMessage(jid, message, { messageId })
1290
+ return { message, messageId }
1291
+ },
1292
+ sendList: async (jid, title, items, quoted, options = {}) => {
1293
+ const { message, messageId } = Utils_1.generateListContent(title, items, quoted, options)
1294
+ await relayMessage(jid, message, { messageId })
1295
+ return { message, messageId }
1296
+ },
1297
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1298
+ const { message, messageId } = Utils_1.generateCodeBlockContent(code, quoted, options)
1299
+ await relayMessage(jid, message, { messageId })
1300
+ return { message, messageId }
1301
+ },
1302
+ sendLatex: async (jid, quoted, options) => {
1303
+ const { message, messageId } = Utils_1.generateLatexContent(quoted, options)
1304
+ await relayMessage(jid, message, { messageId })
1305
+ return { message, messageId }
1306
+ },
1307
+ sendLatexImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1308
+ const { message, messageId } = await Utils_1.generateLatexImageContent(
1309
+ quoted,
1310
+ options,
1311
+ uploadFn,
1312
+ renderLatexToPng
1313
+ )
1314
+ await relayMessage(jid, message, { messageId })
1315
+ return { message, messageId }
1316
+ },
1317
+ sendLatexInlineImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1318
+ const { message, messageId } = await Utils_1.generateLatexInlineImageContent(
1319
+ quoted,
1320
+ options,
1321
+ uploadFn,
1322
+ renderLatexToPng
1323
+ )
1324
+ await relayMessage(jid, message, { messageId })
1325
+ return { message, messageId }
1326
+ },
1327
+ captureUnifiedResponse: Utils_1.captureUnifiedResponse,
1328
+ sendUnifiedResponse: async (jid, quoted, captured) => {
1329
+ const { message, messageId } = Utils_1.generateUnifiedResponseContent(quoted, captured)
1330
+ await relayMessage(jid, message, { messageId })
1331
+ return { message, messageId }
1332
+ },
1333
+ sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1334
+ const { message, messageId } = Utils_1.generateRichMessageContent(submessages, quoted, options)
1335
+ await relayMessage(jid, message, { messageId })
1336
+ return { message, messageId }
1337
+ },
1338
+ sendMessage: async (jid, content, options = {}) => {
1339
+ const userJid = authState.creds.me.id;
1340
+ const luki = new imup(Utils_1, waUploadToServer, relayMessage)
1341
+ const { quoted, participant = false, ptcp, protected: protectedSend, cstoken } = options;
1342
+ const messageType = luki.detectType(content);
1343
+ if (typeof content === 'object' &&
1344
+ 'disappearingMessagesInChat' in content &&
1345
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1346
+ isJidGroup(jid)) {
1347
+ const { disappearingMessagesInChat } = content;
1348
+ const value = typeof disappearingMessagesInChat === 'boolean'
1349
+ ? disappearingMessagesInChat
1350
+ ? WA_DEFAULT_EPHEMERAL
1351
+ : 0
1352
+ : disappearingMessagesInChat;
1353
+ await groupToggleEphemeral(jid, value);
1354
+ }
1355
+ else {
1356
+ if (messageType) {
1357
+ switch(messageType) {
1358
+ case 'PAYMENT':
1359
+ const paymentContent = await luki.handlePayment(content, quoted);
1360
+ return await relayMessage(jid, paymentContent, {
1361
+ messageId: Utils_1.generateMessageID()
1362
+ });
1363
+ case 'PRODUCT':
1364
+ const productContent = await luki.handleProduct(content, jid, quoted);
1365
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
1366
+ return await relayMessage(jid, productMsg.message, {
1367
+ messageId: productMsg.key.id,
1368
+ });
1369
+
1370
+ case 'ALBUM':
1371
+ return await luki.handleAlbum(content, jid, quoted)
1372
+ case 'EVENT':
1373
+ return await luki.handleEvent(content, jid, quoted)
1374
+ case 'POLL_RESULT':
1375
+ return await luki.handlePollResult(content, jid, quoted)
1376
+ case 'ORDER':
1377
+ return await luki.handleOrderMessage(content, jid, quoted)
1378
+ case 'GROUP_STATUS':
1379
+ return await luki.handleGroupStory(content, jid, quoted)
1380
+ case 'GROUP_LABEL':
1381
+ return await luki.handleGbLabel(content, jid)
1382
+ }
1383
+ }
1384
+ const fullMsg = await generateWAMessage(jid, content, {
1385
+ logger,
1386
+ userJid,
1387
+ getUrlInfo: text => getUrlInfo(text, {
1388
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1389
+ fetchOpts: {
1390
+ timeout: 3000,
1391
+ ...(httpRequestOptions || {})
1392
+ },
1393
+ logger,
1394
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1395
+ }),
1396
+ //TODO: CACHE
1397
+ getProfilePicUrl: sock.profilePictureUrl,
1398
+ getCallLink: sock.createCallLink,
1399
+ upload: waUploadToServer,
1400
+ mediaCache: config.mediaCache,
1401
+ options: config.options,
1402
+ messageId: generateMessageIDV2(sock.user?.id),
1403
+ ...options
1404
+ });
1405
+ const isEventMsg = 'event' in content && !!content.event;
1406
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1407
+ const isEditMsg = 'edit' in content && !!content.edit;
1408
+ const isPinMsg = 'pin' in content && !!content.pin;
1409
+ const isPollMessage = 'poll' in content && !!content.poll;
1410
+ const additionalAttributes = {};
1411
+ const additionalNodes = [];
1412
+ // required for delete
1413
+ if (isDeleteMsg) {
1414
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1415
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1416
+ additionalAttributes.edit = '8';
1417
+ }
1418
+ else {
1419
+ additionalAttributes.edit = '7';
1420
+ }
1421
+ }
1422
+ else if (isEditMsg) {
1423
+ additionalAttributes.edit = '1';
1424
+ }
1425
+ else if (isPinMsg) {
1426
+ additionalAttributes.edit = '2';
1427
+ }
1428
+ else if (isPollMessage) {
1429
+ additionalNodes.push({
1430
+ tag: 'meta',
1431
+ attrs: {
1432
+ polltype: 'creation'
1433
+ }
1434
+ });
1435
+ }
1436
+ else if (isEventMsg) {
1437
+ additionalNodes.push({
1438
+ tag: 'meta',
1439
+ attrs: {
1440
+ event_type: 'creation'
1441
+ }
1442
+ });
1443
+ }
1444
+ await relayMessage(jid, fullMsg.message, {
1445
+ messageId: fullMsg.key.id,
1446
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1447
+ additionalAttributes,
1448
+ statusJidList: options.statusJidList,
1449
+ additionalNodes: aiLabel ? additionalNodes : options.additionalNodes,
1450
+ participants: participant || undefined,
1451
+ ptcp,
1452
+ protected: protectedSend,
1453
+ ...(cstoken !== undefined ? { cstoken } : {})
1454
+ });
1455
+ if (config.emitOwnEvents) {
1456
+ process.nextTick(async () => {
1457
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1458
+ });
1459
+ }
1460
+ return fullMsg;
1461
+ }
1462
+ },
1463
+ sendMessageMembers: async (jid, message, options = {}) => {
1464
+ const {
1465
+ messageId: idm,
1466
+ quoted,
1467
+ delayMs = 1500,
1468
+ useUserDevicesCache = true,
1469
+ cachedGroupMetadata,
1470
+ onlyMember = true
1471
+ } = options;
1472
+ const { server } = jidDecode(jid);
1473
+ if (server !== "g.us") throw new Error("@g.us server required");
1474
+ const meId = authState.creds.me.id;
1475
+ const messages = Utils_1.normalizeMessageContent(message);
1476
+ const groupData = cachedGroupMetadata? await cachedGroupMetadata(jid) : await groupMetadata(jid);
1477
+ const isLid = groupData.addressingMode === "lid";
1478
+ const isAdmin = groupData.participants.filter((x) => x.admin !== null).map((y) => y.id)
1479
+ let participantJids = groupData.participants.map(z => z.id);
1480
+ if (onlyMember) {
1481
+ participantJids = isAdmin ? isAdmin : participantJids;
1482
+ }
1483
+ logger.info(`Sending message to ${participantJids.length} members from ${jid}`);
1484
+ for (let i = 0; i < participantJids.length; i++) {
1485
+ const jid = participantJids[i];
1486
+ if (areJidsSameUser(jid, meId)) continue;
1487
+ try {
1488
+ const msgId = `${idm || Utils_1.generateMessageID()}_${i}`;
1489
+ const fullMsg = await Utils_1.generateWAMessageFromContent(jid, message, {
1490
+ messageId: msgId,
1491
+ quoted
1492
+ })
1493
+ await relayMessage(jid, fullMsg.message, {
1494
+ messageId: fullMsg.key.id
1495
+ });
1496
+ logger.debug(`Message successfully sent to ${jid}`);
1497
+ if (delayMs && i < participantJids.length - 1) {
1498
+ await new Promise(z => setTimeout(z, delayMs));
1499
+ }
1500
+ } catch (e) {
1501
+ logger.error({ jid, e }, "Error sending message to");
1502
+ }
1503
+ }
1504
+ return JSON.stringify({
1505
+ members_total: participantJids.length,
1506
+ message
1507
+ }, null, 4);
1508
+ }
1509
+ };
1510
+ };
1511
+ //# sourceMappingURL=messages-send.js.map