keith-baileys 1.0.26

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