supunmd-bail 2.0.1

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