@d0v3riz/baileys 6.3.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 (147) hide show
  1. package/README.md +956 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +2845 -0
  4. package/WAProto/index.d.ts +32006 -0
  5. package/WAProto/index.js +87184 -0
  6. package/WASignalGroup/GroupProtocol.js +1697 -0
  7. package/WASignalGroup/ciphertext_message.js +16 -0
  8. package/WASignalGroup/group_cipher.js +106 -0
  9. package/WASignalGroup/group_session_builder.js +46 -0
  10. package/WASignalGroup/index.js +5 -0
  11. package/WASignalGroup/keyhelper.js +21 -0
  12. package/WASignalGroup/protobufs.js +3 -0
  13. package/WASignalGroup/readme.md +6 -0
  14. package/WASignalGroup/sender_chain_key.js +50 -0
  15. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  16. package/WASignalGroup/sender_key_message.js +92 -0
  17. package/WASignalGroup/sender_key_name.js +70 -0
  18. package/WASignalGroup/sender_key_record.js +54 -0
  19. package/WASignalGroup/sender_key_state.js +129 -0
  20. package/WASignalGroup/sender_message_key.js +39 -0
  21. package/lib/Defaults/baileys-version.json +3 -0
  22. package/lib/Defaults/index.d.ts +284 -0
  23. package/lib/Defaults/index.js +115 -0
  24. package/lib/Defaults/phonenumber-mcc.json +223 -0
  25. package/lib/Signal/libsignal.d.ts +3 -0
  26. package/lib/Signal/libsignal.js +151 -0
  27. package/lib/Socket/Client/abstract-socket-client.d.ts +16 -0
  28. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  29. package/lib/Socket/Client/index.d.ts +3 -0
  30. package/lib/Socket/Client/index.js +19 -0
  31. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  32. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  33. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  34. package/lib/Socket/Client/web-socket-client.js +62 -0
  35. package/lib/Socket/business.d.ts +124 -0
  36. package/lib/Socket/business.js +259 -0
  37. package/lib/Socket/chats.d.ts +74 -0
  38. package/lib/Socket/chats.js +838 -0
  39. package/lib/Socket/groups.d.ts +105 -0
  40. package/lib/Socket/groups.js +291 -0
  41. package/lib/Socket/index.d.ts +126 -0
  42. package/lib/Socket/index.js +10 -0
  43. package/lib/Socket/messages-recv.d.ts +112 -0
  44. package/lib/Socket/messages-recv.js +641 -0
  45. package/lib/Socket/messages-send.d.ts +110 -0
  46. package/lib/Socket/messages-send.js +648 -0
  47. package/lib/Socket/registration.d.ts +211 -0
  48. package/lib/Socket/registration.js +166 -0
  49. package/lib/Socket/socket.d.ts +42 -0
  50. package/lib/Socket/socket.js +527 -0
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/index.js +10 -0
  53. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  54. package/lib/Store/make-cache-manager-store.js +83 -0
  55. package/lib/Store/make-in-memory-store.d.ts +117 -0
  56. package/lib/Store/make-in-memory-store.js +435 -0
  57. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  58. package/lib/Store/make-ordered-dictionary.js +81 -0
  59. package/lib/Store/object-repository.d.ts +10 -0
  60. package/lib/Store/object-repository.js +27 -0
  61. package/lib/Types/Auth.d.ts +106 -0
  62. package/lib/Types/Auth.js +2 -0
  63. package/lib/Types/Call.d.ts +12 -0
  64. package/lib/Types/Call.js +2 -0
  65. package/lib/Types/Chat.d.ts +102 -0
  66. package/lib/Types/Chat.js +4 -0
  67. package/lib/Types/Contact.d.ts +18 -0
  68. package/lib/Types/Contact.js +2 -0
  69. package/lib/Types/Events.d.ts +152 -0
  70. package/lib/Types/Events.js +2 -0
  71. package/lib/Types/GroupMetadata.d.ts +42 -0
  72. package/lib/Types/GroupMetadata.js +2 -0
  73. package/lib/Types/Label.d.ts +35 -0
  74. package/lib/Types/Label.js +27 -0
  75. package/lib/Types/LabelAssociation.d.ts +29 -0
  76. package/lib/Types/LabelAssociation.js +9 -0
  77. package/lib/Types/Message.d.ts +245 -0
  78. package/lib/Types/Message.js +9 -0
  79. package/lib/Types/Product.d.ts +78 -0
  80. package/lib/Types/Product.js +2 -0
  81. package/lib/Types/Signal.d.ts +57 -0
  82. package/lib/Types/Signal.js +2 -0
  83. package/lib/Types/Socket.d.ts +106 -0
  84. package/lib/Types/Socket.js +2 -0
  85. package/lib/Types/State.d.ts +27 -0
  86. package/lib/Types/State.js +2 -0
  87. package/lib/Types/index.d.ts +54 -0
  88. package/lib/Types/index.js +39 -0
  89. package/lib/Utils/auth-utils.d.ts +18 -0
  90. package/lib/Utils/auth-utils.js +202 -0
  91. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  92. package/lib/Utils/baileys-event-stream.js +63 -0
  93. package/lib/Utils/business.d.ts +22 -0
  94. package/lib/Utils/business.js +234 -0
  95. package/lib/Utils/chat-utils.d.ts +71 -0
  96. package/lib/Utils/chat-utils.js +710 -0
  97. package/lib/Utils/crypto.d.ts +38 -0
  98. package/lib/Utils/crypto.js +137 -0
  99. package/lib/Utils/decode-wa-message.d.ts +19 -0
  100. package/lib/Utils/decode-wa-message.js +160 -0
  101. package/lib/Utils/event-buffer.d.ts +35 -0
  102. package/lib/Utils/event-buffer.js +514 -0
  103. package/lib/Utils/generics.d.ts +92 -0
  104. package/lib/Utils/generics.js +368 -0
  105. package/lib/Utils/history.d.ts +15 -0
  106. package/lib/Utils/history.js +91 -0
  107. package/lib/Utils/index.d.ts +17 -0
  108. package/lib/Utils/index.js +33 -0
  109. package/lib/Utils/link-preview.d.ts +21 -0
  110. package/lib/Utils/link-preview.js +116 -0
  111. package/lib/Utils/logger.d.ts +4 -0
  112. package/lib/Utils/logger.js +7 -0
  113. package/lib/Utils/lt-hash.d.ts +12 -0
  114. package/lib/Utils/lt-hash.js +51 -0
  115. package/lib/Utils/make-mutex.d.ts +7 -0
  116. package/lib/Utils/make-mutex.js +43 -0
  117. package/lib/Utils/messages-media.d.ts +101 -0
  118. package/lib/Utils/messages-media.js +632 -0
  119. package/lib/Utils/messages.d.ts +75 -0
  120. package/lib/Utils/messages.js +738 -0
  121. package/lib/Utils/noise-handler.d.ts +20 -0
  122. package/lib/Utils/noise-handler.js +142 -0
  123. package/lib/Utils/process-message.d.ts +41 -0
  124. package/lib/Utils/process-message.js +297 -0
  125. package/lib/Utils/signal.d.ts +32 -0
  126. package/lib/Utils/signal.js +151 -0
  127. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  128. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  129. package/lib/Utils/validate-connection.d.ts +11 -0
  130. package/lib/Utils/validate-connection.js +188 -0
  131. package/lib/WABinary/constants.d.ts +27 -0
  132. package/lib/WABinary/constants.js +40 -0
  133. package/lib/WABinary/decode.d.ts +7 -0
  134. package/lib/WABinary/decode.js +252 -0
  135. package/lib/WABinary/encode.d.ts +3 -0
  136. package/lib/WABinary/encode.js +228 -0
  137. package/lib/WABinary/generic-utils.d.ts +15 -0
  138. package/lib/WABinary/generic-utils.js +110 -0
  139. package/lib/WABinary/index.d.ts +5 -0
  140. package/lib/WABinary/index.js +21 -0
  141. package/lib/WABinary/jid-utils.d.ts +27 -0
  142. package/lib/WABinary/jid-utils.js +56 -0
  143. package/lib/WABinary/types.d.ts +18 -0
  144. package/lib/WABinary/types.js +2 -0
  145. package/lib/index.d.ts +9 -0
  146. package/lib/index.js +27 -0
  147. package/package.json +100 -0
@@ -0,0 +1,648 @@
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 Utils_1 = require("../Utils");
12
+ const link_preview_1 = require("../Utils/link-preview");
13
+ const WABinary_1 = require("../WABinary");
14
+ const groups_1 = require("./groups");
15
+ var ListType = WAProto_1.proto.Message.ListMessage.ListType;
16
+ const makeMessagesSocket = (config) => {
17
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, } = config;
18
+ const sock = (0, groups_1.makeGroupsSocket)(config);
19
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupToggleEphemeral } = sock;
20
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
22
+ useClones: false
23
+ });
24
+ let mediaConn;
25
+ const refreshMediaConn = async (forceGet = false) => {
26
+ const media = await mediaConn;
27
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
28
+ mediaConn = (async () => {
29
+ const result = await query({
30
+ tag: 'iq',
31
+ attrs: {
32
+ type: 'set',
33
+ xmlns: 'w:m',
34
+ to: WABinary_1.S_WHATSAPP_NET,
35
+ },
36
+ content: [{ tag: 'media_conn', attrs: {} }]
37
+ });
38
+ const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
39
+ const node = {
40
+ hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
41
+ hostname: attrs.hostname,
42
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
43
+ })),
44
+ auth: mediaConnNode.attrs.auth,
45
+ ttl: +mediaConnNode.attrs.ttl,
46
+ fetchDate: new Date()
47
+ };
48
+ logger.debug('fetched media conn');
49
+ return node;
50
+ })();
51
+ }
52
+ return mediaConn;
53
+ };
54
+ /**
55
+ * generic send receipt function
56
+ * used for receipts of phone call, read, delivery etc.
57
+ * */
58
+ const sendReceipt = async (jid, participant, messageIds, type) => {
59
+ const node = {
60
+ tag: 'receipt',
61
+ attrs: {
62
+ id: messageIds[0],
63
+ },
64
+ };
65
+ const isReadReceipt = type === 'read' || type === 'read-self';
66
+ if (isReadReceipt) {
67
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
68
+ }
69
+ if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
70
+ node.attrs.recipient = jid;
71
+ node.attrs.to = participant;
72
+ }
73
+ else {
74
+ node.attrs.to = jid;
75
+ if (participant) {
76
+ node.attrs.participant = participant;
77
+ }
78
+ }
79
+ if (type) {
80
+ node.attrs.type = type;
81
+ }
82
+ const remainingMessageIds = messageIds.slice(1);
83
+ if (remainingMessageIds.length) {
84
+ node.content = [
85
+ {
86
+ tag: 'list',
87
+ attrs: {},
88
+ content: remainingMessageIds.map(id => ({
89
+ tag: 'item',
90
+ attrs: { id }
91
+ }))
92
+ }
93
+ ];
94
+ }
95
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
96
+ await sendNode(node);
97
+ };
98
+ /** Correctly bulk send receipts to multiple chats, participants */
99
+ const sendReceipts = async (keys, type) => {
100
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
101
+ for (const { jid, participant, messageIds } of recps) {
102
+ await sendReceipt(jid, participant, messageIds, type);
103
+ }
104
+ };
105
+ /** Bulk read messages. Keys can be from different chats & participants */
106
+ const readMessages = async (keys) => {
107
+ const privacySettings = await fetchPrivacySettings();
108
+ // based on privacy settings, we have to change the read type
109
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
110
+ await sendReceipts(keys, readType);
111
+ };
112
+ /** Fetch all the devices we've to send a message to */
113
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
114
+ var _a;
115
+ const deviceResults = [];
116
+ if (!useCache) {
117
+ logger.debug('not using cache for devices');
118
+ }
119
+ const users = [];
120
+ jids = Array.from(new Set(jids));
121
+ for (let jid of jids) {
122
+ const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
123
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
124
+ const devices = userDevicesCache.get(user);
125
+ if (devices && useCache) {
126
+ deviceResults.push(...devices);
127
+ logger.trace({ user }, 'using cache for devices');
128
+ }
129
+ else {
130
+ users.push({ tag: 'user', attrs: { jid } });
131
+ }
132
+ }
133
+ const iq = {
134
+ tag: 'iq',
135
+ attrs: {
136
+ to: WABinary_1.S_WHATSAPP_NET,
137
+ type: 'get',
138
+ xmlns: 'usync',
139
+ },
140
+ content: [
141
+ {
142
+ tag: 'usync',
143
+ attrs: {
144
+ sid: generateMessageTag(),
145
+ mode: 'query',
146
+ last: 'true',
147
+ index: '0',
148
+ context: 'message',
149
+ },
150
+ content: [
151
+ {
152
+ tag: 'query',
153
+ attrs: {},
154
+ content: [
155
+ {
156
+ tag: 'devices',
157
+ attrs: { version: '2' }
158
+ }
159
+ ]
160
+ },
161
+ { tag: 'list', attrs: {}, content: users }
162
+ ]
163
+ },
164
+ ],
165
+ };
166
+ const result = await query(iq);
167
+ const extracted = (0, Utils_1.extractDeviceJids)(result, authState.creds.me.id, ignoreZeroDevices);
168
+ const deviceMap = {};
169
+ for (const item of extracted) {
170
+ deviceMap[item.user] = deviceMap[item.user] || [];
171
+ deviceMap[item.user].push(item);
172
+ deviceResults.push(item);
173
+ }
174
+ for (const key in deviceMap) {
175
+ userDevicesCache.set(key, deviceMap[key]);
176
+ }
177
+ return deviceResults;
178
+ };
179
+ const assertSessions = async (jids, force) => {
180
+ let didFetchNewSession = false;
181
+ let jidsRequiringFetch = [];
182
+ if (force) {
183
+ jidsRequiringFetch = jids;
184
+ }
185
+ else {
186
+ const addrs = jids.map(jid => (signalRepository
187
+ .jidToSignalProtocolAddress(jid)));
188
+ const sessions = await authState.keys.get('session', addrs);
189
+ for (const jid of jids) {
190
+ const signalId = signalRepository
191
+ .jidToSignalProtocolAddress(jid);
192
+ if (!sessions[signalId]) {
193
+ jidsRequiringFetch.push(jid);
194
+ }
195
+ }
196
+ }
197
+ if (jidsRequiringFetch.length) {
198
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
199
+ const result = await query({
200
+ tag: 'iq',
201
+ attrs: {
202
+ xmlns: 'encrypt',
203
+ type: 'get',
204
+ to: WABinary_1.S_WHATSAPP_NET,
205
+ },
206
+ content: [
207
+ {
208
+ tag: 'key',
209
+ attrs: {},
210
+ content: jidsRequiringFetch.map(jid => ({
211
+ tag: 'user',
212
+ attrs: { jid },
213
+ }))
214
+ }
215
+ ]
216
+ });
217
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
218
+ didFetchNewSession = true;
219
+ }
220
+ return didFetchNewSession;
221
+ };
222
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
223
+ const patched = await patchMessageBeforeSending(message, jids);
224
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
225
+ let shouldIncludeDeviceIdentity = false;
226
+ const nodes = await Promise.all(jids.map(async (jid) => {
227
+ const { type, ciphertext } = await signalRepository
228
+ .encryptMessage({ jid, data: bytes });
229
+ if (type === 'pkmsg') {
230
+ shouldIncludeDeviceIdentity = true;
231
+ }
232
+ const node = {
233
+ tag: 'to',
234
+ attrs: { jid },
235
+ content: [{
236
+ tag: 'enc',
237
+ attrs: {
238
+ v: '2',
239
+ type,
240
+ ...extraAttrs || {}
241
+ },
242
+ content: ciphertext
243
+ }]
244
+ };
245
+ return node;
246
+ }));
247
+ return { nodes, shouldIncludeDeviceIdentity };
248
+ };
249
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, useUserDevicesCache, cachedGroupMetadata }) => {
250
+ const meId = authState.creds.me.id;
251
+ let shouldIncludeDeviceIdentity = false;
252
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
253
+ const isGroup = server === 'g.us';
254
+ msgId = msgId || (0, Utils_1.generateMessageID)();
255
+ useUserDevicesCache = useUserDevicesCache !== false;
256
+ const participants = [];
257
+ const destinationJid = (0, WABinary_1.jidEncode)(user, isGroup ? 'g.us' : 's.whatsapp.net');
258
+ const binaryNodeContent = [];
259
+ const devices = [];
260
+ const meMsg = {
261
+ deviceSentMessage: {
262
+ destinationJid,
263
+ message
264
+ }
265
+ };
266
+ if (participant) {
267
+ // when the retry request is not for a group
268
+ // only send to the specific device that asked for a retry
269
+ // otherwise the message is sent out to every device that should be a recipient
270
+ if (!isGroup) {
271
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
272
+ }
273
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
274
+ devices.push({ user, device });
275
+ }
276
+ await authState.keys.transaction(async () => {
277
+ const mediaType = getMediaType(message);
278
+ if (isGroup) {
279
+ const [groupData, senderKeyMap] = await Promise.all([
280
+ (async () => {
281
+ let groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
282
+ if (groupData) {
283
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
284
+ }
285
+ if (!groupData) {
286
+ groupData = await groupMetadata(jid);
287
+ }
288
+ return groupData;
289
+ })(),
290
+ (async () => {
291
+ if (!participant) {
292
+ const result = await authState.keys.get('sender-key-memory', [jid]);
293
+ return result[jid] || {};
294
+ }
295
+ return {};
296
+ })()
297
+ ]);
298
+ if (!participant) {
299
+ const participantsList = groupData.participants.map(p => p.id);
300
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
301
+ devices.push(...additionalDevices);
302
+ }
303
+ const patched = await patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, 's.whatsapp.net', d.device)));
304
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
305
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
306
+ group: destinationJid,
307
+ data: bytes,
308
+ meId,
309
+ });
310
+ const senderKeyJids = [];
311
+ // ensure a connection is established with every device
312
+ for (const { user, device } of devices) {
313
+ const jid = (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device);
314
+ if (!senderKeyMap[jid] || !!participant) {
315
+ senderKeyJids.push(jid);
316
+ // store that this person has had the sender keys sent to them
317
+ senderKeyMap[jid] = true;
318
+ }
319
+ }
320
+ // if there are some participants with whom the session has not been established
321
+ // if there are, we re-send the senderkey
322
+ if (senderKeyJids.length) {
323
+ logger.debug({ senderKeyJids }, 'sending new sender key');
324
+ const senderKeyMsg = {
325
+ senderKeyDistributionMessage: {
326
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
327
+ groupId: destinationJid
328
+ }
329
+ };
330
+ await assertSessions(senderKeyJids, false);
331
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { mediatype: mediaType } : undefined);
332
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
333
+ participants.push(...result.nodes);
334
+ }
335
+ binaryNodeContent.push({
336
+ tag: 'enc',
337
+ attrs: { v: '2', type: 'skmsg' },
338
+ content: ciphertext
339
+ });
340
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
341
+ }
342
+ else {
343
+ const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
344
+ if (!participant) {
345
+ devices.push({ user });
346
+ devices.push({ user: meUser });
347
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
348
+ devices.push(...additionalDevices);
349
+ }
350
+ const allJids = [];
351
+ const meJids = [];
352
+ const otherJids = [];
353
+ for (const { user, device } of devices) {
354
+ const jid = (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device);
355
+ const isMe = user === meUser;
356
+ if (isMe) {
357
+ meJids.push(jid);
358
+ }
359
+ else {
360
+ otherJids.push(jid);
361
+ }
362
+ allJids.push(jid);
363
+ }
364
+ await assertSessions(allJids, false);
365
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
366
+ createParticipantNodes(meJids, meMsg, mediaType ? { mediatype: mediaType } : undefined),
367
+ createParticipantNodes(otherJids, message, mediaType ? { mediatype: mediaType } : undefined)
368
+ ]);
369
+ participants.push(...meNodes);
370
+ participants.push(...otherNodes);
371
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
372
+ }
373
+ if (participants.length) {
374
+ binaryNodeContent.push({
375
+ tag: 'participants',
376
+ attrs: {},
377
+ content: participants
378
+ });
379
+ }
380
+ const stanza = {
381
+ tag: 'message',
382
+ attrs: {
383
+ id: msgId,
384
+ type: 'text',
385
+ ...(additionalAttributes || {})
386
+ },
387
+ content: binaryNodeContent
388
+ };
389
+ // if the participant to send to is explicitly specified (generally retry recp)
390
+ // ensure the message is only sent to that person
391
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
392
+ if (participant) {
393
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
394
+ stanza.attrs.to = destinationJid;
395
+ stanza.attrs.participant = participant.jid;
396
+ }
397
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
398
+ stanza.attrs.to = participant.jid;
399
+ stanza.attrs.recipient = destinationJid;
400
+ }
401
+ else {
402
+ stanza.attrs.to = participant.jid;
403
+ }
404
+ }
405
+ else {
406
+ stanza.attrs.to = destinationJid;
407
+ }
408
+ if (shouldIncludeDeviceIdentity) {
409
+ stanza.content.push({
410
+ tag: 'device-identity',
411
+ attrs: {},
412
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
413
+ });
414
+ logger.debug({ jid }, 'adding device identity');
415
+ }
416
+ const buttonType = getButtonType(message);
417
+ if (buttonType) {
418
+ stanza.content.push({
419
+ tag: 'biz',
420
+ attrs: {},
421
+ content: [
422
+ {
423
+ tag: buttonType,
424
+ attrs: getButtonArgs(message),
425
+ }
426
+ ]
427
+ });
428
+ logger.debug({ jid }, 'adding business node');
429
+ }
430
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
431
+ await sendNode(stanza);
432
+ });
433
+ return msgId;
434
+ };
435
+ const getMediaType = (message) => {
436
+ if (message.imageMessage) {
437
+ return 'image';
438
+ }
439
+ else if (message.videoMessage) {
440
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
441
+ }
442
+ else if (message.audioMessage) {
443
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
444
+ }
445
+ else if (message.contactMessage) {
446
+ return 'vcard';
447
+ }
448
+ else if (message.documentMessage) {
449
+ return 'document';
450
+ }
451
+ else if (message.contactsArrayMessage) {
452
+ return 'contact_array';
453
+ }
454
+ else if (message.liveLocationMessage) {
455
+ return 'livelocation';
456
+ }
457
+ else if (message.stickerMessage) {
458
+ return 'sticker';
459
+ }
460
+ else if (message.listMessage) {
461
+ return 'list';
462
+ }
463
+ else if (message.listResponseMessage) {
464
+ return 'list_response';
465
+ }
466
+ else if (message.buttonsResponseMessage) {
467
+ return 'buttons_response';
468
+ }
469
+ else if (message.orderMessage) {
470
+ return 'order';
471
+ }
472
+ else if (message.productMessage) {
473
+ return 'product';
474
+ }
475
+ else if (message.interactiveResponseMessage) {
476
+ return 'native_flow_response';
477
+ }
478
+ };
479
+ const getButtonType = (message) => {
480
+ if (message.buttonsMessage) {
481
+ return 'buttons';
482
+ }
483
+ else if (message.buttonsResponseMessage) {
484
+ return 'buttons_response';
485
+ }
486
+ else if (message.interactiveResponseMessage) {
487
+ return 'interactive_response';
488
+ }
489
+ else if (message.listMessage) {
490
+ return 'list';
491
+ }
492
+ else if (message.listResponseMessage) {
493
+ return 'list_response';
494
+ }
495
+ };
496
+ const getButtonArgs = (message) => {
497
+ if (message.templateMessage) {
498
+ // TODO: Add attributes
499
+ return {};
500
+ }
501
+ else if (message.listMessage) {
502
+ const type = message.listMessage.listType;
503
+ if (!type) {
504
+ throw new boom_1.Boom('Expected list type inside message');
505
+ }
506
+ return { v: '2', type: ListType[type].toLowerCase() };
507
+ }
508
+ else {
509
+ return {};
510
+ }
511
+ };
512
+ const getPrivacyTokens = async (jids) => {
513
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
514
+ const result = await query({
515
+ tag: 'iq',
516
+ attrs: {
517
+ to: WABinary_1.S_WHATSAPP_NET,
518
+ type: 'set',
519
+ xmlns: 'privacy'
520
+ },
521
+ content: [
522
+ {
523
+ tag: 'tokens',
524
+ attrs: {},
525
+ content: jids.map(jid => ({
526
+ tag: 'token',
527
+ attrs: {
528
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
529
+ t,
530
+ type: 'trusted_contact'
531
+ }
532
+ }))
533
+ }
534
+ ]
535
+ });
536
+ return result;
537
+ };
538
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
539
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
540
+ return {
541
+ ...sock,
542
+ getPrivacyTokens,
543
+ assertSessions,
544
+ relayMessage,
545
+ sendReceipt,
546
+ sendReceipts,
547
+ readMessages,
548
+ refreshMediaConn,
549
+ waUploadToServer,
550
+ fetchPrivacySettings,
551
+ updateMediaMessage: async (message) => {
552
+ const content = (0, Utils_1.assertMediaContent)(message.message);
553
+ const mediaKey = content.mediaKey;
554
+ const meId = authState.creds.me.id;
555
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
556
+ let error = undefined;
557
+ await Promise.all([
558
+ sendNode(node),
559
+ waitForMsgMediaUpdate(update => {
560
+ const result = update.find(c => c.key.id === message.key.id);
561
+ if (result) {
562
+ if (result.error) {
563
+ error = result.error;
564
+ }
565
+ else {
566
+ try {
567
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
568
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
569
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
570
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
571
+ }
572
+ content.directPath = media.directPath;
573
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
574
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
575
+ }
576
+ catch (err) {
577
+ error = err;
578
+ }
579
+ }
580
+ return true;
581
+ }
582
+ })
583
+ ]);
584
+ if (error) {
585
+ throw error;
586
+ }
587
+ ev.emit('messages.update', [
588
+ { key: message.key, update: { message: message.message } }
589
+ ]);
590
+ return message;
591
+ },
592
+ sendMessage: async (jid, content, options = {}) => {
593
+ var _a, _b;
594
+ const userJid = authState.creds.me.id;
595
+ if (typeof content === 'object' &&
596
+ 'disappearingMessagesInChat' in content &&
597
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
598
+ (0, WABinary_1.isJidGroup)(jid)) {
599
+ const { disappearingMessagesInChat } = content;
600
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
601
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
602
+ disappearingMessagesInChat;
603
+ await groupToggleEphemeral(jid, value);
604
+ }
605
+ else {
606
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
607
+ logger,
608
+ userJid,
609
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
610
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
611
+ fetchOpts: {
612
+ timeout: 3000,
613
+ ...axiosOptions || {}
614
+ },
615
+ logger,
616
+ uploadImage: generateHighQualityLinkPreview
617
+ ? waUploadToServer
618
+ : undefined
619
+ }),
620
+ upload: waUploadToServer,
621
+ mediaCache: config.mediaCache,
622
+ options: config.options,
623
+ ...options,
624
+ });
625
+ const isDeleteMsg = 'delete' in content && !!content.delete;
626
+ const additionalAttributes = {};
627
+ // required for delete
628
+ if (isDeleteMsg) {
629
+ // if the chat is a group, and I am not the author, then delete the message as an admin
630
+ if ((0, WABinary_1.isJidGroup)((_a = content.delete) === null || _a === void 0 ? void 0 : _a.remoteJid) && !((_b = content.delete) === null || _b === void 0 ? void 0 : _b.fromMe)) {
631
+ additionalAttributes.edit = '8';
632
+ }
633
+ else {
634
+ additionalAttributes.edit = '7';
635
+ }
636
+ }
637
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalAttributes });
638
+ if (config.emitOwnEvents) {
639
+ process.nextTick(() => {
640
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
641
+ });
642
+ }
643
+ return fullMsg;
644
+ }
645
+ }
646
+ };
647
+ };
648
+ exports.makeMessagesSocket = makeMessagesSocket;