@zaiinlin/bails 0.0.0-stage → 1.0.3

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