@than-xs/baileys 2.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +422 -0
  3. package/WAProto/index.js +169661 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.js +147 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.js +64 -0
  10. package/lib/Signal/Group/group_cipher.js +96 -0
  11. package/lib/Signal/Group/index.js +57 -0
  12. package/lib/Signal/Group/keyhelper.js +55 -0
  13. package/lib/Signal/Group/queue-job.js +57 -0
  14. package/lib/Signal/Group/sender-chain-key.js +34 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-message.js +69 -0
  17. package/lib/Signal/Group/sender-key-name.js +51 -0
  18. package/lib/Signal/Group/sender-key-record.js +53 -0
  19. package/lib/Signal/Group/sender-key-state.js +99 -0
  20. package/lib/Signal/Group/sender-message-key.js +29 -0
  21. package/lib/Signal/libsignal.js +174 -0
  22. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  23. package/lib/Socket/Client/index.js +19 -0
  24. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  25. package/lib/Socket/Client/web-socket-client.js +62 -0
  26. package/lib/Socket/business.js +260 -0
  27. package/lib/Socket/chats.js +1002 -0
  28. package/lib/Socket/dugong.js +637 -0
  29. package/lib/Socket/groups.js +317 -0
  30. package/lib/Socket/index.js +11 -0
  31. package/lib/Socket/messages-recv.js +1110 -0
  32. package/lib/Socket/messages-send.js +831 -0
  33. package/lib/Socket/newsletter.js +459 -0
  34. package/lib/Socket/registration.js +166 -0
  35. package/lib/Socket/socket.js +662 -0
  36. package/lib/Socket/usync.js +70 -0
  37. package/lib/Store/index.js +10 -0
  38. package/lib/Store/make-cache-manager-store.js +83 -0
  39. package/lib/Store/make-in-memory-store.js +427 -0
  40. package/lib/Store/make-ordered-dictionary.js +81 -0
  41. package/lib/Store/object-repository.js +27 -0
  42. package/lib/Types/Auth.js +2 -0
  43. package/lib/Types/Call.js +2 -0
  44. package/lib/Types/Chat.js +4 -0
  45. package/lib/Types/Contact.js +2 -0
  46. package/lib/Types/Events.js +2 -0
  47. package/lib/Types/GroupMetadata.js +2 -0
  48. package/lib/Types/Label.js +27 -0
  49. package/lib/Types/LabelAssociation.js +9 -0
  50. package/lib/Types/Message.js +9 -0
  51. package/lib/Types/Newsletter.js +38 -0
  52. package/lib/Types/Product.js +2 -0
  53. package/lib/Types/Signal.js +2 -0
  54. package/lib/Types/Socket.js +2 -0
  55. package/lib/Types/State.js +2 -0
  56. package/lib/Types/USync.js +2 -0
  57. package/lib/Types/index.js +42 -0
  58. package/lib/Utils/auth-utils.js +206 -0
  59. package/lib/Utils/baileys-event-stream.js +63 -0
  60. package/lib/Utils/business.js +234 -0
  61. package/lib/Utils/chat-utils.js +729 -0
  62. package/lib/Utils/crypto.js +151 -0
  63. package/lib/Utils/decode-wa-message.js +198 -0
  64. package/lib/Utils/event-buffer.js +514 -0
  65. package/lib/Utils/generics.js +498 -0
  66. package/lib/Utils/history.js +96 -0
  67. package/lib/Utils/index.js +33 -0
  68. package/lib/Utils/link-preview.js +93 -0
  69. package/lib/Utils/logger.js +7 -0
  70. package/lib/Utils/lt-hash.js +51 -0
  71. package/lib/Utils/make-mutex.js +43 -0
  72. package/lib/Utils/messages-media.js +819 -0
  73. package/lib/Utils/messages.js +819 -0
  74. package/lib/Utils/noise-handler.js +155 -0
  75. package/lib/Utils/process-message.js +321 -0
  76. package/lib/Utils/signal.js +153 -0
  77. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  78. package/lib/Utils/validate-connection.js +229 -0
  79. package/lib/WABinary/constants.js +40 -0
  80. package/lib/WABinary/decode.js +252 -0
  81. package/lib/WABinary/encode.js +265 -0
  82. package/lib/WABinary/generic-utils.js +198 -0
  83. package/lib/WABinary/index.js +21 -0
  84. package/lib/WABinary/jid-utils.js +62 -0
  85. package/lib/WABinary/types.js +2 -0
  86. package/lib/WAM/BinaryInfo.js +13 -0
  87. package/lib/WAM/constants.js +15350 -0
  88. package/lib/WAM/encode.js +155 -0
  89. package/lib/WAM/index.js +19 -0
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  94. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  96. package/lib/WAUSync/Protocols/index.js +20 -0
  97. package/lib/WAUSync/USyncQuery.js +89 -0
  98. package/lib/WAUSync/USyncUser.js +26 -0
  99. package/lib/WAUSync/index.js +19 -0
  100. package/lib/index.js +84 -0
  101. package/package.json +110 -0
@@ -0,0 +1,831 @@
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 Types_1 = require("../Types");
12
+ const Utils_1 = require("../Utils");
13
+ const link_preview_1 = require("../Utils/link-preview");
14
+ const WABinary_1 = require("../WABinary");
15
+ const newsletter_1 = require("./newsletter");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const kikyy = require('./dugong');
18
+ const makeMessagesSocket = (config) => {
19
+ const {
20
+ logger,
21
+ linkPreviewImageThumbnailWidth,
22
+ generateHighQualityLinkPreview,
23
+ options: axiosOptions,
24
+ patchMessageBeforeSending
25
+ } = config;
26
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
27
+ const {
28
+ ev,
29
+ authState,
30
+ processingMutex,
31
+ signalRepository,
32
+ upsertMessage,
33
+ query,
34
+ fetchPrivacySettings,
35
+ sendNode,
36
+ groupMetadata,
37
+ groupToggleEphemeral,
38
+ executeUSyncQuery
39
+ } = sock;
40
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
41
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
42
+ useClones: false
43
+ });
44
+ let mediaConn;
45
+ const refreshMediaConn = async (forceGet = false) => {
46
+ const media = await mediaConn;
47
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
48
+ mediaConn = (async () => {
49
+ const result = await query({
50
+ tag: 'iq',
51
+ attrs: {
52
+ type: 'set',
53
+ xmlns: 'w:m',
54
+ to: WABinary_1.S_WHATSAPP_NET,
55
+ },
56
+ content: [{ tag: 'media_conn', attrs: {} }]
57
+ });
58
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn');
59
+ const node = {
60
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
61
+ hostname: attrs.hostname,
62
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
63
+ })),
64
+ auth: mediaConnNode.attrs.auth,
65
+ ttl: +mediaConnNode.attrs.ttl,
66
+ fetchDate: new Date()
67
+ };
68
+ logger.debug('fetched media conn');
69
+ return node;
70
+ })();
71
+ }
72
+ return mediaConn;
73
+ };
74
+ const sendReceipt = async (jid, participant, messageIds, type) => {
75
+ const node = {
76
+ tag: 'receipt',
77
+ attrs: {
78
+ id: messageIds[0],
79
+ },
80
+ };
81
+ const isReadReceipt = type === 'read' || type === 'read-self';
82
+ if (isReadReceipt) {
83
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
84
+ }
85
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
86
+ node.attrs.recipient = jid;
87
+ node.attrs.to = participant;
88
+ }
89
+ else {
90
+ node.attrs.to = jid;
91
+ if (participant) {
92
+ node.attrs.participant = participant;
93
+ }
94
+ }
95
+ if (type) {
96
+ node.attrs.type = WABinary_1.isJidNewsLetter(jid) ? 'read-self' : type;
97
+ }
98
+ const remainingMessageIds = messageIds.slice(1);
99
+ if (remainingMessageIds.length) {
100
+ node.content = [
101
+ {
102
+ tag: 'list',
103
+ attrs: {},
104
+ content: remainingMessageIds.map(id => ({
105
+ tag: 'item',
106
+ attrs: { id }
107
+ }))
108
+ }
109
+ ];
110
+ }
111
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
112
+ await sendNode(node);
113
+ };
114
+ const sendReceipts = async (keys, type) => {
115
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
116
+ for (const { jid, participant, messageIds } of recps) {
117
+ await sendReceipt(jid, participant, messageIds, type);
118
+ }
119
+ };
120
+ const readMessages = async (keys) => {
121
+ const privacySettings = await fetchPrivacySettings();
122
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
123
+ await sendReceipts(keys, readType);
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
+ jids = Array.from(new Set(jids))
132
+ for (let jid of jids) {
133
+ const user = WABinary_1.jidDecode(jid)?.user
134
+ jid = WABinary_1.jidNormalizedUser(jid)
135
+ if (useCache) {
136
+ const devices = userDevicesCache.get(user)
137
+ if (devices) {
138
+ deviceResults.push(...devices)
139
+ logger.trace({ user }, 'using cache for devices')
140
+ }
141
+ else {
142
+ toFetch.push(jid)
143
+ }
144
+ }
145
+ else {
146
+ toFetch.push(jid)
147
+ }
148
+ }
149
+ if (!toFetch.length) {
150
+ return deviceResults
151
+ }
152
+ const query = new WAUSync_1.USyncQuery()
153
+ .withContext('message')
154
+ .withDeviceProtocol()
155
+ for (const jid of toFetch) {
156
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
157
+ }
158
+ const result = await executeUSyncQuery(query)
159
+ if (result) {
160
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
161
+ const deviceMap = {}
162
+ for (const item of extracted) {
163
+ deviceMap[item.user] = deviceMap[item.user] || []
164
+ deviceMap[item.user].push(item)
165
+ deviceResults.push(item)
166
+ }
167
+ for (const key in deviceMap) {
168
+ userDevicesCache.set(key, deviceMap[key])
169
+ }
170
+ }
171
+ return deviceResults
172
+ }
173
+ const assertSessions = async (jids, force) => {
174
+ let didFetchNewSession = false;
175
+ let jidsRequiringFetch = [];
176
+ if (force) {
177
+ jidsRequiringFetch = jids;
178
+ }
179
+ else {
180
+ const addrs = jids.map(jid => (signalRepository
181
+ .jidToSignalProtocolAddress(jid)));
182
+ const sessions = await authState.keys.get('session', addrs);
183
+ for (const jid of jids) {
184
+ const signalId = signalRepository
185
+ .jidToSignalProtocolAddress(jid);
186
+ if (!sessions[signalId]) {
187
+ jidsRequiringFetch.push(jid);
188
+ }
189
+ }
190
+ }
191
+ if (jidsRequiringFetch.length) {
192
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
193
+ const result = await query({
194
+ tag: 'iq',
195
+ attrs: {
196
+ xmlns: 'encrypt',
197
+ type: 'get',
198
+ to: WABinary_1.S_WHATSAPP_NET,
199
+ },
200
+ content: [
201
+ {
202
+ tag: 'key',
203
+ attrs: {},
204
+ content: jidsRequiringFetch.map(jid => ({
205
+ tag: 'user',
206
+ attrs: { jid },
207
+ }))
208
+ }
209
+ ]
210
+ });
211
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
212
+ didFetchNewSession = true;
213
+ }
214
+ return didFetchNewSession;
215
+ };
216
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
217
+ if (!authState.creds.me?.id) {
218
+ throw new boom_1.Boom('Not authenticated')
219
+ }
220
+ const protocolMessage = {
221
+ protocolMessage: {
222
+ peerDataOperationRequestMessage: pdoMessage,
223
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
224
+ }
225
+ };
226
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
227
+ const msgId = await relayMessage(meJid, protocolMessage, {
228
+ additionalAttributes: {
229
+ category: 'peer',
230
+ push_priority: 'high_force',
231
+ },
232
+ });
233
+ return msgId;
234
+ };
235
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
236
+ const patched = await patchMessageBeforeSending(message, jids);
237
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
238
+ let shouldIncludeDeviceIdentity = false;
239
+ const nodes = await Promise.all(jids.map(async (jid) => {
240
+ const { type, ciphertext } = await signalRepository
241
+ .encryptMessage({ jid, data: bytes });
242
+ if (type === 'pkmsg') {
243
+ shouldIncludeDeviceIdentity = true;
244
+ }
245
+ const node = {
246
+ tag: 'to',
247
+ attrs: { jid },
248
+ content: [{
249
+ tag: 'enc',
250
+ attrs: {
251
+ v: '2',
252
+ type,
253
+ ...extraAttrs || {}
254
+ },
255
+ content: ciphertext
256
+ }]
257
+ };
258
+ return node;
259
+ }));
260
+ return { nodes, shouldIncludeDeviceIdentity };
261
+ };
262
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList, AI = true }) => {
263
+ const meId = authState.creds.me.id;
264
+ let shouldIncludeDeviceIdentity = false;
265
+ let didPushAdditional = false
266
+ const { user, server } = WABinary_1.jidDecode(jid);
267
+ const statusJid = 'status@broadcast';
268
+ const isGroup = server === 'g.us';
269
+ const isStatus = jid === statusJid;
270
+ const isLid = server === 'lid';
271
+ const isPrivate = server === 's.whatsapp.net'
272
+ const isNewsletter = server === 'newsletter';
273
+ msgId = msgId || (0, Utils_1.generateMessageID)();
274
+ useUserDevicesCache = useUserDevicesCache !== false;
275
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
276
+ const participants = [];
277
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
278
+ const binaryNodeContent = [];
279
+ const devices = [];
280
+ const meMsg = {
281
+ deviceSentMessage: {
282
+ destinationJid,
283
+ message
284
+ }
285
+ };
286
+ const extraAttrs = {}
287
+ const messages = Utils_1.normalizeMessageContent(message);
288
+ const buttonType = getButtonType(messages);
289
+ if (participant) {
290
+ if (!isGroup && !isStatus) {
291
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
292
+ }
293
+ const { user, device } = WABinary_1.jidDecode(participant.jid);
294
+ devices.push({ user, device });
295
+ }
296
+ await authState.keys.transaction(async () => {
297
+ const mediaType = getMediaType(messages);
298
+ if (mediaType) {
299
+ extraAttrs['mediatype'] = mediaType
300
+ }
301
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
302
+ extraAttrs['decrypt-fail'] = 'hide'
303
+ }
304
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
305
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
306
+ }
307
+ if (isGroup || isStatus) {
308
+ const [groupData, senderKeyMap] = await Promise.all([
309
+ (async () => {
310
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
311
+ if (groupData) {
312
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
313
+ }
314
+ else if (!isStatus) {
315
+ groupData = await groupMetadata(jid)
316
+ }
317
+ return groupData;
318
+ })(),
319
+ (async () => {
320
+ if (!participant && !isStatus) {
321
+ const result = await authState.keys.get('sender-key-memory', [jid])
322
+ return result[jid] || {}
323
+ }
324
+ return {}
325
+ })()
326
+ ]);
327
+ if (!participant) {
328
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
329
+ if (isStatus && statusJidList) {
330
+ participantsList.push(...statusJidList)
331
+ }
332
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
333
+ devices.push(...additionalDevices)
334
+ }
335
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
336
+ const bytes = Utils_1.encodeWAMessage(patched);
337
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
338
+ group: destinationJid,
339
+ data: bytes,
340
+ meId,
341
+ });
342
+ const senderKeyJids = [];
343
+ for (const { user, device } of devices) {
344
+ const jid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
345
+ if (!senderKeyMap[jid] || !!participant) {
346
+ senderKeyJids.push(jid);
347
+ senderKeyMap[jid] = true;
348
+ }
349
+ }
350
+ if (senderKeyJids.length) {
351
+ logger.debug({ senderKeyJids }, 'sending new sender key');
352
+ const senderKeyMsg = {
353
+ senderKeyDistributionMessage: {
354
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
355
+ groupId: destinationJid
356
+ }
357
+ };
358
+ await assertSessions(senderKeyJids, false);
359
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
360
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
361
+ participants.push(...result.nodes);
362
+ }
363
+ binaryNodeContent.push({
364
+ tag: 'enc',
365
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
366
+ content: ciphertext
367
+ });
368
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
369
+ }
370
+ else if (isNewsletter) {
371
+ if (message.protocolMessage?.editedMessage) {
372
+ msgId = message.protocolMessage.key?.id
373
+ message = message.protocolMessage.editedMessage
374
+ }
375
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
376
+ msgId = message.protocolMessage.key?.id
377
+ message = {}
378
+ }
379
+ const patched = await patchMessageBeforeSending(message, [])
380
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
381
+ binaryNodeContent.push({
382
+ tag: 'plaintext',
383
+ attrs: extraAttrs ? extraAttrs : {},
384
+ content: bytes
385
+ })
386
+ }
387
+ else {
388
+ const { user: meUser } = WABinary_1.jidDecode(meId);
389
+ if (!participant) {
390
+ devices.push({ user })
391
+ if (user !== meUser) {
392
+ devices.push({ user: meUser })
393
+ }
394
+ if (additionalAttributes?.['category'] !== 'peer') {
395
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
396
+ devices.push(...additionalDevices)
397
+ }
398
+ }
399
+ const allJids = [];
400
+ const meJids = [];
401
+ const otherJids = [];
402
+ for (const { user, device } of devices) {
403
+ const isMe = user === meUser
404
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
405
+ if (isMe) {
406
+ meJids.push(jid)
407
+ }
408
+ else {
409
+ otherJids.push(jid)
410
+ }
411
+ allJids.push(jid)
412
+ }
413
+ await assertSessions(allJids, false);
414
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
415
+ createParticipantNodes(meJids, meMsg, extraAttrs),
416
+ createParticipantNodes(otherJids, message, extraAttrs)
417
+ ])
418
+ participants.push(...meNodes);
419
+ participants.push(...otherNodes);
420
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
421
+ }
422
+ if (participants.length) {
423
+ if (additionalAttributes?.['category'] === 'peer') {
424
+ const peerNode = participants[0]?.content?.[0]
425
+ if (peerNode) {
426
+ binaryNodeContent.push(peerNode)
427
+ }
428
+ }
429
+ else {
430
+ binaryNodeContent.push({
431
+ tag: 'participants',
432
+ attrs: {},
433
+ content: participants
434
+ })
435
+ }
436
+ }
437
+ const stanza = {
438
+ tag: 'message',
439
+ attrs: {
440
+ id: msgId,
441
+ type: getTypeMessage(messages),
442
+ ...(additionalAttributes || {})
443
+ },
444
+ content: binaryNodeContent
445
+ }
446
+ if (participant) {
447
+ if (WABinary_1.isJidGroup(destinationJid)) {
448
+ stanza.attrs.to = destinationJid;
449
+ stanza.attrs.participant = participant.jid;
450
+ }
451
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
452
+ stanza.attrs.to = participant.jid;
453
+ stanza.attrs.recipient = destinationJid;
454
+ }
455
+ else {
456
+ stanza.attrs.to = participant.jid;
457
+ }
458
+ }
459
+ else {
460
+ stanza.attrs.to = destinationJid;
461
+ }
462
+ if (shouldIncludeDeviceIdentity) {
463
+ stanza.content.push({
464
+ tag: 'device-identity',
465
+ attrs: {},
466
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
467
+ });
468
+ logger.debug({ jid }, 'adding device identity');
469
+ }
470
+ if (AI && isPrivate) {
471
+ const botNode = {
472
+ tag: 'bot',
473
+ attrs: {
474
+ biz_bot: '1'
475
+ }
476
+ }
477
+ const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
478
+ if (filteredBizBot) {
479
+ stanza.content.push(...additionalNodes)
480
+ didPushAdditional = true
481
+ }
482
+ else {
483
+ stanza.content.push(botNode)
484
+ }
485
+ }
486
+ if (!isNewsletter && buttonType && !isStatus) {
487
+ const content = WABinary_1.getAdditionalNode(buttonType)
488
+ const filteredNode = WABinary_1.getBinaryNodeFilter(additionalNodes)
489
+ if (filteredNode) {
490
+ didPushAdditional = true
491
+ stanza.content.push(...additionalNodes)
492
+ }
493
+ else {
494
+ stanza.content.push(...content)
495
+ }
496
+ logger.debug({ jid }, 'adding business node')
497
+ }
498
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
499
+ stanza.content.push(...additionalNodes);
500
+ }
501
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
502
+ await sendNode(stanza);
503
+ });
504
+ message = Types_1.WAProto.Message.fromObject(message)
505
+ const messageJSON = {
506
+ key: {
507
+ remoteJid: jid,
508
+ fromMe: true,
509
+ id: msgId
510
+ },
511
+ message: message,
512
+ messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
513
+ messageStubParameters: [],
514
+ participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
515
+ status: Types_1.WAMessageStatus.PENDING
516
+ }
517
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
518
+ };
519
+ const getTypeMessage = (msg) => {
520
+ const message = Utils_1.normalizeMessageContent(msg);
521
+ if (message.reactionMessage) {
522
+ return 'reaction'
523
+ }
524
+ else if (getMediaType(message)) {
525
+ return 'media'
526
+ }
527
+ else {
528
+ return 'text'
529
+ }
530
+ }
531
+ const getMediaType = (message) => {
532
+ if (message.imageMessage) {
533
+ return 'image'
534
+ }
535
+ else if (message.videoMessage) {
536
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
537
+ }
538
+ else if (message.audioMessage) {
539
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
540
+ }
541
+ else if (message.contactMessage) {
542
+ return 'vcard'
543
+ }
544
+ else if (message.documentMessage) {
545
+ return 'document'
546
+ }
547
+ else if (message.contactsArrayMessage) {
548
+ return 'contact_array'
549
+ }
550
+ else if (message.liveLocationMessage) {
551
+ return 'livelocation'
552
+ }
553
+ else if (message.stickerMessage) {
554
+ return 'sticker'
555
+ }
556
+ else if (message.listMessage) {
557
+ return 'list'
558
+ }
559
+ else if (message.listResponseMessage) {
560
+ return 'list_response'
561
+ }
562
+ else if (message.buttonsResponseMessage) {
563
+ return 'buttons_response'
564
+ }
565
+ else if (message.orderMessage) {
566
+ return 'order'
567
+ }
568
+ else if (message.productMessage) {
569
+ return 'product'
570
+ }
571
+ else if (message.interactiveResponseMessage) {
572
+ return 'native_flow_response'
573
+ }
574
+ else if (message.groupInviteMessage) {
575
+ return 'url'
576
+ }
577
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
578
+ return 'productlink'
579
+ }
580
+ }
581
+ const getButtonType = (message) => {
582
+ if (message.listMessage) {
583
+ return 'list'
584
+ }
585
+ else if (message.buttonsMessage) {
586
+ return 'buttons'
587
+ }
588
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
589
+ return 'review_and_pay'
590
+ }
591
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
592
+ return 'review_order'
593
+ }
594
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
595
+ return 'payment_info'
596
+ }
597
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
598
+ return 'payment_status'
599
+ }
600
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
601
+ return 'payment_method'
602
+ }
603
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
604
+ return 'interactive'
605
+ }
606
+ else if (message.interactiveMessage?.nativeFlowMessage) {
607
+ return 'native_flow'
608
+ }
609
+ }
610
+ const getPrivacyTokens = async (jids) => {
611
+ const t = Utils_1.unixTimestampSeconds().toString();
612
+ const result = await query({
613
+ tag: 'iq',
614
+ attrs: {
615
+ to: WABinary_1.S_WHATSAPP_NET,
616
+ type: 'set',
617
+ xmlns: 'privacy'
618
+ },
619
+ content: [
620
+ {
621
+ tag: 'tokens',
622
+ attrs: {},
623
+ content: jids.map(jid => ({
624
+ tag: 'token',
625
+ attrs: {
626
+ jid: WABinary_1.jidNormalizedUser(jid),
627
+ t,
628
+ type: 'trusted_contact'
629
+ }
630
+ }))
631
+ }
632
+ ]
633
+ });
634
+ return result;
635
+ }
636
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
637
+ const rahmi = new kikyy(Utils_1, waUploadToServer, relayMessage, config, sock);
638
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
639
+ return {
640
+ ...sock,
641
+ getPrivacyTokens,
642
+ assertSessions,
643
+ relayMessage,
644
+ sendReceipt,
645
+ sendReceipts,
646
+ rahmi,
647
+ readMessages,
648
+ refreshMediaConn,
649
+ getUSyncDevices,
650
+ createParticipantNodes,
651
+ waUploadToServer,
652
+ sendPeerDataOperationMessage,
653
+ fetchPrivacySettings,
654
+ updateMediaMessage: async (message) => {
655
+ const content = (0, Utils_1.assertMediaContent)(message.message);
656
+ const mediaKey = content.mediaKey;
657
+ const meId = authState.creds.me.id;
658
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
659
+ let error = undefined;
660
+ await Promise.all([
661
+ sendNode(node),
662
+ waitForMsgMediaUpdate(update => {
663
+ const result = update.find(c => c.key.id === message.key.id);
664
+ if (result) {
665
+ if (result.error) {
666
+ error = result.error;
667
+ }
668
+ else {
669
+ try {
670
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
671
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
672
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
673
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
674
+ }
675
+ content.directPath = media.directPath;
676
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
677
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
678
+ }
679
+ catch (err) {
680
+ error = err;
681
+ }
682
+ }
683
+ return true;
684
+ }
685
+ })
686
+ ]);
687
+ if (error) {
688
+ throw error;
689
+ }
690
+ ev.emit('messages.update', [
691
+ {
692
+ key: message.key,
693
+ update: {
694
+ message: message.message
695
+ }
696
+ }
697
+ ]);
698
+ return message;
699
+ },
700
+ setLabelGroup: async (id, text) => {
701
+ await relayMessage(id, {
702
+ protocolMessage: {
703
+ type: 30,
704
+ memberLabel: {
705
+ label: text.slice(0, 30)
706
+ }
707
+ }
708
+ }, {
709
+ additionalNodes: [
710
+ {
711
+ tag: "meta",
712
+ attrs: {
713
+ tag_reason: "user_update",
714
+ appdata: "member_tag"
715
+ },
716
+ content: undefined
717
+ }
718
+ ]
719
+ })
720
+ },
721
+ sendStatusMention: async (content, jids = []) => {
722
+ return await rahmi.sendStatusWhatsApp(content, jids);
723
+ },
724
+ sendMessage: async (jid, content, options = {}) => {
725
+ const userJid = authState.creds.me.id;
726
+ delete options.ephemeralExpiration
727
+ const { filter = false, quoted } = options;
728
+ const getParticipantAttr = () => filter ? { participant: { jid } } : {};
729
+ const messageType = rahmi.detectType(content);
730
+ if (typeof content === 'object' && 'disappearingMessagesInChat' in content &&
731
+ typeof content['disappearingMessagesInChat'] !== 'undefined' && WABinary_1.isJidGroup(jid)) {
732
+ const { disappearingMessagesInChat } = content
733
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
734
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
735
+ disappearingMessagesInChat
736
+ await groupToggleEphemeral(jid, value)
737
+ }
738
+ else {
739
+ let mediaHandle
740
+ if (messageType) {
741
+ switch (messageType) {
742
+ case 'PAYMENT':
743
+ const paymentContent = await rahmi.handlePayment(content, quoted);
744
+ return await relayMessage(jid, paymentContent, {
745
+ messageId: Utils_1.generateMessageID(),
746
+ ...getParticipantAttr()
747
+ });
748
+ case 'PRODUCT':
749
+ const productContent = await rahmi.handleProduct(content, jid, quoted);
750
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
751
+ return await relayMessage(jid, productMsg.message, {
752
+ messageId: productMsg.key.id,
753
+ ...getParticipantAttr()
754
+ });
755
+ case 'INTERACTIVE':
756
+ const interactiveContent = await rahmi.handleInteractive(content, jid, quoted);
757
+ const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
758
+ return await relayMessage(jid, interactiveMsg.message, {
759
+ messageId: interactiveMsg.key.id,
760
+ ...getParticipantAttr()
761
+ });
762
+ case 'ALBUM':
763
+ return await rahmi.handleAlbum(content, jid, quoted)
764
+ case 'EVENT':
765
+ return await rahmi.handleEvent(content, jid, quoted)
766
+ case 'POLL_RESULT':
767
+ return await rahmi.handlePollResult(content, jid, quoted)
768
+ case 'GROUP_STORY':
769
+ return await rahmi.handleGroupStory(content, jid, quoted)
770
+ }
771
+ }
772
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
773
+ logger,
774
+ userJid,
775
+ quoted,
776
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
777
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
778
+ fetchOpts: {
779
+ timeout: 3000,
780
+ ...axiosOptions || {}
781
+ },
782
+ logger,
783
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
784
+ }),
785
+ upload: async (readStream, opts) => {
786
+ const up = await waUploadToServer(readStream, {
787
+ ...opts,
788
+ newsletter: WABinary_1.isJidNewsLetter(jid)
789
+ });
790
+ return up;
791
+ },
792
+ mediaCache: config.mediaCache,
793
+ options: config.options,
794
+ ...options
795
+ });
796
+ const isDeleteMsg = 'delete' in content && !!content.delete;
797
+ const isEditMsg = 'edit' in content && !!content.edit;
798
+ const isAiMsg = 'ai' in content && !!content.ai;
799
+ const additionalAttributes = {};
800
+ const additionalNodes = [];
801
+ if (isDeleteMsg) {
802
+ const fromMe = content.delete?.fromMe;
803
+ const isGroup = WABinary_1.isJidGroup(content.delete?.remoteJid);
804
+ additionalAttributes.edit = (isGroup && !fromMe) || WABinary_1.isJidNewsLetter(jid) ? '8' : '7';
805
+ } else if (isEditMsg) {
806
+ additionalAttributes.edit = WABinary_1.isJidNewsLetter(jid) ? '3' : '1';
807
+ } else if (isAiMsg) {
808
+ additionalNodes.push({
809
+ attrs: {
810
+ biz_bot: '1'
811
+ }, tag: "bot"
812
+ });
813
+ }
814
+ await relayMessage(jid, fullMsg.message, {
815
+ messageId: fullMsg.key.id,
816
+ cachedGroupMetadata: options.cachedGroupMetadata,
817
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
818
+ additionalAttributes,
819
+ statusJidList: options.statusJidList
820
+ });
821
+ if (config.emitOwnEvents) {
822
+ process.nextTick(() => {
823
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
824
+ });
825
+ }
826
+ return fullMsg;
827
+ }
828
+ }
829
+ }
830
+ };
831
+ exports.makeMessagesSocket = makeMessagesSocket;