ndikzv1 26.0.12

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 (179) hide show
  1. package/WAProto/index.d.ts +55057 -0
  2. package/WAProto/index.js +169661 -0
  3. package/WASignalGroup/GroupProtocol.js +1697 -0
  4. package/WASignalGroup/ciphertext_message.js +16 -0
  5. package/WASignalGroup/group_cipher.js +120 -0
  6. package/WASignalGroup/group_session_builder.js +46 -0
  7. package/WASignalGroup/index.js +5 -0
  8. package/WASignalGroup/keyhelper.js +21 -0
  9. package/WASignalGroup/protobufs.js +3 -0
  10. package/WASignalGroup/queue_job.js +69 -0
  11. package/WASignalGroup/sender_chain_key.js +50 -0
  12. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  13. package/WASignalGroup/sender_key_message.js +92 -0
  14. package/WASignalGroup/sender_key_name.js +70 -0
  15. package/WASignalGroup/sender_key_record.js +56 -0
  16. package/WASignalGroup/sender_key_state.js +129 -0
  17. package/WASignalGroup/sender_message_key.js +39 -0
  18. package/engine-requirements.js +10 -0
  19. package/lib/Defaults/baileys-version.json +3 -0
  20. package/lib/Defaults/index.d.ts +282 -0
  21. package/lib/Defaults/index.js +122 -0
  22. package/lib/Defaults/phonenumber-mcc.json +223 -0
  23. package/lib/Signal/libsignal.d.ts +3 -0
  24. package/lib/Signal/libsignal.js +161 -0
  25. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  26. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  27. package/lib/Socket/Client/index.d.ts +3 -0
  28. package/lib/Socket/Client/index.js +19 -0
  29. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  30. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  31. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  32. package/lib/Socket/Client/web-socket-client.js +62 -0
  33. package/lib/Socket/business.d.ts +172 -0
  34. package/lib/Socket/business.js +260 -0
  35. package/lib/Socket/chats.d.ts +83 -0
  36. package/lib/Socket/chats.js +871 -0
  37. package/lib/Socket/groups.d.ts +124 -0
  38. package/lib/Socket/groups.js +332 -0
  39. package/lib/Socket/index.d.ts +174 -0
  40. package/lib/Socket/index.js +10 -0
  41. package/lib/Socket/messages-recv.d.ts +161 -0
  42. package/lib/Socket/messages-recv.js +1046 -0
  43. package/lib/Socket/messages-send.d.ts +151 -0
  44. package/lib/Socket/messages-send.js +806 -0
  45. package/lib/Socket/newsletter.d.ts +136 -0
  46. package/lib/Socket/newsletter.js +250 -0
  47. package/lib/Socket/registration.d.ts +266 -0
  48. package/lib/Socket/registration.js +166 -0
  49. package/lib/Socket/socket.d.ts +42 -0
  50. package/lib/Socket/socket.js +640 -0
  51. package/lib/Socket/usync.d.ts +36 -0
  52. package/lib/Socket/usync.js +70 -0
  53. package/lib/Store/index.d.ts +2 -0
  54. package/lib/Store/index.js +8 -0
  55. package/lib/Store/make-in-memory-store.d.ts +118 -0
  56. package/lib/Store/make-in-memory-store.js +431 -0
  57. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  58. package/lib/Store/make-ordered-dictionary.js +81 -0
  59. package/lib/Store/object-repository.d.ts +10 -0
  60. package/lib/Store/object-repository.js +27 -0
  61. package/lib/Types/Auth.d.ts +109 -0
  62. package/lib/Types/Auth.js +2 -0
  63. package/lib/Types/Call.d.ts +13 -0
  64. package/lib/Types/Call.js +2 -0
  65. package/lib/Types/Chat.d.ts +109 -0
  66. package/lib/Types/Chat.js +4 -0
  67. package/lib/Types/Contact.d.ts +23 -0
  68. package/lib/Types/Contact.js +2 -0
  69. package/lib/Types/Events.d.ts +199 -0
  70. package/lib/Types/Events.js +2 -0
  71. package/lib/Types/GroupMetadata.d.ts +64 -0
  72. package/lib/Types/GroupMetadata.js +2 -0
  73. package/lib/Types/Label.d.ts +35 -0
  74. package/lib/Types/Label.js +27 -0
  75. package/lib/Types/LabelAssociation.d.ts +29 -0
  76. package/lib/Types/LabelAssociation.js +9 -0
  77. package/lib/Types/Message.d.ts +384 -0
  78. package/lib/Types/Message.js +7 -0
  79. package/lib/Types/Newsletter.d.ts +79 -0
  80. package/lib/Types/Newsletter.js +18 -0
  81. package/lib/Types/Product.d.ts +78 -0
  82. package/lib/Types/Product.js +2 -0
  83. package/lib/Types/Signal.d.ts +57 -0
  84. package/lib/Types/Signal.js +2 -0
  85. package/lib/Types/Socket.d.ts +119 -0
  86. package/lib/Types/Socket.js +2 -0
  87. package/lib/Types/State.d.ts +27 -0
  88. package/lib/Types/State.js +2 -0
  89. package/lib/Types/USync.d.ts +25 -0
  90. package/lib/Types/USync.js +2 -0
  91. package/lib/Types/index.d.ts +64 -0
  92. package/lib/Types/index.js +42 -0
  93. package/lib/Utils/auth-utils.d.ts +18 -0
  94. package/lib/Utils/auth-utils.js +206 -0
  95. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  96. package/lib/Utils/baileys-event-stream.js +63 -0
  97. package/lib/Utils/business.d.ts +22 -0
  98. package/lib/Utils/business.js +234 -0
  99. package/lib/Utils/chat-utils.d.ts +70 -0
  100. package/lib/Utils/chat-utils.js +730 -0
  101. package/lib/Utils/crypto.d.ts +40 -0
  102. package/lib/Utils/crypto.js +193 -0
  103. package/lib/Utils/decode-wa-message.d.ts +36 -0
  104. package/lib/Utils/decode-wa-message.js +204 -0
  105. package/lib/Utils/event-buffer.d.ts +35 -0
  106. package/lib/Utils/event-buffer.js +520 -0
  107. package/lib/Utils/generics.d.ts +89 -0
  108. package/lib/Utils/generics.js +445 -0
  109. package/lib/Utils/history.d.ts +19 -0
  110. package/lib/Utils/history.js +94 -0
  111. package/lib/Utils/index.d.ts +17 -0
  112. package/lib/Utils/index.js +33 -0
  113. package/lib/Utils/link-preview.d.ts +21 -0
  114. package/lib/Utils/link-preview.js +126 -0
  115. package/lib/Utils/logger.d.ts +11 -0
  116. package/lib/Utils/logger.js +7 -0
  117. package/lib/Utils/lt-hash.d.ts +12 -0
  118. package/lib/Utils/lt-hash.js +51 -0
  119. package/lib/Utils/make-mutex.d.ts +7 -0
  120. package/lib/Utils/make-mutex.js +43 -0
  121. package/lib/Utils/messages-media.d.ts +120 -0
  122. package/lib/Utils/messages-media.js +879 -0
  123. package/lib/Utils/messages.d.ts +75 -0
  124. package/lib/Utils/messages.js +1022 -0
  125. package/lib/Utils/noise-handler.d.ts +20 -0
  126. package/lib/Utils/noise-handler.js +155 -0
  127. package/lib/Utils/process-message.d.ts +42 -0
  128. package/lib/Utils/process-message.js +372 -0
  129. package/lib/Utils/signal.d.ts +33 -0
  130. package/lib/Utils/signal.js +153 -0
  131. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  132. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  133. package/lib/Utils/validate-connection.d.ts +11 -0
  134. package/lib/Utils/validate-connection.js +207 -0
  135. package/lib/WABinary/constants.d.ts +27 -0
  136. package/lib/WABinary/constants.js +1303 -0
  137. package/lib/WABinary/decode.d.ts +6 -0
  138. package/lib/WABinary/decode.js +265 -0
  139. package/lib/WABinary/encode.d.ts +2 -0
  140. package/lib/WABinary/encode.js +250 -0
  141. package/lib/WABinary/generic-utils.d.ts +14 -0
  142. package/lib/WABinary/generic-utils.js +110 -0
  143. package/lib/WABinary/index.d.ts +5 -0
  144. package/lib/WABinary/index.js +21 -0
  145. package/lib/WABinary/jid-utils.d.ts +36 -0
  146. package/lib/WABinary/jid-utils.js +83 -0
  147. package/lib/WABinary/types.d.ts +18 -0
  148. package/lib/WABinary/types.js +2 -0
  149. package/lib/WAM/BinaryInfo.d.ts +8 -0
  150. package/lib/WAM/BinaryInfo.js +13 -0
  151. package/lib/WAM/constants.d.ts +38 -0
  152. package/lib/WAM/constants.js +15350 -0
  153. package/lib/WAM/encode.d.ts +2 -0
  154. package/lib/WAM/encode.js +155 -0
  155. package/lib/WAM/index.d.ts +3 -0
  156. package/lib/WAM/index.js +19 -0
  157. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  158. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  159. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  160. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  161. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  162. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  163. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  164. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  165. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  166. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  167. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  168. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  169. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  170. package/lib/WAUSync/Protocols/index.js +20 -0
  171. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  172. package/lib/WAUSync/USyncQuery.js +89 -0
  173. package/lib/WAUSync/USyncUser.d.ts +12 -0
  174. package/lib/WAUSync/USyncUser.js +26 -0
  175. package/lib/WAUSync/index.d.ts +3 -0
  176. package/lib/WAUSync/index.js +19 -0
  177. package/lib/index.d.ts +13 -0
  178. package/lib/index.js +63 -0
  179. package/package.json +90 -0
@@ -0,0 +1,806 @@
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 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 WAUSync_1 = require("../WAUSync");
15
+ const newsletter_1 = require("./newsletter");
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, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
20
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
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 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
+ };
284
+ const extraAttrs = {};
285
+ if (participant) {
286
+ // when the retry request is not for a group
287
+ // only send to the specific device that asked for a retry
288
+ // otherwise the message is sent out to every device that should be a recipient
289
+ if (!isGroup && !isStatus) {
290
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
291
+ }
292
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
293
+ devices.push({ user, device });
294
+ }
295
+ await authState.keys.transaction(async () => {
296
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
297
+ const mediaType = getMediaType(message);
298
+ if (mediaType) {
299
+ extraAttrs['mediatype'] = mediaType;
300
+ }
301
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
302
+ extraAttrs['decrypt-fail'] = 'hide';
303
+ }
304
+ if (isGroup || isStatus) {
305
+ const [groupData, senderKeyMap] = await Promise.all([
306
+ (async () => {
307
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
308
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
309
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
310
+ }
311
+ else if (!isStatus) {
312
+ groupData = await groupMetadata(jid);
313
+ }
314
+ return groupData;
315
+ })(),
316
+ (async () => {
317
+ if (!participant && !isStatus) {
318
+ const result = await authState.keys.get('sender-key-memory', [jid]);
319
+ return result[jid] || {};
320
+ }
321
+ return {};
322
+ })()
323
+ ]);
324
+ if (!participant) {
325
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
326
+ if (isStatus && statusJidList) {
327
+ participantsList.push(...statusJidList);
328
+ }
329
+ if (!isStatus) {
330
+ additionalAttributes = {
331
+ ...additionalAttributes,
332
+ // eslint-disable-next-line camelcase
333
+ addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
334
+ };
335
+ }
336
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
337
+ devices.push(...additionalDevices);
338
+ }
339
+ const patched = await patchMessageBeforeSending(message);
340
+ if (Array.isArray(patched)) {
341
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
342
+ }
343
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
344
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
345
+ group: destinationJid,
346
+ data: bytes,
347
+ meId,
348
+ });
349
+ const senderKeyJids = [];
350
+ // ensure a connection is established with every device
351
+ for (const { user, device } of devices) {
352
+ const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
353
+ if (!senderKeyMap[jid] || !!participant) {
354
+ senderKeyJids.push(jid);
355
+ // store that this person has had the sender keys sent to them
356
+ senderKeyMap[jid] = true;
357
+ }
358
+ }
359
+ // if there are some participants with whom the session has not been established
360
+ // if there are, we re-send the senderkey
361
+ if (senderKeyJids.length) {
362
+ logger.debug({ senderKeyJids }, 'sending new sender key');
363
+ const senderKeyMsg = {
364
+ senderKeyDistributionMessage: {
365
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
366
+ groupId: destinationJid
367
+ }
368
+ };
369
+ await assertSessions(senderKeyJids, false);
370
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
371
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
372
+ participants.push(...result.nodes);
373
+ }
374
+ binaryNodeContent.push({
375
+ tag: 'enc',
376
+ attrs: { v: '2', type: 'skmsg' },
377
+ content: ciphertext
378
+ });
379
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
380
+ }
381
+ else if (isNewsletter) {
382
+ // Message edit
383
+ if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
384
+ msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
385
+ message = message.protocolMessage.editedMessage;
386
+ }
387
+ // Message delete
388
+ if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
389
+ msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
390
+ message = {};
391
+ }
392
+ const patched = await patchMessageBeforeSending(message, []);
393
+ if (Array.isArray(patched)) {
394
+ throw new boom_1.Boom('Per-jid patching is not supported in channel');
395
+ }
396
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
397
+ binaryNodeContent.push({
398
+ tag: 'plaintext',
399
+ attrs: mediaType ? { mediatype: mediaType } : {},
400
+ content: bytes
401
+ });
402
+ }
403
+ else {
404
+ const { user: meUser, device: meDevice } = (0, WABinary_1.jidDecode)(meId);
405
+ if (!participant) {
406
+ devices.push({ user });
407
+ // do not send message to self if the device is 0 (mobile)
408
+ if (!((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer' && user === meUser)) {
409
+ if (meDevice !== undefined && meDevice !== 0) {
410
+ devices.push({ user: meUser });
411
+ }
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 content = (0, Utils_1.normalizeMessageContent)(message);
494
+ const contentType = (0, Utils_1.getContentType)(content);
495
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
496
+ contentType === 'buttonsMessage' ||
497
+ contentType === 'listMessage')) {
498
+ const bizNode = { tag: 'biz', attrs: {} };
499
+ if ((((_l = (_k = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _k === void 0 ? void 0 : _k.message) === null || _l === void 0 ? void 0 : _l.interactiveMessage) || ((_o = (_m = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _m === void 0 ? void 0 : _m.message) === null || _o === void 0 ? void 0 : _o.interactiveMessage) || ((_q = (_p = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _p === void 0 ? void 0 : _p.message) === null || _q === void 0 ? void 0 : _q.interactiveMessage) || (message === null || message === void 0 ? void 0 : message.interactiveMessage)) || (((_s = (_r = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _r === void 0 ? void 0 : _r.message) === null || _s === void 0 ? void 0 : _s.buttonsMessage) || ((_u = (_t = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _t === void 0 ? void 0 : _t.message) === null || _u === void 0 ? void 0 : _u.buttonsMessage) || ((_w = (_v = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _v === void 0 ? void 0 : _v.message) === null || _w === void 0 ? void 0 : _w.buttonsMessage) || (message === null || message === void 0 ? void 0 : message.buttonsMessage))) {
500
+ bizNode.content = [{
501
+ tag: 'interactive',
502
+ attrs: {
503
+ type: 'native_flow',
504
+ v: '1'
505
+ },
506
+ content: [{
507
+ tag: 'native_flow',
508
+ attrs: { v: '9', name: 'mixed' }
509
+ }]
510
+ }];
511
+ }
512
+ else if (message === null || message === void 0 ? void 0 : message.listMessage) {
513
+ // list message only support in private chat
514
+ bizNode.content = [{
515
+ tag: 'list',
516
+ attrs: {
517
+ type: 'product_list',
518
+ v: '2'
519
+ }
520
+ }];
521
+ }
522
+ stanza.content.push(bizNode);
523
+ }
524
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
525
+ await sendNode(stanza);
526
+ });
527
+ return msgId;
528
+ };
529
+ const getTypeMessage = (msg) => {
530
+ if (msg.viewOnceMessage) {
531
+ return getTypeMessage(msg.viewOnceMessage.message);
532
+ }
533
+ else if (msg.viewOnceMessageV2) {
534
+ return getTypeMessage(msg.viewOnceMessageV2.message);
535
+ }
536
+ else if (msg.viewOnceMessageV2Extension) {
537
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
538
+ }
539
+ else if (msg.ephemeralMessage) {
540
+ return getTypeMessage(msg.ephemeralMessage.message);
541
+ }
542
+ else if (msg.documentWithCaptionMessage) {
543
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
544
+ }
545
+ else if (msg.reactionMessage) {
546
+ return 'reaction';
547
+ }
548
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
549
+ return 'poll';
550
+ }
551
+ else if (getMediaType(msg)) {
552
+ return 'media';
553
+ }
554
+ else {
555
+ return 'text';
556
+ }
557
+ };
558
+ const getMediaType = (message) => {
559
+ if (message.imageMessage) {
560
+ return 'image';
561
+ }
562
+ else if (message.videoMessage) {
563
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
564
+ }
565
+ else if (message.audioMessage) {
566
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
567
+ }
568
+ else if (message.contactMessage) {
569
+ return 'vcard';
570
+ }
571
+ else if (message.documentMessage) {
572
+ return 'document';
573
+ }
574
+ else if (message.contactsArrayMessage) {
575
+ return 'contact_array';
576
+ }
577
+ else if (message.liveLocationMessage) {
578
+ return 'livelocation';
579
+ }
580
+ else if (message.stickerMessage) {
581
+ return 'sticker';
582
+ }
583
+ else if (message.listMessage) {
584
+ return 'list';
585
+ }
586
+ else if (message.listResponseMessage) {
587
+ return 'list_response';
588
+ }
589
+ else if (message.buttonsResponseMessage) {
590
+ return 'buttons_response';
591
+ }
592
+ else if (message.orderMessage) {
593
+ return 'order';
594
+ }
595
+ else if (message.productMessage) {
596
+ return 'product';
597
+ }
598
+ else if (message.interactiveResponseMessage) {
599
+ return 'native_flow_response';
600
+ }
601
+ else if (message.groupInviteMessage) {
602
+ return 'url';
603
+ }
604
+ };
605
+ const getPrivacyTokens = async (jids) => {
606
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
607
+ const result = await query({
608
+ tag: 'iq',
609
+ attrs: {
610
+ to: WABinary_1.S_WHATSAPP_NET,
611
+ type: 'set',
612
+ xmlns: 'privacy'
613
+ },
614
+ content: [
615
+ {
616
+ tag: 'tokens',
617
+ attrs: {},
618
+ content: jids.map(jid => ({
619
+ tag: 'token',
620
+ attrs: {
621
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
622
+ t,
623
+ type: 'trusted_contact'
624
+ }
625
+ }))
626
+ }
627
+ ]
628
+ });
629
+ return result;
630
+ };
631
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
632
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
633
+ return {
634
+ ...sock,
635
+ getPrivacyTokens,
636
+ assertSessions,
637
+ relayMessage,
638
+ sendReceipt,
639
+ sendReceipts,
640
+ readMessages,
641
+ refreshMediaConn,
642
+ waUploadToServer,
643
+ fetchPrivacySettings,
644
+ getUSyncDevices,
645
+ createParticipantNodes,
646
+ sendPeerDataOperationMessage,
647
+ updateMediaMessage: async (message) => {
648
+ const content = (0, Utils_1.assertMediaContent)(message.message);
649
+ const mediaKey = content.mediaKey;
650
+ const meId = authState.creds.me.id;
651
+ const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
652
+ let error = undefined;
653
+ await Promise.all([
654
+ sendNode(node),
655
+ waitForMsgMediaUpdate(async (update) => {
656
+ const result = update.find(c => c.key.id === message.key.id);
657
+ if (result) {
658
+ if (result.error) {
659
+ error = result.error;
660
+ }
661
+ else {
662
+ try {
663
+ const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
664
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
665
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
666
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
667
+ }
668
+ content.directPath = media.directPath;
669
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
670
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
671
+ }
672
+ catch (err) {
673
+ error = err;
674
+ }
675
+ }
676
+ return true;
677
+ }
678
+ })
679
+ ]);
680
+ if (error) {
681
+ throw error;
682
+ }
683
+ ev.emit('messages.update', [
684
+ { key: message.key, update: { message: message.message } }
685
+ ]);
686
+ return message;
687
+ },
688
+ sendMessage: async (jid, content, options = {}) => {
689
+ var _a, _b, _c, _d, _e;
690
+ const userJid = authState.creds.me.id;
691
+ if (!options.ephemeralExpiration) {
692
+ if ((0, WABinary_1.isJidGroup)(jid)) {
693
+ const groups = await sock.groupQuery(jid, 'get', [{
694
+ tag: 'query',
695
+ attrs: {
696
+ request: 'interactive'
697
+ }
698
+ }]);
699
+ const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
700
+ 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;
701
+ options.ephemeralExpiration = expiration;
702
+ }
703
+ }
704
+ if (typeof content === 'object' &&
705
+ 'disappearingMessagesInChat' in content &&
706
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
707
+ (0, WABinary_1.isJidGroup)(jid)) {
708
+ const { disappearingMessagesInChat } = content;
709
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
710
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
711
+ disappearingMessagesInChat;
712
+ await groupToggleEphemeral(jid, value);
713
+ }
714
+ else {
715
+ let mediaHandle;
716
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
717
+ logger,
718
+ userJid,
719
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
720
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
721
+ fetchOpts: {
722
+ timeout: 3000,
723
+ ...axiosOptions || {}
724
+ },
725
+ logger,
726
+ uploadImage: generateHighQualityLinkPreview
727
+ ? waUploadToServer
728
+ : undefined
729
+ }),
730
+ getProfilePicUrl: sock.profilePictureUrl,
731
+ upload: async (readStream, opts) => {
732
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
733
+ mediaHandle = up.handle;
734
+ return up;
735
+ },
736
+ mediaCache: config.mediaCache,
737
+ options: config.options,
738
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
739
+ ...options,
740
+ });
741
+ const isDeleteMsg = 'delete' in content && !!content.delete;
742
+ const isEditMsg = 'edit' in content && !!content.edit;
743
+ const isPinMsg = 'pin' in content && !!content.pin;
744
+ const isKeepMsg = 'keep' in content && content.keep;
745
+ const isPollMessage = 'poll' in content && !!content.poll;
746
+ const isAiMsg = 'ai' in content && !!content.ai;
747
+ const additionalAttributes = {};
748
+ const additionalNodes = [];
749
+ // required for delete
750
+ if (isDeleteMsg) {
751
+ // if the chat is a group, and I am not the author, then delete the message as an admin
752
+ if (((0, WABinary_1.isJidGroup)((_d = content.delete) === null || _d === void 0 ? void 0 : _d.remoteJid) && !((_e = content.delete) === null || _e === void 0 ? void 0 : _e.fromMe)) || (0, WABinary_1.isJidNewsletter)(jid)) {
753
+ additionalAttributes.edit = '8';
754
+ }
755
+ else {
756
+ additionalAttributes.edit = '7';
757
+ }
758
+ // required for edit message
759
+ }
760
+ else if (isEditMsg) {
761
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
762
+ // required for pin message
763
+ }
764
+ else if (isPinMsg) {
765
+ additionalAttributes.edit = '2';
766
+ // required for keep message
767
+ }
768
+ else if (isKeepMsg) {
769
+ additionalAttributes.edit = '6';
770
+ // required for polling message
771
+ }
772
+ else if (isPollMessage) {
773
+ additionalNodes.push({
774
+ tag: 'meta',
775
+ attrs: {
776
+ polltype: 'creation'
777
+ },
778
+ });
779
+ // required to display AI icon on message
780
+ }
781
+ else if (isAiMsg) {
782
+ additionalNodes.push({
783
+ attrs: {
784
+ biz_bot: '1'
785
+ },
786
+ tag: "bot"
787
+ });
788
+ }
789
+ if (mediaHandle) {
790
+ additionalAttributes['media_id'] = mediaHandle;
791
+ }
792
+ if ('cachedGroupMetadata' in options) {
793
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
794
+ }
795
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
796
+ if (config.emitOwnEvents) {
797
+ process.nextTick(() => {
798
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
799
+ });
800
+ }
801
+ return fullMsg;
802
+ }
803
+ }
804
+ };
805
+ };
806
+ exports.makeMessagesSocket = makeMessagesSocket;