@gara31/void-baileys 7.0.0-rc.14

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