@queenanya/baileys 7.5.11 → 8.1.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 (157) hide show
  1. package/package.json +13 -97
  2. package/LICENSE +0 -21
  3. package/README.md +0 -931
  4. package/WAProto/GenerateStatics.sh +0 -4
  5. package/WAProto/WAProto.proto +0 -3344
  6. package/WAProto/index.d.ts +0 -37016
  7. package/WAProto/index.js +0 -101044
  8. package/WASignalGroup/GroupProtocol.js +0 -1697
  9. package/WASignalGroup/ciphertext_message.js +0 -16
  10. package/WASignalGroup/group_cipher.js +0 -120
  11. package/WASignalGroup/group_session_builder.js +0 -46
  12. package/WASignalGroup/index.js +0 -5
  13. package/WASignalGroup/keyhelper.js +0 -21
  14. package/WASignalGroup/protobufs.js +0 -3
  15. package/WASignalGroup/queue_job.js +0 -69
  16. package/WASignalGroup/sender_chain_key.js +0 -50
  17. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  18. package/WASignalGroup/sender_key_message.js +0 -92
  19. package/WASignalGroup/sender_key_name.js +0 -70
  20. package/WASignalGroup/sender_key_record.js +0 -56
  21. package/WASignalGroup/sender_key_state.js +0 -129
  22. package/WASignalGroup/sender_message_key.js +0 -39
  23. package/lib/Defaults/baileys-version.json +0 -3
  24. package/lib/Defaults/index.d.ts +0 -53
  25. package/lib/Defaults/index.js +0 -107
  26. package/lib/Signal/libsignal.d.ts +0 -3
  27. package/lib/Signal/libsignal.js +0 -152
  28. package/lib/Socket/Client/index.d.ts +0 -2
  29. package/lib/Socket/Client/index.js +0 -18
  30. package/lib/Socket/Client/types.d.ts +0 -17
  31. package/lib/Socket/Client/types.js +0 -13
  32. package/lib/Socket/Client/websocket.d.ts +0 -12
  33. package/lib/Socket/Client/websocket.js +0 -62
  34. package/lib/Socket/business.d.ts +0 -177
  35. package/lib/Socket/business.js +0 -260
  36. package/lib/Socket/chats.d.ts +0 -91
  37. package/lib/Socket/chats.js +0 -949
  38. package/lib/Socket/groups.d.ts +0 -131
  39. package/lib/Socket/groups.js +0 -314
  40. package/lib/Socket/index.d.ts +0 -177
  41. package/lib/Socket/index.js +0 -10
  42. package/lib/Socket/messages-recv.d.ts +0 -164
  43. package/lib/Socket/messages-recv.js +0 -918
  44. package/lib/Socket/messages-send.d.ts +0 -157
  45. package/lib/Socket/messages-send.js +0 -794
  46. package/lib/Socket/newsletter.d.ts +0 -143
  47. package/lib/Socket/newsletter.js +0 -249
  48. package/lib/Socket/socket.d.ts +0 -45
  49. package/lib/Socket/socket.js +0 -616
  50. package/lib/Store/index.d.ts +0 -3
  51. package/lib/Store/index.js +0 -10
  52. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  53. package/lib/Store/make-cache-manager-store.js +0 -83
  54. package/lib/Store/make-in-memory-store.d.ts +0 -118
  55. package/lib/Store/make-in-memory-store.js +0 -420
  56. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  57. package/lib/Store/make-ordered-dictionary.js +0 -81
  58. package/lib/Store/object-repository.d.ts +0 -10
  59. package/lib/Store/object-repository.js +0 -27
  60. package/lib/Types/Auth.d.ts +0 -105
  61. package/lib/Types/Auth.js +0 -2
  62. package/lib/Types/Call.d.ts +0 -13
  63. package/lib/Types/Call.js +0 -2
  64. package/lib/Types/Chat.d.ts +0 -107
  65. package/lib/Types/Chat.js +0 -4
  66. package/lib/Types/Contact.d.ts +0 -19
  67. package/lib/Types/Contact.js +0 -2
  68. package/lib/Types/Events.d.ts +0 -199
  69. package/lib/Types/Events.js +0 -2
  70. package/lib/Types/GroupMetadata.d.ts +0 -56
  71. package/lib/Types/GroupMetadata.js +0 -2
  72. package/lib/Types/Label.d.ts +0 -46
  73. package/lib/Types/Label.js +0 -27
  74. package/lib/Types/LabelAssociation.d.ts +0 -29
  75. package/lib/Types/LabelAssociation.js +0 -9
  76. package/lib/Types/Message.d.ts +0 -280
  77. package/lib/Types/Message.js +0 -9
  78. package/lib/Types/Newsletter.d.ts +0 -79
  79. package/lib/Types/Newsletter.js +0 -18
  80. package/lib/Types/Product.d.ts +0 -78
  81. package/lib/Types/Product.js +0 -2
  82. package/lib/Types/Signal.d.ts +0 -57
  83. package/lib/Types/Signal.js +0 -2
  84. package/lib/Types/Socket.d.ts +0 -118
  85. package/lib/Types/Socket.js +0 -2
  86. package/lib/Types/State.d.ts +0 -27
  87. package/lib/Types/State.js +0 -2
  88. package/lib/Types/index.d.ts +0 -65
  89. package/lib/Types/index.js +0 -42
  90. package/lib/Utils/auth-utils.d.ts +0 -18
  91. package/lib/Utils/auth-utils.js +0 -200
  92. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  93. package/lib/Utils/baileys-event-stream.js +0 -63
  94. package/lib/Utils/business.d.ts +0 -22
  95. package/lib/Utils/business.js +0 -234
  96. package/lib/Utils/chat-utils.d.ts +0 -72
  97. package/lib/Utils/chat-utils.js +0 -745
  98. package/lib/Utils/crypto.d.ts +0 -42
  99. package/lib/Utils/crypto.js +0 -153
  100. package/lib/Utils/decode-wa-message.d.ts +0 -20
  101. package/lib/Utils/decode-wa-message.js +0 -218
  102. package/lib/Utils/event-buffer.d.ts +0 -35
  103. package/lib/Utils/event-buffer.js +0 -520
  104. package/lib/Utils/generics.d.ts +0 -119
  105. package/lib/Utils/generics.js +0 -467
  106. package/lib/Utils/history.d.ts +0 -19
  107. package/lib/Utils/history.js +0 -94
  108. package/lib/Utils/index.d.ts +0 -18
  109. package/lib/Utils/index.js +0 -34
  110. package/lib/Utils/link-preview.d.ts +0 -21
  111. package/lib/Utils/link-preview.js +0 -116
  112. package/lib/Utils/logger.d.ts +0 -2
  113. package/lib/Utils/logger.js +0 -7
  114. package/lib/Utils/lt-hash.d.ts +0 -12
  115. package/lib/Utils/lt-hash.js +0 -51
  116. package/lib/Utils/make-mutex.d.ts +0 -7
  117. package/lib/Utils/make-mutex.js +0 -44
  118. package/lib/Utils/messages-media.d.ts +0 -131
  119. package/lib/Utils/messages-media.js +0 -786
  120. package/lib/Utils/messages.d.ts +0 -78
  121. package/lib/Utils/messages.js +0 -767
  122. package/lib/Utils/noise-handler.d.ts +0 -21
  123. package/lib/Utils/noise-handler.js +0 -150
  124. package/lib/Utils/process-message.d.ts +0 -42
  125. package/lib/Utils/process-message.js +0 -355
  126. package/lib/Utils/signal.d.ts +0 -32
  127. package/lib/Utils/signal.js +0 -158
  128. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  129. package/lib/Utils/use-multi-file-auth-state.js +0 -94
  130. package/lib/Utils/use-single-file-auth-state.d.ts +0 -5
  131. package/lib/Utils/use-single-file-auth-state.js +0 -66
  132. package/lib/Utils/validate-connection.d.ts +0 -10
  133. package/lib/Utils/validate-connection.js +0 -171
  134. package/lib/WABinary/constants.d.ts +0 -27
  135. package/lib/WABinary/constants.js +0 -40
  136. package/lib/WABinary/decode.d.ts +0 -8
  137. package/lib/WABinary/decode.js +0 -254
  138. package/lib/WABinary/encode.d.ts +0 -2
  139. package/lib/WABinary/encode.js +0 -230
  140. package/lib/WABinary/generic-utils.d.ts +0 -16
  141. package/lib/WABinary/generic-utils.js +0 -110
  142. package/lib/WABinary/index.d.ts +0 -5
  143. package/lib/WABinary/index.js +0 -21
  144. package/lib/WABinary/jid-utils.d.ts +0 -31
  145. package/lib/WABinary/jid-utils.js +0 -62
  146. package/lib/WABinary/types.d.ts +0 -18
  147. package/lib/WABinary/types.js +0 -2
  148. package/lib/WAM/BinaryInfo.d.ts +0 -18
  149. package/lib/WAM/BinaryInfo.js +0 -13
  150. package/lib/WAM/constants.d.ts +0 -39
  151. package/lib/WAM/constants.js +0 -15350
  152. package/lib/WAM/encode.d.ts +0 -4
  153. package/lib/WAM/encode.js +0 -155
  154. package/lib/WAM/index.d.ts +0 -3
  155. package/lib/WAM/index.js +0 -19
  156. package/lib/index.d.ts +0 -11
  157. package/lib/index.js +0 -30
@@ -1,794 +0,0 @@
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 newsletter_1 = require("./newsletter");
15
- var ListType = WAProto_1.proto.Message.ListMessage.ListType;
16
- const makeMessagesSocket = (config) => {
17
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
18
- const sock = (0, newsletter_1.makeNewsletterSocket)(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 = (0, WABinary_1.isJidNewsletter)(jid) ? 'read-self' : 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
- if (!users.length) {
134
- return deviceResults;
135
- }
136
- const iq = {
137
- tag: 'iq',
138
- attrs: {
139
- to: WABinary_1.S_WHATSAPP_NET,
140
- type: 'get',
141
- xmlns: 'usync',
142
- },
143
- content: [
144
- {
145
- tag: 'usync',
146
- attrs: {
147
- sid: generateMessageTag(),
148
- mode: 'query',
149
- last: 'true',
150
- index: '0',
151
- context: 'message',
152
- },
153
- content: [
154
- {
155
- tag: 'query',
156
- attrs: {},
157
- content: [
158
- {
159
- tag: 'devices',
160
- attrs: { version: '2' }
161
- }
162
- ]
163
- },
164
- { tag: 'list', attrs: {}, content: users }
165
- ]
166
- },
167
- ],
168
- };
169
- const result = await query(iq);
170
- const extracted = (0, Utils_1.extractDeviceJids)(result, authState.creds.me.id, ignoreZeroDevices);
171
- const deviceMap = {};
172
- for (const item of extracted) {
173
- deviceMap[item.user] = deviceMap[item.user] || [];
174
- deviceMap[item.user].push(item);
175
- deviceResults.push(item);
176
- }
177
- for (const key in deviceMap) {
178
- userDevicesCache.set(key, deviceMap[key]);
179
- }
180
- return deviceResults;
181
- };
182
- const assertSessions = async (jids, force) => {
183
- let didFetchNewSession = false;
184
- let jidsRequiringFetch = [];
185
- if (force) {
186
- jidsRequiringFetch = jids;
187
- }
188
- else {
189
- const addrs = jids.map(jid => (signalRepository
190
- .jidToSignalProtocolAddress(jid)));
191
- const sessions = await authState.keys.get('session', addrs);
192
- for (const jid of jids) {
193
- const signalId = signalRepository
194
- .jidToSignalProtocolAddress(jid);
195
- if (!sessions[signalId]) {
196
- jidsRequiringFetch.push(jid);
197
- }
198
- }
199
- }
200
- if (jidsRequiringFetch.length) {
201
- logger.debug({ jidsRequiringFetch }, 'fetching sessions');
202
- const result = await query({
203
- tag: 'iq',
204
- attrs: {
205
- xmlns: 'encrypt',
206
- type: 'get',
207
- to: WABinary_1.S_WHATSAPP_NET,
208
- },
209
- content: [
210
- {
211
- tag: 'key',
212
- attrs: {},
213
- content: jidsRequiringFetch.map(jid => ({
214
- tag: 'user',
215
- attrs: { jid },
216
- }))
217
- }
218
- ]
219
- });
220
- await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
221
- didFetchNewSession = true;
222
- }
223
- return didFetchNewSession;
224
- };
225
- const sendPeerDataOperationMessage = async (pdoMessage) => {
226
- var _a;
227
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
228
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
229
- throw new boom_1.Boom('Not authenticated');
230
- }
231
- const protocolMessage = {
232
- protocolMessage: {
233
- peerDataOperationRequestMessage: pdoMessage,
234
- type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
235
- }
236
- };
237
- const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
238
- const msgId = await relayMessage(meJid, protocolMessage, {
239
- additionalAttributes: {
240
- category: 'peer',
241
- // eslint-disable-next-line camelcase
242
- push_priority: 'high_force',
243
- },
244
- });
245
- return msgId;
246
- };
247
- const createParticipantNodes = async (jids, message, extraAttrs) => {
248
- const patched = await patchMessageBeforeSending(message, jids);
249
- const bytes = (0, Utils_1.encodeWAMessage)(patched);
250
- let shouldIncludeDeviceIdentity = false;
251
- const nodes = await Promise.all(jids.map(async (jid) => {
252
- const { type, ciphertext } = await signalRepository
253
- .encryptMessage({ jid, data: bytes });
254
- if (type === 'pkmsg') {
255
- shouldIncludeDeviceIdentity = true;
256
- }
257
- const node = {
258
- tag: 'to',
259
- attrs: { jid },
260
- content: [{
261
- tag: 'enc',
262
- attrs: {
263
- v: '2',
264
- type,
265
- ...extraAttrs || {}
266
- },
267
- content: ciphertext
268
- }]
269
- };
270
- return node;
271
- }));
272
- return { nodes, shouldIncludeDeviceIdentity };
273
- };
274
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
275
- var _a;
276
- const meId = authState.creds.me.id;
277
- let shouldIncludeDeviceIdentity = false;
278
- const { user, server } = (0, WABinary_1.jidDecode)(jid);
279
- const statusJid = 'status@broadcast';
280
- const isGroup = server === 'g.us';
281
- const isNewsletter = server == 'newsletter';
282
- const isStatus = jid === statusJid;
283
- const isLid = server === 'lid';
284
- msgId = msgId || (0, Utils_1.generateMessageIDV3)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
285
- useUserDevicesCache = useUserDevicesCache !== false;
286
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
287
- const participants = [];
288
- const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
289
- const binaryNodeContent = [];
290
- const devices = [];
291
- const meMsg = {
292
- deviceSentMessage: {
293
- destinationJid,
294
- message
295
- }
296
- };
297
- const extraAttrs = {};
298
- if (participant) {
299
- // when the retry request is not for a group
300
- // only send to the specific device that asked for a retry
301
- // otherwise the message is sent out to every device that should be a recipient
302
- if (!isGroup && !isStatus) {
303
- additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
304
- }
305
- const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
306
- devices.push({ user, device });
307
- }
308
- await authState.keys.transaction(async () => {
309
- var _a, _b, _c, _d, _e;
310
- const mediaType = getMediaType(message);
311
- if (mediaType) {
312
- extraAttrs['mediatype'] = mediaType;
313
- }
314
- if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
315
- extraAttrs['decrypt-fail'] = 'hide';
316
- }
317
- if (isGroup || isStatus) {
318
- const [groupData, senderKeyMap] = await Promise.all([
319
- (async () => {
320
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
321
- if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
322
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
323
- }
324
- else if (!isStatus) {
325
- groupData = await groupMetadata(jid);
326
- }
327
- return groupData;
328
- })(),
329
- (async () => {
330
- if (!participant && !isStatus) {
331
- const result = await authState.keys.get('sender-key-memory', [jid]);
332
- return result[jid] || {};
333
- }
334
- return {};
335
- })()
336
- ]);
337
- if (!participant) {
338
- const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
339
- if (isStatus && statusJidList) {
340
- participantsList.push(...statusJidList);
341
- }
342
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
343
- devices.push(...additionalDevices);
344
- }
345
- const patched = await patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
346
- const bytes = (0, Utils_1.encodeWAMessage)(patched);
347
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
348
- group: destinationJid,
349
- data: bytes,
350
- meId,
351
- });
352
- const senderKeyJids = [];
353
- // ensure a connection is established with every device
354
- for (const { user, device } of devices) {
355
- const jid = (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : 's.whatsapp.net', device);
356
- if (!senderKeyMap[jid] || !!participant) {
357
- senderKeyJids.push(jid);
358
- // store that this person has had the sender keys sent to them
359
- senderKeyMap[jid] = true;
360
- }
361
- }
362
- // if there are some participants with whom the session has not been established
363
- // if there are, we re-send the senderkey
364
- if (senderKeyJids.length) {
365
- logger.debug({ senderKeyJids }, 'sending new sender key');
366
- const senderKeyMsg = {
367
- senderKeyDistributionMessage: {
368
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
369
- groupId: destinationJid
370
- }
371
- };
372
- await assertSessions(senderKeyJids, false);
373
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
374
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
375
- participants.push(...result.nodes);
376
- }
377
- binaryNodeContent.push({
378
- tag: 'enc',
379
- attrs: { v: '2', type: 'skmsg' },
380
- content: ciphertext
381
- });
382
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
383
- }
384
- else if (isNewsletter) {
385
- const patched = await patchMessageBeforeSending(message, []);
386
- const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
387
- binaryNodeContent.push({
388
- tag: 'plaintext',
389
- attrs: {},
390
- content: bytes
391
- });
392
- }
393
- else {
394
- const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
395
- if (!participant) {
396
- devices.push({ user });
397
- if (user !== meUser) {
398
- devices.push({ user: meUser });
399
- }
400
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
401
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
402
- devices.push(...additionalDevices);
403
- }
404
- }
405
- const allJids = [];
406
- const meJids = [];
407
- const otherJids = [];
408
- for (const { user, device } of devices) {
409
- const isMe = user === meUser;
410
- const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_c = (_b = authState.creds) === null || _b === void 0 ? void 0 : _b.me) === null || _c === void 0 ? void 0 : _c.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
411
- if (isMe) {
412
- meJids.push(jid);
413
- }
414
- else {
415
- otherJids.push(jid);
416
- }
417
- allJids.push(jid);
418
- }
419
- await assertSessions(allJids, false);
420
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
421
- createParticipantNodes(meJids, meMsg, extraAttrs),
422
- createParticipantNodes(otherJids, message, extraAttrs)
423
- ]);
424
- participants.push(...meNodes);
425
- participants.push(...otherNodes);
426
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
427
- }
428
- if (participants.length) {
429
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
430
- const peerNode = (_e = (_d = participants[0]) === null || _d === void 0 ? void 0 : _d.content) === null || _e === void 0 ? void 0 : _e[0];
431
- if (peerNode) {
432
- binaryNodeContent.push(peerNode); // push only enc
433
- }
434
- }
435
- else {
436
- binaryNodeContent.push({
437
- tag: 'participants',
438
- attrs: {},
439
- content: participants
440
- });
441
- }
442
- }
443
- const stanza = {
444
- tag: 'message',
445
- attrs: {
446
- id: msgId,
447
- type: getMessageType(message),
448
- ...(additionalAttributes || {})
449
- },
450
- content: binaryNodeContent
451
- };
452
- // if the participant to send to is explicitly specified (generally retry recp)
453
- // ensure the message is only sent to that person
454
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
455
- if (participant) {
456
- if ((0, WABinary_1.isJidGroup)(destinationJid)) {
457
- stanza.attrs.to = destinationJid;
458
- stanza.attrs.participant = participant.jid;
459
- }
460
- else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
461
- stanza.attrs.to = participant.jid;
462
- stanza.attrs.recipient = destinationJid;
463
- }
464
- else {
465
- stanza.attrs.to = participant.jid;
466
- }
467
- }
468
- else {
469
- stanza.attrs.to = destinationJid;
470
- }
471
- if (shouldIncludeDeviceIdentity) {
472
- stanza.content.push({
473
- tag: 'device-identity',
474
- attrs: {},
475
- content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
476
- });
477
- logger.debug({ jid }, 'adding device identity');
478
- }
479
- if (additionalNodes && additionalNodes.length > 0) {
480
- stanza.content.push(...additionalNodes);
481
- }
482
- /**
483
- const buttonType = getButtonType(message)
484
- if(buttonType) {
485
- (stanza.content as BinaryNode[]).push({
486
- tag: 'biz',
487
- attrs: { },
488
- content: [
489
- {
490
- tag: buttonType,
491
- attrs: getButtonArgs(message),
492
- }
493
- ]
494
- })
495
-
496
- logger.debug({ jid }, 'adding business node')
497
- }
498
- */
499
- logger.debug({ msgId }, `sending message to ${participants.length} devices`);
500
- await sendNode(stanza);
501
- });
502
- return msgId;
503
- };
504
- const getTypeMessage = (msg) => {
505
- if (msg.viewOnceMessage) {
506
- return getTypeMessage(msg.viewOnceMessage.message);
507
- }
508
- else if (msg.viewOnceMessageV2) {
509
- return getTypeMessage(msg.viewOnceMessageV2.message);
510
- }
511
- else if (msg.viewOnceMessageV2Extension) {
512
- return getTypeMessage(msg.viewOnceMessageV2Extension.message);
513
- }
514
- else if (msg.ephemeralMessage) {
515
- return getTypeMessage(msg.ephemeralMessage.message);
516
- }
517
- else if (msg.documentWithCaptionMessage) {
518
- return getTypeMessage(msg.documentWithCaptionMessage.message);
519
- }
520
- else if (msg.reactionMessage) {
521
- return 'reaction';
522
- }
523
- else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
524
- return 'reaction';
525
- }
526
- else if (getMediaType(msg)) {
527
- return 'media';
528
- }
529
- else {
530
- return 'text';
531
- }
532
- };
533
- const getMessageType = (message) => {
534
- if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
535
- return 'poll';
536
- }
537
- return 'text';
538
- };
539
- const getMediaType = (message) => {
540
- if (message.imageMessage) {
541
- return 'image';
542
- }
543
- else if (message.videoMessage) {
544
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
545
- }
546
- else if (message.audioMessage) {
547
- return message.audioMessage.ptt ? 'ptt' : 'audio';
548
- }
549
- else if (message.contactMessage) {
550
- return 'vcard';
551
- }
552
- else if (message.documentMessage) {
553
- return 'document';
554
- }
555
- else if (message.contactsArrayMessage) {
556
- return 'contact_array';
557
- }
558
- else if (message.liveLocationMessage) {
559
- return 'livelocation';
560
- }
561
- else if (message.stickerMessage) {
562
- return 'sticker';
563
- }
564
- else if (message.listMessage) {
565
- return 'list';
566
- }
567
- else if (message.listResponseMessage) {
568
- return 'list_response';
569
- }
570
- else if (message.buttonsResponseMessage) {
571
- return 'buttons_response';
572
- }
573
- else if (message.orderMessage) {
574
- return 'order';
575
- }
576
- else if (message.productMessage) {
577
- return 'product';
578
- }
579
- else if (message.interactiveResponseMessage) {
580
- return 'native_flow_response';
581
- }
582
- else if (message.groupInviteMessage) {
583
- return 'url';
584
- }
585
- };
586
- const getButtonType = (message) => {
587
- if (message.buttonsMessage) {
588
- return 'buttons';
589
- }
590
- else if (message.buttonsResponseMessage) {
591
- return 'buttons_response';
592
- }
593
- else if (message.interactiveResponseMessage) {
594
- return 'interactive_response';
595
- }
596
- else if (message.listMessage) {
597
- return 'list';
598
- }
599
- else if (message.listResponseMessage) {
600
- return 'list_response';
601
- }
602
- };
603
- const getButtonArgs = (message) => {
604
- if (message.templateMessage) {
605
- // TODO: Add attributes
606
- return {};
607
- }
608
- else if (message.listMessage) {
609
- const type = message.listMessage.listType;
610
- if (!type) {
611
- throw new boom_1.Boom('Expected list type inside message');
612
- }
613
- return { v: '2', type: ListType[type].toLowerCase() };
614
- }
615
- else {
616
- return {};
617
- }
618
- };
619
- const getPrivacyTokens = async (jids) => {
620
- const t = (0, Utils_1.unixTimestampSeconds)().toString();
621
- const result = await query({
622
- tag: 'iq',
623
- attrs: {
624
- to: WABinary_1.S_WHATSAPP_NET,
625
- type: 'set',
626
- xmlns: 'privacy'
627
- },
628
- content: [
629
- {
630
- tag: 'tokens',
631
- attrs: {},
632
- content: jids.map(jid => ({
633
- tag: 'token',
634
- attrs: {
635
- jid: (0, WABinary_1.jidNormalizedUser)(jid),
636
- t,
637
- type: 'trusted_contact'
638
- }
639
- }))
640
- }
641
- ]
642
- });
643
- return result;
644
- };
645
- const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
646
- const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
647
- return {
648
- ...sock,
649
- getPrivacyTokens,
650
- assertSessions,
651
- relayMessage,
652
- sendReceipt,
653
- sendReceipts,
654
- // getButtonArgs,
655
- readMessages,
656
- refreshMediaConn,
657
- waUploadToServer,
658
- fetchPrivacySettings,
659
- sendPeerDataOperationMessage,
660
- createParticipantNodes,
661
- getUSyncDevices,
662
- updateMediaMessage: async (message) => {
663
- const content = (0, Utils_1.assertMediaContent)(message.message);
664
- const mediaKey = content.mediaKey;
665
- const meId = authState.creds.me.id;
666
- const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
667
- let error = undefined;
668
- await Promise.all([
669
- sendNode(node),
670
- waitForMsgMediaUpdate(update => {
671
- const result = update.find(c => c.key.id === message.key.id);
672
- if (result) {
673
- if (result.error) {
674
- error = result.error;
675
- }
676
- else {
677
- try {
678
- const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
679
- if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
680
- const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
681
- throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
682
- }
683
- content.directPath = media.directPath;
684
- content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
685
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
686
- }
687
- catch (err) {
688
- error = err;
689
- }
690
- }
691
- return true;
692
- }
693
- })
694
- ]);
695
- if (error) {
696
- throw error;
697
- }
698
- ev.emit('messages.update', [
699
- { key: message.key, update: { message: message.message } }
700
- ]);
701
- return message;
702
- },
703
- sendMessage: async (jid, content, options = {}) => {
704
- var _a, _b, _c;
705
- const userJid = authState.creds.me.id;
706
- if (typeof content === 'object' &&
707
- 'disappearingMessagesInChat' in content &&
708
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
709
- (0, WABinary_1.isJidGroup)(jid)) {
710
- const { disappearingMessagesInChat } = content;
711
- const value = typeof disappearingMessagesInChat === 'boolean' ?
712
- (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
713
- disappearingMessagesInChat;
714
- await groupToggleEphemeral(jid, value);
715
- }
716
- else {
717
- let mediaHandle;
718
- const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
719
- logger,
720
- userJid,
721
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
722
- thumbnailWidth: linkPreviewImageThumbnailWidth,
723
- fetchOpts: {
724
- timeout: 3000,
725
- ...axiosOptions || {}
726
- },
727
- logger,
728
- uploadImage: generateHighQualityLinkPreview
729
- ? waUploadToServer
730
- : undefined
731
- }),
732
- //TODO: CACHE
733
- getProfilePicUrl: sock.profilePictureUrl,
734
- upload: async (readStream, opts) => {
735
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
736
- mediaHandle = up.handle;
737
- return up;
738
- },
739
- /**
740
- upload: waUploadToServer,
741
- */
742
- mediaCache: config.mediaCache,
743
- options: config.options,
744
- messageId: (0, Utils_1.generateMessageIDV3)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id),
745
- ...options,
746
- });
747
- const isDeleteMsg = 'delete' in content && !!content.delete;
748
- const isEditMsg = 'edit' in content && !!content.edit;
749
- const isPinMsg = 'pin' in content && !!content.pin;
750
- const isPollMessage = 'poll' in content && !!content.poll;
751
- const additionalAttributes = {};
752
- const additionalNodes = [];
753
- // required for delete
754
- if (isDeleteMsg) {
755
- // if the chat is a group, and I am not the author, then delete the message as an admin
756
- if (((0, WABinary_1.isJidGroup)((_b = content.delete) === null || _b === void 0 ? void 0 : _b.remoteJid) && !((_c = content.delete) === null || _c === void 0 ? void 0 : _c.fromMe)) || (0, WABinary_1.isJidNewsletter)(jid)) {
757
- additionalAttributes.edit = '8';
758
- }
759
- else {
760
- additionalAttributes.edit = '7';
761
- }
762
- }
763
- else if (isEditMsg) {
764
- additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
765
- }
766
- else if (isPinMsg) {
767
- additionalAttributes.edit = '2';
768
- }
769
- else if (isPollMessage) {
770
- additionalNodes.push({
771
- tag: 'meta',
772
- attrs: {
773
- polltype: 'creation'
774
- },
775
- });
776
- }
777
- if (mediaHandle) {
778
- additionalAttributes['media_id'] = mediaHandle;
779
- }
780
- if ('cachedGroupMetadata' in options) {
781
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
782
- }
783
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes });
784
- if (config.emitOwnEvents) {
785
- process.nextTick(() => {
786
- processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
787
- });
788
- }
789
- return fullMsg;
790
- }
791
- }
792
- };
793
- };
794
- exports.makeMessagesSocket = makeMessagesSocket;