ell-bail 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +116 -0
  2. package/WAProto/index.js +130309 -0
  3. package/engine-requirements.js +11 -0
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.d.ts +53 -0
  6. package/lib/Defaults/index.js +130 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/KeyDB/BinarySearch.js +18 -0
  9. package/lib/KeyDB/KeyedDB.js +164 -0
  10. package/lib/KeyDB/index.js +2 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  14. package/lib/Signal/Group/group-session-builder.js +64 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  16. package/lib/Signal/Group/group_cipher.js +96 -0
  17. package/lib/Signal/Group/index.d.ts +11 -0
  18. package/lib/Signal/Group/index.js +57 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  20. package/lib/Signal/Group/keyhelper.js +55 -0
  21. package/lib/Signal/Group/queue-job.d.ts +1 -0
  22. package/lib/Signal/Group/queue-job.js +57 -0
  23. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  24. package/lib/Signal/Group/sender-chain-key.js +34 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  28. package/lib/Signal/Group/sender-key-message.js +69 -0
  29. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  30. package/lib/Signal/Group/sender-key-name.js +51 -0
  31. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  32. package/lib/Signal/Group/sender-key-record.js +53 -0
  33. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  34. package/lib/Signal/Group/sender-key-state.js +99 -0
  35. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  36. package/lib/Signal/Group/sender-message-key.js +29 -0
  37. package/lib/Signal/Group/x +1 -0
  38. package/lib/Signal/libsignal.d.ts +3 -0
  39. package/lib/Signal/libsignal.js +174 -0
  40. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  41. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  42. package/lib/Socket/Client/index.d.ts +3 -0
  43. package/lib/Socket/Client/index.js +19 -0
  44. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  45. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  46. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  47. package/lib/Socket/Client/web-socket-client.js +62 -0
  48. package/lib/Socket/business.d.ts +171 -0
  49. package/lib/Socket/business.js +260 -0
  50. package/lib/Socket/chats.d.ts +80 -0
  51. package/lib/Socket/chats.js +864 -0
  52. package/lib/Socket/groups.d.ts +115 -0
  53. package/lib/Socket/groups.js +316 -0
  54. package/lib/Socket/index.d.ts +173 -0
  55. package/lib/Socket/index.js +10 -0
  56. package/lib/Socket/luxu.d.ts +251 -0
  57. package/lib/Socket/luxu.js +550 -0
  58. package/lib/Socket/messages-recv.d.ts +161 -0
  59. package/lib/Socket/messages-recv.js +1152 -0
  60. package/lib/Socket/messages-send.d.ts +149 -0
  61. package/lib/Socket/messages-send.js +1002 -0
  62. package/lib/Socket/newsletter.d.ts +236 -0
  63. package/lib/Socket/newsletter.js +236 -0
  64. package/lib/Socket/registration.d.ts +268 -0
  65. package/lib/Socket/registration.js +789 -0
  66. package/lib/Socket/socket.d.ts +43 -0
  67. package/lib/Socket/socket.js +630 -0
  68. package/lib/Socket/usync.d.ts +36 -0
  69. package/lib/Socket/usync.js +70 -0
  70. package/lib/Store/index.d.ts +3 -0
  71. package/lib/Store/index.js +10 -0
  72. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  73. package/lib/Store/make-cache-manager-store.js +83 -0
  74. package/lib/Store/make-in-memory-store.d.ts +118 -0
  75. package/lib/Store/make-in-memory-store.js +427 -0
  76. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  77. package/lib/Store/make-ordered-dictionary.js +81 -0
  78. package/lib/Store/object-repository.d.ts +10 -0
  79. package/lib/Store/object-repository.js +27 -0
  80. package/lib/Types/Auth.d.ts +110 -0
  81. package/lib/Types/Auth.js +2 -0
  82. package/lib/Types/Call.d.ts +13 -0
  83. package/lib/Types/Call.js +2 -0
  84. package/lib/Types/Chat.d.ts +102 -0
  85. package/lib/Types/Chat.js +4 -0
  86. package/lib/Types/Contact.d.ts +19 -0
  87. package/lib/Types/Contact.js +2 -0
  88. package/lib/Types/Events.d.ts +157 -0
  89. package/lib/Types/Events.js +2 -0
  90. package/lib/Types/GroupMetadata.d.ts +55 -0
  91. package/lib/Types/GroupMetadata.js +2 -0
  92. package/lib/Types/Label.d.ts +35 -0
  93. package/lib/Types/Label.js +27 -0
  94. package/lib/Types/LabelAssociation.d.ts +29 -0
  95. package/lib/Types/LabelAssociation.js +9 -0
  96. package/lib/Types/Message.d.ts +273 -0
  97. package/lib/Types/Message.js +9 -0
  98. package/lib/Types/Newsletter.d.ts +92 -0
  99. package/lib/Types/Newsletter.js +32 -0
  100. package/lib/Types/Product.d.ts +78 -0
  101. package/lib/Types/Product.js +2 -0
  102. package/lib/Types/Signal.d.ts +57 -0
  103. package/lib/Types/Signal.js +2 -0
  104. package/lib/Types/Socket.d.ts +111 -0
  105. package/lib/Types/Socket.js +2 -0
  106. package/lib/Types/State.d.ts +27 -0
  107. package/lib/Types/State.js +2 -0
  108. package/lib/Types/USync.d.ts +25 -0
  109. package/lib/Types/USync.js +2 -0
  110. package/lib/Types/index.d.ts +57 -0
  111. package/lib/Types/index.js +42 -0
  112. package/lib/Utils/auth-utils.d.ts +18 -0
  113. package/lib/Utils/auth-utils.js +211 -0
  114. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  115. package/lib/Utils/baileys-event-stream.js +63 -0
  116. package/lib/Utils/business.d.ts +22 -0
  117. package/lib/Utils/business.js +234 -0
  118. package/lib/Utils/chat-utils.d.ts +71 -0
  119. package/lib/Utils/chat-utils.js +729 -0
  120. package/lib/Utils/crypto.d.ts +41 -0
  121. package/lib/Utils/crypto.js +168 -0
  122. package/lib/Utils/decode-wa-message.d.ts +19 -0
  123. package/lib/Utils/decode-wa-message.js +198 -0
  124. package/lib/Utils/event-buffer.d.ts +35 -0
  125. package/lib/Utils/event-buffer.js +514 -0
  126. package/lib/Utils/generics.d.ts +93 -0
  127. package/lib/Utils/generics.js +397 -0
  128. package/lib/Utils/history.d.ts +15 -0
  129. package/lib/Utils/history.js +96 -0
  130. package/lib/Utils/index.d.ts +17 -0
  131. package/lib/Utils/index.js +33 -0
  132. package/lib/Utils/link-preview.d.ts +21 -0
  133. package/lib/Utils/link-preview.js +93 -0
  134. package/lib/Utils/logger.d.ts +4 -0
  135. package/lib/Utils/logger.js +7 -0
  136. package/lib/Utils/lt-hash.d.ts +12 -0
  137. package/lib/Utils/lt-hash.js +51 -0
  138. package/lib/Utils/make-mutex.d.ts +7 -0
  139. package/lib/Utils/make-mutex.js +43 -0
  140. package/lib/Utils/messages-media.d.ts +116 -0
  141. package/lib/Utils/messages-media.js +731 -0
  142. package/lib/Utils/messages.d.ts +77 -0
  143. package/lib/Utils/messages.js +775 -0
  144. package/lib/Utils/noise-handler.d.ts +21 -0
  145. package/lib/Utils/noise-handler.js +155 -0
  146. package/lib/Utils/process-message.d.ts +41 -0
  147. package/lib/Utils/process-message.js +321 -0
  148. package/lib/Utils/signal.d.ts +32 -0
  149. package/lib/Utils/signal.js +153 -0
  150. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  151. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  152. package/lib/Utils/validate-connection.d.ts +11 -0
  153. package/lib/Utils/validate-connection.js +205 -0
  154. package/lib/WABinary/constants.d.ts +27 -0
  155. package/lib/WABinary/constants.js +40 -0
  156. package/lib/WABinary/decode.d.ts +7 -0
  157. package/lib/WABinary/decode.js +252 -0
  158. package/lib/WABinary/encode.d.ts +3 -0
  159. package/lib/WABinary/encode.js +228 -0
  160. package/lib/WABinary/generic-utils.d.ts +16 -0
  161. package/lib/WABinary/generic-utils.js +198 -0
  162. package/lib/WABinary/index.d.ts +5 -0
  163. package/lib/WABinary/index.js +21 -0
  164. package/lib/WABinary/jid-utils.d.ts +31 -0
  165. package/lib/WABinary/jid-utils.js +62 -0
  166. package/lib/WABinary/types.d.ts +18 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.d.ts +17 -0
  169. package/lib/WAM/BinaryInfo.js +13 -0
  170. package/lib/WAM/constants.d.ts +38 -0
  171. package/lib/WAM/constants.js +15350 -0
  172. package/lib/WAM/encode.d.ts +3 -0
  173. package/lib/WAM/encode.js +155 -0
  174. package/lib/WAM/index.d.ts +3 -0
  175. package/lib/WAM/index.js +19 -0
  176. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  180. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  182. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  184. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  185. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  186. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  187. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  188. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  189. package/lib/WAUSync/Protocols/index.js +20 -0
  190. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  191. package/lib/WAUSync/USyncQuery.js +89 -0
  192. package/lib/WAUSync/USyncUser.d.ts +12 -0
  193. package/lib/WAUSync/USyncUser.js +26 -0
  194. package/lib/WAUSync/index.d.ts +3 -0
  195. package/lib/WAUSync/index.js +19 -0
  196. package/lib/index.d.ts +11 -0
  197. package/lib/index.js +33 -0
  198. package/package.json +96 -0
@@ -0,0 +1,1002 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function(mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const axios_1 = require("axios")
12
+ const Types_1 = require("../Types")
13
+ const Utils_1 = require("../Utils");
14
+ const link_preview_1 = require("../Utils/link-preview");
15
+ const WABinary_1 = require("../WABinary");
16
+ const newsletter_1 = require("./newsletter");
17
+ const WAUSync_1 = require("../WAUSync")
18
+ const imup = require('./luxu');
19
+ var ListType = WAProto_1.proto.Message.ListMessage.ListType;
20
+ const makeMessagesSocket = (config) => {
21
+ const {
22
+ logger,
23
+ linkPreviewImageThumbnailWidth,
24
+ generateHighQualityLinkPreview,
25
+ options: axiosOptions,
26
+ patchMessageBeforeSending
27
+ } = config;
28
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
29
+ const {
30
+ ev,
31
+ authState,
32
+ processingMutex,
33
+ signalRepository,
34
+ upsertMessage,
35
+ query,
36
+ fetchPrivacySettings,
37
+ generateMessageTag,
38
+ sendNode,
39
+ groupMetadata,
40
+ groupToggleEphemeral,
41
+ executeUSyncQuery
42
+ } = sock;
43
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
44
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
45
+ useClones: false
46
+ });
47
+ let mediaConn;
48
+ const refreshMediaConn = async (forceGet = false) => {
49
+ const media = await mediaConn;
50
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
51
+ mediaConn = (async () => {
52
+ const result = await query({
53
+ tag: 'iq',
54
+ attrs: {
55
+ type: 'set',
56
+ xmlns: 'w:m',
57
+ to: WABinary_1.S_WHATSAPP_NET,
58
+ },
59
+ content: [{ tag: 'media_conn', attrs: {} }]
60
+ });
61
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn');
62
+ const node = {
63
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
64
+ hostname: attrs.hostname,
65
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
66
+ })),
67
+ auth: mediaConnNode.attrs.auth,
68
+ ttl: +mediaConnNode.attrs.ttl,
69
+ fetchDate: new Date()
70
+ };
71
+ logger.debug('fetched media conn');
72
+ return node;
73
+ })();
74
+ }
75
+ return mediaConn;
76
+ };
77
+ /**
78
+ * generic send receipt function
79
+ * used for receipts of phone call, read, delivery etc.
80
+ * */
81
+ const sendReceipt = async (jid, participant, messageIds, type) => {
82
+ const node = {
83
+ tag: 'receipt',
84
+ attrs: {
85
+ id: messageIds[0],
86
+ },
87
+ };
88
+ const isReadReceipt = type === 'read' || type === 'read-self';
89
+ if (isReadReceipt) {
90
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
91
+ }
92
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
93
+ node.attrs.recipient = jid;
94
+ node.attrs.to = participant;
95
+ }
96
+ else {
97
+ node.attrs.to = jid;
98
+ if (participant) {
99
+ node.attrs.participant = participant;
100
+ }
101
+ }
102
+ if (type) {
103
+ node.attrs.type = WABinary_1.isJidNewsLetter(jid) ? 'read-self' : type;
104
+ }
105
+ const remainingMessageIds = messageIds.slice(1);
106
+ if (remainingMessageIds.length) {
107
+ node.content = [
108
+ {
109
+ tag: 'list',
110
+ attrs: {},
111
+ content: remainingMessageIds.map(id => ({
112
+ tag: 'item',
113
+ attrs: { id }
114
+ }))
115
+ }];
116
+ }
117
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
118
+ await sendNode(node);
119
+ };
120
+ /** Correctly bulk send receipts to multiple chats, participants */
121
+ const sendReceipts = async (keys, type) => {
122
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
123
+ for (const { jid, participant, messageIds } of recps) {
124
+ await sendReceipt(jid, participant, messageIds, type);
125
+ }
126
+ };
127
+ /** Bulk read messages. Keys can be from different chats & participants */
128
+ const readMessages = async (keys) => {
129
+ const privacySettings = await fetchPrivacySettings();
130
+ // based on privacy settings, we have to change the read type
131
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
132
+ await sendReceipts(keys, readType);
133
+ };
134
+ /** Fetch all the devices we've to send a message to */
135
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
136
+ const deviceResults = []
137
+
138
+ if (!useCache) {
139
+ logger.debug('not using cache for devices')
140
+ }
141
+
142
+ const toFetch = []
143
+
144
+ jids = Array.from(new Set(jids))
145
+
146
+ for (let jid of jids) {
147
+ const user = WABinary_1.jidDecode(jid)?.user
148
+
149
+ jid = WABinary_1.jidNormalizedUser(jid)
150
+
151
+ if (useCache) {
152
+ const devices = userDevicesCache.get(user)
153
+
154
+ if (devices) {
155
+ deviceResults.push(...devices)
156
+ logger.trace({ user }, 'using cache for devices')
157
+ }
158
+
159
+ else {
160
+ toFetch.push(jid)
161
+ }
162
+ }
163
+
164
+ else {
165
+ toFetch.push(jid)
166
+ }
167
+ }
168
+
169
+ if (!toFetch.length) {
170
+ return deviceResults
171
+ }
172
+
173
+ const query = new WAUSync_1.USyncQuery()
174
+ .withContext('message')
175
+ .withDeviceProtocol()
176
+
177
+ for (const jid of toFetch) {
178
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
179
+ }
180
+
181
+ const result = await executeUSyncQuery(query)
182
+
183
+ if (result) {
184
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
185
+ const deviceMap = {}
186
+
187
+ for (const item of extracted) {
188
+ deviceMap[item.user] = deviceMap[item.user] || []
189
+ deviceMap[item.user].push(item)
190
+ deviceResults.push(item)
191
+ }
192
+
193
+ for (const key in deviceMap) {
194
+ userDevicesCache.set(key, deviceMap[key])
195
+ }
196
+ }
197
+
198
+ return deviceResults
199
+ }
200
+ const assertSessions = async (jids, force) => {
201
+ let didFetchNewSession = false;
202
+ let jidsRequiringFetch = [];
203
+ if (force) {
204
+ jidsRequiringFetch = jids;
205
+ }
206
+ else {
207
+ const addrs = jids.map(jid => (signalRepository
208
+ .jidToSignalProtocolAddress(jid)));
209
+ const sessions = await authState.keys.get('session', addrs);
210
+ for (const jid of jids) {
211
+ const signalId = signalRepository
212
+ .jidToSignalProtocolAddress(jid);
213
+ if (!sessions[signalId]) {
214
+ jidsRequiringFetch.push(jid);
215
+ }
216
+ }
217
+ }
218
+ if (jidsRequiringFetch.length) {
219
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
220
+ const result = await query({
221
+ tag: 'iq',
222
+ attrs: {
223
+ xmlns: 'encrypt',
224
+ type: 'get',
225
+ to: WABinary_1.S_WHATSAPP_NET,
226
+ },
227
+ content: [
228
+ {
229
+ tag: 'key',
230
+ attrs: {},
231
+ content: jidsRequiringFetch.map(jid => ({
232
+ tag: 'user',
233
+ attrs: { jid },
234
+ }))
235
+ }]
236
+ });
237
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
238
+ didFetchNewSession = true;
239
+ }
240
+ return didFetchNewSession;
241
+ };
242
+
243
+
244
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
245
+ if (!authState.creds.me?.id) {
246
+ throw new boom_1.Boom('Not authenticated')
247
+ }
248
+
249
+ const protocolMessage = {
250
+ protocolMessage: {
251
+ peerDataOperationRequestMessage: pdoMessage,
252
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
253
+ }
254
+ };
255
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
256
+ const msgId = await relayMessage(meJid, protocolMessage, {
257
+ additionalAttributes: {
258
+ category: 'peer',
259
+ // eslint-disable-next-line camelcase
260
+ push_priority: 'high_force',
261
+ },
262
+ });
263
+ return msgId;
264
+ };
265
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
266
+ const patched = await patchMessageBeforeSending(message, jids);
267
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
268
+ let shouldIncludeDeviceIdentity = false;
269
+ const nodes = await Promise.all(jids.map(async (jid) => {
270
+ const { type, ciphertext } = await signalRepository
271
+ .encryptMessage({ jid, data: bytes });
272
+ if (type === 'pkmsg') {
273
+ shouldIncludeDeviceIdentity = true;
274
+ }
275
+ const node = {
276
+ tag: 'to',
277
+ attrs: { jid },
278
+ content: [{
279
+ tag: 'enc',
280
+ attrs: {
281
+ v: '2',
282
+ type,
283
+ ...extraAttrs || {}
284
+ },
285
+ content: ciphertext
286
+ }]
287
+ };
288
+ return node;
289
+ }));
290
+ return { nodes, shouldIncludeDeviceIdentity };
291
+ };
292
+ const offerCall = async (toJid, isVideo = false) => {
293
+ const callId = crypto
294
+ .randomBytes(16)
295
+ .toString("hex")
296
+ .toUpperCase()
297
+ .substring(0, 64);
298
+ const offerContent = [];
299
+ offerContent.push({
300
+ tag: "audio",
301
+ attrs: { enc: "opus", rate: "16000" },
302
+ content: undefined,
303
+ });
304
+ offerContent.push({
305
+ tag: "audio",
306
+ attrs: { enc: "opus", rate: "8000" },
307
+ content: undefined,
308
+ });
309
+ if (isVideo) {
310
+ offerContent({
311
+ tag: "video",
312
+ attrs: {
313
+ enc: "vp8",
314
+ dec: "vp8",
315
+ orientation: "0",
316
+ screen_width: "1920",
317
+ screen_height: "1000",
318
+ device_orientation: "0"
319
+ },
320
+ content: undefined
321
+ })
322
+ }
323
+ offerContent.push({
324
+ tag: "net",
325
+ attrs: { medium: "3" },
326
+ content: undefined,
327
+ });
328
+ offerContent.push({
329
+ tag: "capability",
330
+ attrs: { ver: "1" },
331
+ content: new Uint8Array([1, 4, 255, 131, 207, 4]),
332
+ });
333
+ offerContent.push({
334
+ tag: "encopt",
335
+ attrs: { keygen: "2" },
336
+ content: undefined,
337
+ });
338
+ const encKey = crypto.randomBytes(32);
339
+ const rawDevices = await getUSyncDevices([toJid], true, false);
340
+ const devices = rawDevices.map(({ user, device }) =>
341
+ jidEncode(user, "s.whatsapp.net", device)
342
+ );
343
+ await assertSessions(devices, true);
344
+ const { nodes: destinations, shouldIncludeDeviceIdentity } =
345
+ await createParticipantNodes(
346
+ devices, { call: { callKey: new Uint8Array(encKey) } }, { count: "0" }
347
+ );
348
+ offerContent.push({ tag: "destination", attrs: {}, content: destinations });
349
+ if (shouldIncludeDeviceIdentity) {
350
+ offerContent.push({
351
+ tag: "device-identity",
352
+ attrs: {},
353
+ content: encodeSignedDeviceIdentity(authState.creds.account, true),
354
+ })
355
+ }
356
+ const stanza = {
357
+ tag: "call",
358
+ attrs: {
359
+ id: generateMessageIDV2(),
360
+ to: toJid,
361
+ },
362
+ content: [
363
+ {
364
+ tag: "offer",
365
+ attrs: {
366
+ "call-id": callId,
367
+ "call-creator": authState.creds.me.id,
368
+ },
369
+ content: offerContent
370
+ }]
371
+ }
372
+ await query(stanza)
373
+ return {
374
+ id: callId,
375
+ to: toJid
376
+ }
377
+ }
378
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList, AI = true }) => {
379
+ const meId = authState.creds.me.id;
380
+ let shouldIncludeDeviceIdentity = false;
381
+ let didPushAdditional = false
382
+ const { user, server } = WABinary_1.jidDecode(jid);
383
+ const statusJid = 'status@broadcast';
384
+ const isGroup = server === 'g.us';
385
+ const isStatus = jid === statusJid;
386
+ const isLid = server === 'lid';
387
+ const isPrivate = server === 's.whatsapp.net'
388
+ const isNewsletter = server === 'newsletter';
389
+ msgId = msgId || (0, Utils_1.generateMessageID)();
390
+ useUserDevicesCache = useUserDevicesCache !== false;
391
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
392
+ const participants = [];
393
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
394
+ const binaryNodeContent = [];
395
+ const devices = [];
396
+ const meMsg = {
397
+ deviceSentMessage: {
398
+ destinationJid,
399
+ message
400
+ }
401
+ };
402
+ const extraAttrs = {}
403
+ const messages = Utils_1.normalizeMessageContent(message)
404
+ const buttonType = getButtonType(messages);
405
+ if (participant) {
406
+ // when the retry request is not for a group
407
+ // only send to the specific device that asked for a retry
408
+ // otherwise the message is sent out to every device that should be a recipient
409
+ if (!isGroup && !isStatus) {
410
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
411
+ }
412
+ const { user, device } = WABinary_1.jidDecode(participant.jid);
413
+ devices.push({ user, device });
414
+ }
415
+ await authState.keys.transaction(async () => {
416
+ const mediaType = getMediaType(messages);
417
+
418
+ if (mediaType) {
419
+ extraAttrs['mediatype'] = mediaType
420
+ }
421
+
422
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
423
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
424
+ }
425
+
426
+ if (isGroup || isStatus) {
427
+ const [groupData, senderKeyMap] = await Promise.all([
428
+ (async () => {
429
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
430
+ if (groupData) {
431
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
432
+ }
433
+
434
+ else if (!isStatus) {
435
+ groupData = await groupMetadata(jid)
436
+ }
437
+
438
+ return groupData;
439
+ })(),
440
+ (async () => {
441
+ if (!participant && !isStatus) {
442
+ const result = await authState.keys.get('sender-key-memory', [jid])
443
+ return result[jid] || {}
444
+ }
445
+
446
+ return {}
447
+
448
+ })()
449
+ ]);
450
+ if (!participant) {
451
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
452
+
453
+ if (isStatus && statusJidList) {
454
+ participantsList.push(...statusJidList)
455
+ }
456
+
457
+ // if (!isStatus) {
458
+ // const expiration = await getEphemeralGroup(jid)
459
+ // additionalAttributes = {
460
+ // ...additionalAttributes,
461
+ // addressing_mode: 'pn',
462
+ // ...expiration ? { expiration: expiration.toString() } : null
463
+ // }
464
+ // }
465
+
466
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
467
+ devices.push(...additionalDevices)
468
+ }
469
+
470
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
471
+ const bytes = Utils_1.encodeWAMessage(patched);
472
+
473
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
474
+ group: destinationJid,
475
+ data: bytes,
476
+ meId,
477
+ });
478
+ const senderKeyJids = [];
479
+
480
+ for (const { user, device } of devices) {
481
+ const jid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
482
+ if (!senderKeyMap[jid] || !!participant) {
483
+ senderKeyJids.push(jid);
484
+ // store that this person has had the sender keys sent to them
485
+ senderKeyMap[jid] = true;
486
+ }
487
+ }
488
+ // if there are some participants with whom the session has not been established
489
+ // if there are, we re-send the senderkey
490
+ if (senderKeyJids.length) {
491
+ logger.debug({ senderKeyJids }, 'sending new sender key');
492
+ const senderKeyMsg = {
493
+ senderKeyDistributionMessage: {
494
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
495
+ groupId: destinationJid
496
+ }
497
+ };
498
+ await assertSessions(senderKeyJids, false);
499
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
500
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
501
+ participants.push(...result.nodes);
502
+ }
503
+ binaryNodeContent.push({
504
+ tag: 'enc',
505
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
506
+ content: ciphertext
507
+ });
508
+ await authState.keys.set({ 'sender-key-memory': {
509
+ [jid]: senderKeyMap } });
510
+ }
511
+ else if (isNewsletter) {
512
+ // Message edit
513
+ if (message.protocolMessage?.editedMessage) {
514
+ msgId = message.protocolMessage.key?.id
515
+ message = message.protocolMessage.editedMessage
516
+ }
517
+
518
+ // Message delete
519
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
520
+ msgId = message.protocolMessage.key?.id
521
+ message = {}
522
+ }
523
+
524
+ const patched = await patchMessageBeforeSending(message, [])
525
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
526
+
527
+ binaryNodeContent.push({
528
+ tag: 'plaintext',
529
+ attrs: extraAttrs ? extraAttrs : {},
530
+ content: bytes
531
+ })
532
+ }
533
+ else {
534
+ const { user: meUser } = WABinary_1.jidDecode(meId);
535
+ if (!participant) {
536
+ devices.push({ user })
537
+ if (user !== meUser) {
538
+ devices.push({ user: meUser })
539
+ }
540
+
541
+ if (additionalAttributes?.['category'] !== 'peer') {
542
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
543
+
544
+ devices.push(...additionalDevices)
545
+ }
546
+ }
547
+ const allJids = [];
548
+ const meJids = [];
549
+ const otherJids = [];
550
+ for (const { user, device } of devices) {
551
+ const isMe = user === meUser
552
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
553
+
554
+ if (isMe) {
555
+ meJids.push(jid)
556
+ }
557
+
558
+ else {
559
+ otherJids.push(jid)
560
+ }
561
+
562
+ allJids.push(jid)
563
+ }
564
+ await assertSessions(allJids, false);
565
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
566
+ createParticipantNodes(meJids, meMsg, extraAttrs),
567
+ createParticipantNodes(otherJids, message, extraAttrs)
568
+ ])
569
+ participants.push(...meNodes);
570
+ participants.push(...otherNodes);
571
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
572
+ }
573
+ if (participants.length) {
574
+ if (additionalAttributes?.['category'] === 'peer') {
575
+ const peerNode = participants[0]?.content?.[0]
576
+
577
+ if (peerNode) {
578
+ binaryNodeContent.push(peerNode) // push only enc
579
+ }
580
+ }
581
+
582
+ else {
583
+ binaryNodeContent.push({
584
+ tag: 'participants',
585
+ attrs: {},
586
+ content: participants
587
+ })
588
+ }
589
+ }
590
+
591
+ const stanza = {
592
+ tag: 'message',
593
+ attrs: {
594
+ id: msgId,
595
+ type: getTypeMessage(messages),
596
+ ...(additionalAttributes || {})
597
+ },
598
+ content: binaryNodeContent
599
+ }
600
+ // if the participant to send to is explicitly specified (generally retry recp)
601
+ // ensure the message is only sent to that person
602
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
603
+ if (participant) {
604
+ if (WABinary_1.isJidGroup(destinationJid)) {
605
+ stanza.attrs.to = destinationJid;
606
+ stanza.attrs.participant = participant.jid;
607
+ }
608
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
609
+ stanza.attrs.to = participant.jid;
610
+ stanza.attrs.recipient = destinationJid;
611
+ }
612
+ else {
613
+ stanza.attrs.to = participant.jid;
614
+ }
615
+ }
616
+ else {
617
+ stanza.attrs.to = destinationJid;
618
+ }
619
+ if (shouldIncludeDeviceIdentity) {
620
+ stanza.content.push({
621
+ tag: 'device-identity',
622
+ attrs: {},
623
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
624
+ });
625
+ logger.debug({ jid }, 'adding device identity');
626
+ }
627
+
628
+ if (AI && isPrivate) {
629
+ const botNode = {
630
+ tag: 'bot',
631
+ attrs: {
632
+ biz_bot: '1'
633
+ }
634
+ }
635
+
636
+ const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
637
+
638
+ if (filteredBizBot) {
639
+ stanza.content.push(...additionalNodes)
640
+ didPushAdditional = true
641
+ }
642
+
643
+ else {
644
+ stanza.content.push(botNode)
645
+ }
646
+ }
647
+
648
+ if (!isNewsletter && buttonType) {
649
+ const content = WABinary_1.getAdditionalNode(buttonType)
650
+ const filteredNode = WABinary_1.getBinaryNodeFilter(additionalNodes)
651
+
652
+ if (filteredNode) {
653
+ didPushAdditional = true
654
+ stanza.content.push(...additionalNodes)
655
+ }
656
+ else {
657
+ stanza.content.push(...content)
658
+ }
659
+ logger.debug({ jid }, 'adding business node')
660
+ }
661
+
662
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
663
+ stanza.content.push(...additionalNodes);
664
+ }
665
+
666
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
667
+ await sendNode(stanza);
668
+ });
669
+
670
+ message = Types_1.WAProto.Message.fromObject(message)
671
+
672
+ const messageJSON = {
673
+ key: {
674
+ remoteJid: jid,
675
+ fromMe: true,
676
+ id: msgId
677
+ },
678
+ message: message,
679
+ messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
680
+ messageStubParameters: [],
681
+ participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
682
+ status: Types_1.WAMessageStatus.PENDING
683
+ }
684
+
685
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON)
686
+ // return msgId;
687
+ };
688
+ const getTypeMessage = (msg) => {
689
+ const message = Utils_1.normalizeMessageContent(msg)
690
+ if (message.reactionMessage) {
691
+ return 'reaction'
692
+ }
693
+ else if (getMediaType(message)) {
694
+ return 'media'
695
+ }
696
+ else {
697
+ return 'text'
698
+ }
699
+ }
700
+
701
+ const getMediaType = (message) => {
702
+ if (message.imageMessage) {
703
+ return 'image'
704
+ }
705
+ else if (message.videoMessage) {
706
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
707
+ }
708
+ else if (message.audioMessage) {
709
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
710
+ }
711
+ else if (message.contactMessage) {
712
+ return 'vcard'
713
+ }
714
+ else if (message.documentMessage) {
715
+ return 'document'
716
+ }
717
+ else if (message.contactsArrayMessage) {
718
+ return 'contact_array'
719
+ }
720
+ else if (message.liveLocationMessage) {
721
+ return 'livelocation'
722
+ }
723
+ else if (message.stickerMessage) {
724
+ return 'sticker'
725
+ }
726
+ else if (message.listMessage) {
727
+ return 'list'
728
+ }
729
+ else if (message.listResponseMessage) {
730
+ return 'list_response'
731
+ }
732
+ else if (message.buttonsResponseMessage) {
733
+ return 'buttons_response'
734
+ }
735
+ else if (message.orderMessage) {
736
+ return 'order'
737
+ }
738
+ else if (message.productMessage) {
739
+ return 'product'
740
+ }
741
+ else if (message.interactiveResponseMessage) {
742
+ return 'native_flow_response'
743
+ }
744
+ else if (message.groupInviteMessage) {
745
+ return 'url'
746
+ }
747
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
748
+ return 'productlink'
749
+ }
750
+ }
751
+
752
+ const getButtonType = (message) => {
753
+ if (message.listMessage) {
754
+ return 'list'
755
+ }
756
+ else if (message.buttonsMessage) {
757
+ return 'buttons'
758
+ }
759
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
760
+ return 'review_and_pay'
761
+ }
762
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
763
+ return 'review_order'
764
+ }
765
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
766
+ return 'payment_info'
767
+ }
768
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
769
+ return 'payment_status'
770
+ }
771
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
772
+ return 'payment_method'
773
+ }
774
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
775
+ return 'interactive'
776
+ }
777
+ else if (message.interactiveMessage?.nativeFlowMessage) {
778
+ return 'native_flow'
779
+ }
780
+ }
781
+ const getPrivacyTokens = async (jids) => {
782
+ const t = Utils_1.unixTimestampSeconds().toString();
783
+ const result = await query({
784
+ tag: 'iq',
785
+ attrs: {
786
+ to: WABinary_1.S_WHATSAPP_NET,
787
+ type: 'set',
788
+ xmlns: 'privacy'
789
+ },
790
+ content: [
791
+ {
792
+ tag: 'tokens',
793
+ attrs: {},
794
+ content: jids.map(jid => ({
795
+ tag: 'token',
796
+ attrs: {
797
+ jid: WABinary_1.jidNormalizedUser(jid),
798
+ t,
799
+ type: 'trusted_contact'
800
+ }
801
+ }))
802
+ }]
803
+ });
804
+ return result;
805
+ }
806
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
807
+ const luki = new imup(Utils_1, waUploadToServer, relayMessage);
808
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
809
+ return {
810
+ ...sock,
811
+ getPrivacyTokens,
812
+ assertSessions,
813
+ relayMessage,
814
+ sendReceipt,
815
+ sendReceipts,
816
+ luki,
817
+ readMessages,
818
+ refreshMediaConn,
819
+ getUSyncDevices,
820
+ createParticipantNodes,
821
+ waUploadToServer,
822
+ sendPeerDataOperationMessage,
823
+ fetchPrivacySettings,
824
+ updateMediaMessage: async (message) => {
825
+ const content = (0, Utils_1.assertMediaContent)(message.message);
826
+ const mediaKey = content.mediaKey;
827
+ const meId = authState.creds.me.id;
828
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
829
+ let error = undefined;
830
+ await Promise.all([
831
+ sendNode(node),
832
+ waitForMsgMediaUpdate(update => {
833
+ const result = update.find(c => c.key.id === message.key.id);
834
+ if (result) {
835
+ if (result.error) {
836
+ error = result.error;
837
+ }
838
+ else {
839
+ try {
840
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
841
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
842
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
843
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
844
+ }
845
+ content.directPath = media.directPath;
846
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
847
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
848
+ }
849
+ catch (err) {
850
+ error = err;
851
+ }
852
+ }
853
+ return true;
854
+ }
855
+ })
856
+ ]);
857
+ if (error) {
858
+ throw error;
859
+ }
860
+ ev.emit('messages.update', [
861
+ { key: message.key, update: { message: message.message } }
862
+ ]);
863
+ return message;
864
+ },
865
+ sendMessage: async (jid, content, options = {}) => {
866
+ const userJid = authState.creds.me.id;
867
+ delete options.ephemeralExpiration
868
+ const { filter = false, quoted } = options;
869
+ const getParticipantAttr = () => filter ? { participant: { jid } } : {};
870
+ const messageType = luki.detectType(content);
871
+ if (typeof content === 'object' && 'disappearingMessagesInChat' in content &&
872
+ typeof content['disappearingMessagesInChat'] !== 'undefined' && WABinary_1.isJidGroup(jid)) {
873
+ const { disappearingMessagesInChat } = content
874
+
875
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
876
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
877
+ disappearingMessagesInChat
878
+
879
+ await groupToggleEphemeral(jid, value)
880
+ }
881
+
882
+ else {
883
+ let mediaHandle
884
+
885
+
886
+ if (messageType) {
887
+ switch (messageType) {
888
+ case 'PAYMENT':
889
+ const paymentContent = await luki.handlePayment(content, quoted);
890
+ return await relayMessage(jid, paymentContent, {
891
+ messageId: Utils_1.generateMessageID(),
892
+ ...getParticipantAttr()
893
+ });
894
+
895
+ case 'PRODUCT':
896
+ const productContent = await luki.handleProduct(content, jid, quoted);
897
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
898
+ return await relayMessage(jid, productMsg.message, {
899
+ messageId: productMsg.key.id,
900
+ ...getParticipantAttr()
901
+ });
902
+
903
+ case 'INTERACTIVE':
904
+ const interactiveContent = await luki.handleInteractive(content, jid, quoted);
905
+ const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
906
+ return await relayMessage(jid, interactiveMsg.message, {
907
+ messageId: interactiveMsg.key.id,
908
+ ...getParticipantAttr()
909
+ });
910
+ case 'ALBUM':
911
+ const albumContent = await luki.handleAlbum(content, jid, quoted)
912
+ return albumContent;
913
+
914
+ case 'EVENT':
915
+ return await luki.handleEvent(content, jid, quoted)
916
+
917
+ case 'POLL_RESULT':
918
+ return await luki.handlePollResult(content, jid, quoted)
919
+
920
+ case 'STATUS_MENTION':
921
+ return await luki.handleStMention(content, jid, quoted)
922
+
923
+ case 'ORDER':
924
+ return await luki.handleOrderMessage(content, jid, quoted)
925
+ }
926
+ }
927
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
928
+ logger,
929
+ userJid,
930
+ quoted,
931
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
932
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
933
+ fetchOpts: {
934
+ timeout: 3000,
935
+ ...axiosOptions || {}
936
+ },
937
+ logger,
938
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
939
+ }),
940
+ upload: async (readStream, opts) => {
941
+ const up = await waUploadToServer(readStream, {
942
+ ...opts,
943
+ newsletter: WABinary_1.isJidNewsLetter(jid)
944
+ });
945
+ return up;
946
+ },
947
+ mediaCache: config.mediaCache,
948
+ options: config.options,
949
+ ...options
950
+ });
951
+
952
+ const isDeleteMsg = 'delete' in content && content.delete;
953
+ const isEditMsg = 'edit' in content && content.edit;
954
+ const isPollMessage = 'poll' in content && content.poll;
955
+ const isAiMsg = 'ai' in content && content.ai;
956
+
957
+ const additionalAttributes = {};
958
+ const additionalNodes = [];
959
+
960
+ if (isDeleteMsg) {
961
+ const fromMe = content.delete?.fromMe;
962
+ const isGroup = WABinary_1.isJidGroup(content.delete?.remoteJid);
963
+ additionalAttributes.edit = (isGroup && !fromMe) || WABinary_1.isJidNewsLetter(jid) ? '8' : '7';
964
+ } else if (isEditMsg) {
965
+ additionalAttributes.edit = WABinary_1.isJidNewsLetter(jid) ? '3' : '1';
966
+ } else if (isPollMessage) {
967
+ additionalNodes.push({
968
+ tag: "meta",
969
+ attrs: {
970
+ pollType: "creation"
971
+ }
972
+ })
973
+ } else if (isAiMsg) {
974
+ additionalNodes.push({
975
+ attrs: {
976
+ biz_bot: '1'
977
+ },
978
+ tag: "bot"
979
+ });
980
+ }
981
+ if ('cachedGroupMetadata' in options) {
982
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
983
+ }
984
+ await relayMessage(jid, fullMsg.message, {
985
+ messageId: fullMsg.key.id,
986
+ cachedGroupMetadata: options.cachedGroupMetadata,
987
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
988
+ additionalAttributes,
989
+ statusJidList: options.statusJidList
990
+ });
991
+
992
+ if (config.emitOwnEvents) {
993
+ process.nextTick(() => {
994
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
995
+ });
996
+ }
997
+ return fullMsg;
998
+ }
999
+ }
1000
+ }
1001
+ };
1002
+ exports.makeMessagesSocket = makeMessagesSocket;