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