@zetagoaurum-socket/decagramton 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +3344 -0
  5. package/WAProto/index.d.ts +37016 -0
  6. package/WAProto/index.js +130281 -0
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/sender_chain_key.js +50 -0
  16. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  17. package/WASignalGroup/sender_key_message.js +92 -0
  18. package/WASignalGroup/sender_key_name.js +70 -0
  19. package/WASignalGroup/sender_key_record.js +56 -0
  20. package/WASignalGroup/sender_key_state.js +129 -0
  21. package/WASignalGroup/sender_message_key.js +39 -0
  22. package/lib/Defaults/baileys-version.json +3 -0
  23. package/lib/Defaults/index.d.ts +53 -0
  24. package/lib/Defaults/index.js +130 -0
  25. package/lib/Defaults/phonenumber-mcc.json +223 -0
  26. package/lib/Signal/libsignal.d.ts +3 -0
  27. package/lib/Signal/libsignal.js +152 -0
  28. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  29. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  30. package/lib/Socket/Client/index.d.ts +3 -0
  31. package/lib/Socket/Client/index.js +19 -0
  32. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  33. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  34. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  35. package/lib/Socket/Client/web-socket-client.js +62 -0
  36. package/lib/Socket/business.d.ts +170 -0
  37. package/lib/Socket/business.js +260 -0
  38. package/lib/Socket/chats.d.ts +80 -0
  39. package/lib/Socket/chats.js +874 -0
  40. package/lib/Socket/dugong.js +193 -0
  41. package/lib/Socket/groups.d.ts +115 -0
  42. package/lib/Socket/groups.js +320 -0
  43. package/lib/Socket/index.d.ts +173 -0
  44. package/lib/Socket/index.js +24 -0
  45. package/lib/Socket/messages-recv.d.ts +160 -0
  46. package/lib/Socket/messages-recv.js +874 -0
  47. package/lib/Socket/messages-send.d.ts +148 -0
  48. package/lib/Socket/messages-send.js +868 -0
  49. package/lib/Socket/newsletter.d.ts +134 -0
  50. package/lib/Socket/newsletter.js +236 -0
  51. package/lib/Socket/registration.d.ts +267 -0
  52. package/lib/Socket/registration.js +166 -0
  53. package/lib/Socket/socket.d.ts +43 -0
  54. package/lib/Socket/socket.js +657 -0
  55. package/lib/Socket/usync.d.ts +36 -0
  56. package/lib/Socket/usync.js +70 -0
  57. package/lib/Store/index.d.ts +3 -0
  58. package/lib/Store/index.js +10 -0
  59. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  60. package/lib/Store/make-cache-manager-store.js +83 -0
  61. package/lib/Store/make-in-memory-store.d.ts +118 -0
  62. package/lib/Store/make-in-memory-store.js +427 -0
  63. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  64. package/lib/Store/make-ordered-dictionary.js +81 -0
  65. package/lib/Store/object-repository.d.ts +10 -0
  66. package/lib/Store/object-repository.js +27 -0
  67. package/lib/Types/Auth.d.ts +110 -0
  68. package/lib/Types/Auth.js +2 -0
  69. package/lib/Types/Call.d.ts +13 -0
  70. package/lib/Types/Call.js +2 -0
  71. package/lib/Types/Chat.d.ts +102 -0
  72. package/lib/Types/Chat.js +4 -0
  73. package/lib/Types/Contact.d.ts +19 -0
  74. package/lib/Types/Contact.js +2 -0
  75. package/lib/Types/Events.d.ts +157 -0
  76. package/lib/Types/Events.js +2 -0
  77. package/lib/Types/GroupMetadata.d.ts +54 -0
  78. package/lib/Types/GroupMetadata.js +2 -0
  79. package/lib/Types/Label.d.ts +35 -0
  80. package/lib/Types/Label.js +27 -0
  81. package/lib/Types/LabelAssociation.d.ts +29 -0
  82. package/lib/Types/LabelAssociation.js +9 -0
  83. package/lib/Types/Message.d.ts +273 -0
  84. package/lib/Types/Message.js +9 -0
  85. package/lib/Types/Newsletter.d.ts +92 -0
  86. package/lib/Types/Newsletter.js +32 -0
  87. package/lib/Types/Product.d.ts +78 -0
  88. package/lib/Types/Product.js +2 -0
  89. package/lib/Types/Signal.d.ts +57 -0
  90. package/lib/Types/Signal.js +2 -0
  91. package/lib/Types/Socket.d.ts +111 -0
  92. package/lib/Types/Socket.js +2 -0
  93. package/lib/Types/State.d.ts +27 -0
  94. package/lib/Types/State.js +2 -0
  95. package/lib/Types/index.d.ts +57 -0
  96. package/lib/Types/index.js +42 -0
  97. package/lib/Utils/auth-utils.d.ts +18 -0
  98. package/lib/Utils/auth-utils.js +206 -0
  99. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  100. package/lib/Utils/baileys-event-stream.js +63 -0
  101. package/lib/Utils/business.d.ts +22 -0
  102. package/lib/Utils/business.js +234 -0
  103. package/lib/Utils/chat-utils.d.ts +71 -0
  104. package/lib/Utils/chat-utils.js +724 -0
  105. package/lib/Utils/crypto.d.ts +41 -0
  106. package/lib/Utils/crypto.js +151 -0
  107. package/lib/Utils/decode-wa-message.d.ts +19 -0
  108. package/lib/Utils/decode-wa-message.js +198 -0
  109. package/lib/Utils/event-buffer.d.ts +35 -0
  110. package/lib/Utils/event-buffer.js +514 -0
  111. package/lib/Utils/generics.d.ts +92 -0
  112. package/lib/Utils/generics.js +391 -0
  113. package/lib/Utils/history.d.ts +15 -0
  114. package/lib/Utils/history.js +91 -0
  115. package/lib/Utils/index.d.ts +17 -0
  116. package/lib/Utils/index.js +34 -0
  117. package/lib/Utils/link-preview.d.ts +21 -0
  118. package/lib/Utils/link-preview.js +93 -0
  119. package/lib/Utils/logger.d.ts +4 -0
  120. package/lib/Utils/logger.js +7 -0
  121. package/lib/Utils/lt-hash.d.ts +12 -0
  122. package/lib/Utils/lt-hash.js +51 -0
  123. package/lib/Utils/make-mutex.d.ts +7 -0
  124. package/lib/Utils/make-mutex.js +43 -0
  125. package/lib/Utils/messages-media.d.ts +116 -0
  126. package/lib/Utils/messages-media.js +731 -0
  127. package/lib/Utils/messages.d.ts +77 -0
  128. package/lib/Utils/messages.js +1030 -0
  129. package/lib/Utils/noise-handler.d.ts +21 -0
  130. package/lib/Utils/noise-handler.js +155 -0
  131. package/lib/Utils/process-message.d.ts +41 -0
  132. package/lib/Utils/process-message.js +321 -0
  133. package/lib/Utils/rate-limiter.js +55 -0
  134. package/lib/Utils/signal.d.ts +32 -0
  135. package/lib/Utils/signal.js +151 -0
  136. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  137. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  138. package/lib/Utils/validate-connection.d.ts +11 -0
  139. package/lib/Utils/validate-connection.js +205 -0
  140. package/lib/WABinary/constants.d.ts +27 -0
  141. package/lib/WABinary/constants.js +40 -0
  142. package/lib/WABinary/decode.d.ts +7 -0
  143. package/lib/WABinary/decode.js +252 -0
  144. package/lib/WABinary/encode.d.ts +3 -0
  145. package/lib/WABinary/encode.js +228 -0
  146. package/lib/WABinary/generic-utils.d.ts +15 -0
  147. package/lib/WABinary/generic-utils.js +110 -0
  148. package/lib/WABinary/index.d.ts +5 -0
  149. package/lib/WABinary/index.js +21 -0
  150. package/lib/WABinary/jid-utils.d.ts +31 -0
  151. package/lib/WABinary/jid-utils.js +83 -0
  152. package/lib/WABinary/types.d.ts +18 -0
  153. package/lib/WABinary/types.js +2 -0
  154. package/lib/WAM/BinaryInfo.d.ts +17 -0
  155. package/lib/WAM/BinaryInfo.js +13 -0
  156. package/lib/WAM/constants.d.ts +38 -0
  157. package/lib/WAM/constants.js +15350 -0
  158. package/lib/WAM/encode.d.ts +3 -0
  159. package/lib/WAM/encode.js +155 -0
  160. package/lib/WAM/index.d.ts +3 -0
  161. package/lib/WAM/index.js +19 -0
  162. package/lib/WAUSync/Fall +1 -0
  163. package/lib/WAUSync/Protocols/Fal +1 -0
  164. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  167. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  168. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  170. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  172. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  173. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  174. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  176. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  177. package/lib/WAUSync/Protocols/index.js +20 -0
  178. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  179. package/lib/WAUSync/USyncQuery.js +89 -0
  180. package/lib/WAUSync/USyncUser.d.ts +12 -0
  181. package/lib/WAUSync/USyncUser.js +26 -0
  182. package/lib/WAUSync/index.d.ts +3 -0
  183. package/lib/WAUSync/index.js +19 -0
  184. package/lib/index.d.ts +11 -0
  185. package/lib/index.js +30 -0
  186. package/package.json +106 -0
@@ -0,0 +1,868 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Utils_1 = require("../Utils");
12
+ const link_preview_1 = require("../Utils/link-preview");
13
+ const WABinary_1 = require("../WABinary");
14
+ const newsletter_1 = require("./newsletter");
15
+ var ListType = WAProto_1.proto.Message.ListMessage.ListType;
16
+ const makeMessagesSocket = (config) => {
17
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, } = config;
18
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
19
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupToggleEphemeral } = sock;
20
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
22
+ useClones: false
23
+ });
24
+ let mediaConn;
25
+ const refreshMediaConn = async (forceGet = false) => {
26
+ const media = await mediaConn;
27
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
28
+ mediaConn = (async () => {
29
+ const result = await query({
30
+ tag: 'iq',
31
+ attrs: {
32
+ type: 'set',
33
+ xmlns: 'w:m',
34
+ to: WABinary_1.S_WHATSAPP_NET,
35
+ },
36
+ content: [{ tag: 'media_conn', attrs: {} }]
37
+ });
38
+ const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
39
+ const node = {
40
+ hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
41
+ hostname: attrs.hostname,
42
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
43
+ })),
44
+ auth: mediaConnNode.attrs.auth,
45
+ ttl: +mediaConnNode.attrs.ttl,
46
+ fetchDate: new Date()
47
+ };
48
+ logger.debug('fetched media conn');
49
+ return node;
50
+ })();
51
+ }
52
+ return mediaConn;
53
+ };
54
+ /**
55
+ * generic send receipt function
56
+ * used for receipts of phone call, read, delivery etc.
57
+ * */
58
+ const sendReceipt = async (jid, participant, messageIds, type) => {
59
+ const node = {
60
+ tag: 'receipt',
61
+ attrs: {
62
+ id: messageIds[0],
63
+ },
64
+ };
65
+ const isReadReceipt = type === 'read' || type === 'read-self';
66
+ if (isReadReceipt) {
67
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
68
+ }
69
+ if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
70
+ node.attrs.recipient = jid;
71
+ node.attrs.to = participant;
72
+ }
73
+ else {
74
+ node.attrs.to = jid;
75
+ if (participant) {
76
+ node.attrs.participant = participant;
77
+ }
78
+ }
79
+ if (type) {
80
+ node.attrs.type = (0, WABinary_1.isJidNewsLetter)(jid) ? 'read-self' : type;
81
+ }
82
+ const remainingMessageIds = messageIds.slice(1);
83
+ if (remainingMessageIds.length) {
84
+ node.content = [
85
+ {
86
+ tag: 'list',
87
+ attrs: {},
88
+ content: remainingMessageIds.map(id => ({
89
+ tag: 'item',
90
+ attrs: { id }
91
+ }))
92
+ }
93
+ ];
94
+ }
95
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
96
+ await sendNode(node);
97
+ };
98
+ /** Correctly bulk send receipts to multiple chats, participants */
99
+ const sendReceipts = async (keys, type) => {
100
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
101
+ for (const { jid, participant, messageIds } of recps) {
102
+ await sendReceipt(jid, participant, messageIds, type);
103
+ }
104
+ };
105
+ /** Bulk read messages. Keys can be from different chats & participants */
106
+ const readMessages = async (keys) => {
107
+ const privacySettings = await fetchPrivacySettings();
108
+ // based on privacy settings, we have to change the read type
109
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
110
+ await sendReceipts(keys, readType);
111
+ };
112
+ /** Fetch all the devices we've to send a message to */
113
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
114
+ var _a;
115
+ const deviceResults = [];
116
+ if (!useCache) {
117
+ logger.debug('not using cache for devices');
118
+ }
119
+ const users = [];
120
+ jids = Array.from(new Set(jids));
121
+ for (let jid of jids) {
122
+ const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
123
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
124
+ const devices = userDevicesCache.get(user);
125
+ if (devices && useCache) {
126
+ deviceResults.push(...devices);
127
+ logger.trace({ user }, 'using cache for devices');
128
+ }
129
+ else {
130
+ users.push({ tag: 'user', attrs: { jid } });
131
+ }
132
+ }
133
+ if (!users.length) {
134
+ return deviceResults;
135
+ }
136
+ const iq = {
137
+ tag: 'iq',
138
+ attrs: {
139
+ to: WABinary_1.S_WHATSAPP_NET,
140
+ type: 'get',
141
+ xmlns: 'usync',
142
+ },
143
+ content: [
144
+ {
145
+ tag: 'usync',
146
+ attrs: {
147
+ sid: generateMessageTag(),
148
+ mode: 'query',
149
+ last: 'true',
150
+ index: '0',
151
+ context: 'message',
152
+ },
153
+ content: [
154
+ {
155
+ tag: 'query',
156
+ attrs: {},
157
+ content: [
158
+ {
159
+ tag: 'devices',
160
+ attrs: { version: '2' }
161
+ }
162
+ ]
163
+ },
164
+ { tag: 'list', attrs: {}, content: users }
165
+ ]
166
+ },
167
+ ],
168
+ };
169
+ const result = await query(iq);
170
+ const extracted = (0, Utils_1.extractDeviceJids)(result, authState.creds.me.id, ignoreZeroDevices);
171
+ const deviceMap = {};
172
+ for (const item of extracted) {
173
+ deviceMap[item.user] = deviceMap[item.user] || [];
174
+ deviceMap[item.user].push(item);
175
+ deviceResults.push(item);
176
+ }
177
+ for (const key in deviceMap) {
178
+ userDevicesCache.set(key, deviceMap[key]);
179
+ }
180
+ return deviceResults;
181
+ };
182
+ const assertSessions = async (jids, force) => {
183
+ let didFetchNewSession = false;
184
+ let jidsRequiringFetch = [];
185
+ if (force) {
186
+ jidsRequiringFetch = jids;
187
+ }
188
+ else {
189
+ const addrs = jids.map(jid => (signalRepository
190
+ .jidToSignalProtocolAddress(jid)));
191
+ const sessions = await authState.keys.get('session', addrs);
192
+ for (const jid of jids) {
193
+ const signalId = signalRepository
194
+ .jidToSignalProtocolAddress(jid);
195
+ if (!sessions[signalId]) {
196
+ jidsRequiringFetch.push(jid);
197
+ }
198
+ }
199
+ }
200
+ if (jidsRequiringFetch.length) {
201
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
202
+ const result = await query({
203
+ tag: 'iq',
204
+ attrs: {
205
+ xmlns: 'encrypt',
206
+ type: 'get',
207
+ to: WABinary_1.S_WHATSAPP_NET,
208
+ },
209
+ content: [
210
+ {
211
+ tag: 'key',
212
+ attrs: {},
213
+ content: jidsRequiringFetch.map(jid => ({
214
+ tag: 'user',
215
+ attrs: { jid },
216
+ }))
217
+ }
218
+ ]
219
+ });
220
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
221
+ didFetchNewSession = true;
222
+ }
223
+ return didFetchNewSession;
224
+ };
225
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
226
+ const patched = await patchMessageBeforeSending(message, jids);
227
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
228
+ let shouldIncludeDeviceIdentity = false;
229
+ const nodes = await Promise.all(jids.map(async (jid) => {
230
+ const { type, ciphertext } = await signalRepository
231
+ .encryptMessage({ jid, data: bytes });
232
+ if (type === 'pkmsg') {
233
+ shouldIncludeDeviceIdentity = true;
234
+ }
235
+ const node = {
236
+ tag: 'to',
237
+ attrs: { jid },
238
+ content: [{
239
+ tag: 'enc',
240
+ attrs: {
241
+ v: '2',
242
+ type,
243
+ ...extraAttrs || {}
244
+ },
245
+ content: ciphertext
246
+ }]
247
+ };
248
+ return node;
249
+ }));
250
+ return { nodes, shouldIncludeDeviceIdentity };
251
+ }; //apela
252
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, statusJidList }) => {
253
+ const meId = authState.creds.me.id;
254
+ let shouldIncludeDeviceIdentity = false;
255
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
256
+ const statusJid = 'status@broadcast';
257
+ const isGroup = server === 'g.us';
258
+ const isStatus = jid === statusJid;
259
+ const isLid = server === 'lid';
260
+ const isNewsletter = server === 'newsletter';
261
+ msgId = msgId || (0, Utils_1.generateMessageID)();
262
+ useUserDevicesCache = useUserDevicesCache !== false;
263
+ const participants = [];
264
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
265
+ const binaryNodeContent = [];
266
+ const devices = [];
267
+ const meMsg = {
268
+ deviceSentMessage: {
269
+ destinationJid,
270
+ message
271
+ }
272
+ };
273
+ if (participant) {
274
+ // when the retry request is not for a group
275
+ // only send to the specific device that asked for a retry
276
+ // otherwise the message is sent out to every device that should be a recipient
277
+ if (!isGroup && !isStatus) {
278
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
279
+ }
280
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
281
+ devices.push({ user, device });
282
+ }
283
+ await authState.keys.transaction(async () => {
284
+ var _a, _b, _c, _d, _e, _f;
285
+ const mediaType = getMediaType(message);
286
+ if (isGroup || isStatus) {
287
+ const [groupData, senderKeyMap] = await Promise.all([
288
+ (async () => {
289
+ let groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
290
+ if (groupData) {
291
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
292
+ }
293
+ if (!groupData && !isStatus) {
294
+ groupData = await groupMetadata(jid);
295
+ }
296
+ return groupData;
297
+ })(),
298
+ (async () => {
299
+ if (!participant && !isStatus) {
300
+ const result = await authState.keys.get('sender-key-memory', [jid]);
301
+ return result[jid] || {};
302
+ }
303
+ return {};
304
+ })()
305
+ ]);
306
+ if (!participant) {
307
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
308
+ if (isStatus && statusJidList) {
309
+ participantsList.push(...statusJidList);
310
+ }
311
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
312
+ devices.push(...additionalDevices);
313
+ }
314
+ const patched = await patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
315
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
316
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
317
+ group: destinationJid,
318
+ data: bytes,
319
+ meId,
320
+ });
321
+ const senderKeyJids = [];
322
+ // ensure a connection is established with every device
323
+ for (const { user, device } of devices) {
324
+ const jid = (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : 's.whatsapp.net', device);
325
+ if (!senderKeyMap[jid] || !!participant) {
326
+ senderKeyJids.push(jid);
327
+ // store that this person has had the sender keys sent to them
328
+ senderKeyMap[jid] = true;
329
+ }
330
+ }
331
+ // if there are some participants with whom the session has not been established
332
+ // if there are, we re-send the senderkey
333
+ if (senderKeyJids.length) {
334
+ logger.debug({ senderKeyJids }, 'sending new sender key');
335
+ const senderKeyMsg = {
336
+ senderKeyDistributionMessage: {
337
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
338
+ groupId: destinationJid
339
+ }
340
+ };
341
+ await assertSessions(senderKeyJids, false);
342
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { mediatype: mediaType } : undefined);
343
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
344
+ participants.push(...result.nodes);
345
+ }
346
+ binaryNodeContent.push({
347
+ tag: 'enc',
348
+ attrs: { v: '2', type: 'skmsg' },
349
+ content: ciphertext
350
+ });
351
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
352
+ }
353
+ else if (isNewsletter) {
354
+ // Message edit
355
+ if ((_a = message.protocolMessage) === null || _a === void 0 ? void 0 : _a.editedMessage) {
356
+ msgId = (_b = message.protocolMessage.key) === null || _b === void 0 ? void 0 : _b.id;
357
+ message = message.protocolMessage.editedMessage;
358
+ }
359
+ // Message delete
360
+ if (((_c = message.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
361
+ msgId = (_d = message.protocolMessage.key) === null || _d === void 0 ? void 0 : _d.id;
362
+ message = {};
363
+ }
364
+ const patched = await patchMessageBeforeSending(message, []);
365
+ const bytes = WAProto_1.proto.Message.encode(patched).finish();
366
+ binaryNodeContent.push({
367
+ tag: 'plaintext',
368
+ attrs: mediaType ? { mediatype: mediaType } : {},
369
+ content: bytes
370
+ });
371
+ }
372
+ else {
373
+ const { user: meUser, device: meDevice } = (0, WABinary_1.jidDecode)(meId);
374
+ if (!participant) {
375
+ devices.push({ user });
376
+ // do not send message to self if the device is 0 (mobile)
377
+ if (meDevice !== undefined && meDevice !== 0) {
378
+ devices.push({ user: meUser });
379
+ }
380
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
381
+ devices.push(...additionalDevices);
382
+ }
383
+ const allJids = [];
384
+ const meJids = [];
385
+ const otherJids = [];
386
+ for (const { user, device } of devices) {
387
+ const isMe = user === meUser;
388
+ const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_f = (_e = authState.creds) === null || _e === void 0 ? void 0 : _e.me) === null || _f === void 0 ? void 0 : _f.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
389
+ if (isMe) {
390
+ meJids.push(jid);
391
+ }
392
+ else {
393
+ otherJids.push(jid);
394
+ }
395
+ allJids.push(jid);
396
+ }
397
+ await assertSessions(allJids, false);
398
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
399
+ createParticipantNodes(meJids, meMsg, mediaType ? { mediatype: mediaType } : undefined),
400
+ createParticipantNodes(otherJids, message, mediaType ? { mediatype: mediaType } : undefined)
401
+ ]);
402
+ participants.push(...meNodes);
403
+ participants.push(...otherNodes);
404
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
405
+ }
406
+ if (participants.length) {
407
+ binaryNodeContent.push({
408
+ tag: 'participants',
409
+ attrs: {},
410
+ content: participants
411
+ });
412
+ }
413
+ const stanza = {
414
+ tag: 'message',
415
+ attrs: {
416
+ id: msgId,
417
+ type: isNewsletter ? getTypeMessage(message) : 'text',
418
+ ...(additionalAttributes || {})
419
+ },
420
+ content: binaryNodeContent
421
+ };
422
+ // if the participant to send to is explicitly specified (generally retry recp)
423
+ // ensure the message is only sent to that person
424
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
425
+ if (participant) {
426
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
427
+ stanza.attrs.to = destinationJid;
428
+ stanza.attrs.participant = participant.jid;
429
+ }
430
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
431
+ stanza.attrs.to = participant.jid;
432
+ stanza.attrs.recipient = destinationJid;
433
+ }
434
+ else {
435
+ stanza.attrs.to = participant.jid;
436
+ }
437
+ }
438
+ else {
439
+ stanza.attrs.to = destinationJid;
440
+ }
441
+ if (shouldIncludeDeviceIdentity) {
442
+ stanza.content.push({
443
+ tag: 'device-identity',
444
+ attrs: {},
445
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
446
+ });
447
+ logger.debug({ jid }, 'adding device identity');
448
+ }
449
+ if (additionalNodes && additionalNodes.length > 0) {
450
+ stanza.content.push(...additionalNodes);
451
+ }
452
+ else {
453
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && ((message === null || message === void 0 ? void 0 : message.viewOnceMessage) ? message === null || message === void 0 ? void 0 : message.viewOnceMessage : (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) ? message === null || message === void 0 ? void 0 : message.viewOnceMessageV2 : (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) ? message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension : (message === null || message === void 0 ? void 0 : message.ephemeralMessage) ? message === null || message === void 0 ? void 0 : message.ephemeralMessage : (message === null || message === void 0 ? void 0 : message.templateMessage) ? message === null || message === void 0 ? void 0 : message.templateMessage : (message === null || message === void 0 ? void 0 : message.interactiveMessage) ? message === null || message === void 0 ? void 0 : message.interactiveMessage : message === null || message === void 0 ? void 0 : message.buttonsMessage)) {
454
+ stanza.content.push({
455
+ tag: 'biz',
456
+ attrs: {},
457
+ content: [{
458
+ tag: 'interactive',
459
+ attrs: {
460
+ type: 'native_flow',
461
+ v: '1'
462
+ },
463
+ content: [{
464
+ tag: 'native_flow',
465
+ attrs: { v: '9', name: 'mixed' }
466
+ }]
467
+ }]
468
+ });
469
+ }
470
+ }
471
+ const buttonType = getButtonType(message);
472
+ if (buttonType) {
473
+ stanza.content.push({
474
+ tag: 'biz',
475
+ attrs: {},
476
+ content: [
477
+ {
478
+ tag: buttonType,
479
+ attrs: getButtonArgs(message),
480
+ }
481
+ ]
482
+ });
483
+ logger.debug({ jid }, 'adding business node');
484
+ }
485
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
486
+ await sendNode(stanza);
487
+ });
488
+ return msgId;
489
+ };
490
+ const getTypeMessage = (msg) => {
491
+ const message = Utils_1.normalizeMessageContent(msg)
492
+ if (message.reactionMessage) {
493
+ return 'reaction'
494
+ }
495
+ else if (getMediaType(message)) {
496
+ return 'media'
497
+ }
498
+ else {
499
+ return 'text'
500
+ }
501
+ }
502
+
503
+ const getMediaType = (message) => {
504
+ if (message.imageMessage) {
505
+ return 'image'
506
+ }
507
+ else if (message.videoMessage) {
508
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
509
+ }
510
+ else if (message.audioMessage) {
511
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
512
+ }
513
+ else if (message.contactMessage) {
514
+ return 'vcard'
515
+ }
516
+ else if (message.documentMessage) {
517
+ return 'document'
518
+ }
519
+ else if (message.contactsArrayMessage) {
520
+ return 'contact_array'
521
+ }
522
+ else if (message.liveLocationMessage) {
523
+ return 'livelocation'
524
+ }
525
+ else if (message.stickerMessage) {
526
+ return 'sticker'
527
+ }
528
+ else if (message.listMessage) {
529
+ return 'list'
530
+ }
531
+ else if (message.listResponseMessage) {
532
+ return 'list_response'
533
+ }
534
+ else if (message.buttonsResponseMessage) {
535
+ return 'buttons_response'
536
+ }
537
+ else if (message.orderMessage) {
538
+ return 'order'
539
+ }
540
+ else if (message.productMessage) {
541
+ return 'product'
542
+ }
543
+ else if (message.interactiveResponseMessage) {
544
+ return 'native_flow_response'
545
+ }
546
+ else if (message.groupInviteMessage) {
547
+ return 'url'
548
+ }
549
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
550
+ return 'productlink'
551
+ }
552
+ }
553
+ const getButtonType = (message) => {
554
+ if (message.listMessage) {
555
+ return 'list'
556
+ }
557
+ else if (message.buttonsMessage) {
558
+ return 'buttons'
559
+ }
560
+ else if(message.interactiveMessage?.nativeFlowMessage) {
561
+ return 'native_flow'
562
+ }
563
+ }
564
+ const getButtonArgs = (message) => {
565
+ if (message.interactiveMessage?.nativeFlowMessage && message.interactiveMessage.nativeFlowMessage?.buttons?.length > 0 && message.interactiveMessage.nativeFlowMessage.buttons[0].name === 'review_and_pay') {
566
+ return {
567
+ tag: 'biz',
568
+ attrs: {
569
+ native_flow_name: 'order_details'
570
+ }
571
+ }
572
+ } else if (message.interactiveMessage?.nativeFlowMessage && message.interactiveMessage.nativeFlowMessage?.buttons?.length > 0 && message.interactiveMessage.nativeFlowMessage.buttons[0].name === 'payment_info') {
573
+ return {
574
+ tag: 'biz',
575
+ attrs: {
576
+ native_flow_name: 'payment_info'
577
+ }
578
+ }
579
+ } else if (message.interactiveMessage?.nativeFlowMessage &&message.interactiveMessage.nativeFlowMessage?.buttons?.length > 0 &&
580
+ ['mpm', 'cta_catalog', 'send_location', 'call_permission_request', 'wa_payment_transaction_details', 'automated_greeting_message_view_catalog']
581
+ .includes(message.interactiveMessage.nativeFlowMessage.buttons[0].name)) {
582
+ return {
583
+ tag: 'biz',
584
+ attrs: {},
585
+ content: [{
586
+ tag: 'interactive',
587
+ attrs: {
588
+ type: 'native_flow',
589
+ v: '1'
590
+ },
591
+ content: [{
592
+ tag: 'native_flow',
593
+ attrs: {
594
+ v: '2',
595
+ name: message.interactiveMessage.nativeFlowMessage.buttons[0].name
596
+ }
597
+ }]
598
+ }]
599
+ }
600
+ } else if (message.interactiveMessage?.nativeFlowMessage || message.buttonsMessage) {
601
+ return {
602
+ tag: 'biz',
603
+ attrs: {},
604
+ content: [{
605
+ tag: 'interactive',
606
+ attrs: {
607
+ type: 'native_flow',
608
+ v: '1'
609
+ },
610
+ content: [{
611
+ tag: 'native_flow',
612
+ attrs: {
613
+ v: '9',
614
+ name: 'mixed'
615
+ }
616
+ }]
617
+ }]
618
+ }
619
+ } else if (message.listMessage) {
620
+ return {
621
+ tag: 'biz',
622
+ attrs: {},
623
+ content: [{
624
+ tag: 'list',
625
+ attrs: {
626
+ v: '2',
627
+ type: 'product_list'
628
+ }
629
+ }]
630
+ }
631
+ } else {
632
+ return {
633
+ tag: 'biz',
634
+ attrs: {}
635
+ }
636
+ }
637
+ }
638
+ const getPrivacyTokens = async (jids) => {
639
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
640
+ const result = await query({
641
+ tag: 'iq',
642
+ attrs: {
643
+ to: WABinary_1.S_WHATSAPP_NET,
644
+ type: 'set',
645
+ xmlns: 'privacy'
646
+ },
647
+ content: [
648
+ {
649
+ tag: 'tokens',
650
+ attrs: {},
651
+ content: jids.map(jid => ({
652
+ tag: 'token',
653
+ attrs: {
654
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
655
+ t,
656
+ type: 'trusted_contact'
657
+ }
658
+ }))
659
+ }
660
+ ]
661
+ });
662
+ return result;
663
+ };
664
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
665
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
666
+ return {
667
+ ...sock,
668
+ getPrivacyTokens,
669
+ assertSessions,
670
+ relayMessage,
671
+ sendReceipt,
672
+ sendReceipts,
673
+ getButtonArgs,
674
+ readMessages,
675
+ refreshMediaConn,
676
+ getUSyncDevices,
677
+ createParticipantNodes,
678
+ waUploadToServer,
679
+ fetchPrivacySettings,
680
+ updateMediaMessage: async (message) => {
681
+ const content = (0, Utils_1.assertMediaContent)(message.message);
682
+ const mediaKey = content.mediaKey;
683
+ const meId = authState.creds.me.id;
684
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
685
+ let error = undefined;
686
+ await Promise.all([
687
+ sendNode(node),
688
+ waitForMsgMediaUpdate(update => {
689
+ const result = update.find(c => c.key.id === message.key.id);
690
+ if (result) {
691
+ if (result.error) {
692
+ error = result.error;
693
+ }
694
+ else {
695
+ try {
696
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
697
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
698
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
699
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
700
+ }
701
+ content.directPath = media.directPath;
702
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
703
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
704
+ }
705
+ catch (err) {
706
+ error = err;
707
+ }
708
+ }
709
+ return true;
710
+ }
711
+ })
712
+ ]);
713
+ if (error) {
714
+ throw error;
715
+ }
716
+ ev.emit('messages.update', [
717
+ { key: message.key, update: { message: message.message } }
718
+ ]);
719
+ return message;
720
+ },
721
+ sendMessage: async (jid, content, options = {}) => {
722
+ const userJid = authState.creds.me.id;
723
+ const additionalAttributes = {};
724
+ const additionalNodes = [];
725
+
726
+ // ZetaGo-Aurum Enterprise Rate Limiter
727
+ const { kikyy } = require("./dugong");
728
+ const rahmi = new kikyy(sock);
729
+ const { RateLimiter } = require("../Utils");
730
+ // Singleton rate limiter for the socket instance (naively re-created here, should be in closure)
731
+ // Ideally should be passed in config, but for now we create per-call to throttle BURSTS slightly
732
+ // Real rate limiting should be at socket level.
733
+ // Let's attach it to 'sock' if not exists or use a global one.
734
+ if (!sock.rateLimiter) {
735
+ sock.rateLimiter = new RateLimiter({ maxTokens: 5, refillRate: 2 });
736
+ }
737
+ await sock.rateLimiter.consume(1);
738
+
739
+ const messageType = Object.keys(content)[0];
740
+ if (messageType) {
741
+ switch (messageType) {
742
+ case 'PAYMENT':
743
+ const paymentContent = await rahmi.handlePayment(content, options.quoted);
744
+ return await relayMessage(jid, paymentContent, {
745
+ messageId: (0, Utils_1.generateMessageID)(),
746
+ participants: options.participants,
747
+ additionalAttributes: { ...additionalAttributes, ...options.additionalAttributes },
748
+ additionalNodes: options.additionalNodes,
749
+ AI: true
750
+ });
751
+
752
+ case 'PRODUCT':
753
+ const productContent = await rahmi.handleProduct(content, jid, options.quoted);
754
+ const productMsg = await (0, Utils_1.generateWAMessageFromContent)(jid, productContent, { quoted: options.quoted });
755
+ return await relayMessage(jid, productMsg.message, {
756
+ messageId: productMsg.key.id,
757
+ participants: options.participants,
758
+ additionalAttributes: { ...additionalAttributes, ...options.additionalAttributes },
759
+ additionalNodes: options.additionalNodes,
760
+ AI: true
761
+ });
762
+
763
+ case 'INTERACTIVE':
764
+ const interactiveContent = await rahmi.handleInteractive(content, jid, options.quoted);
765
+ const interactiveMsg = await (0, Utils_1.generateWAMessageFromContent)(jid, interactiveContent, { quoted: options.quoted });
766
+ return await relayMessage(jid, interactiveMsg.message, {
767
+ messageId: interactiveMsg.key.id,
768
+ participants: options.participants,
769
+ additionalAttributes: { ...additionalAttributes, ...options.additionalAttributes },
770
+ additionalNodes: options.additionalNodes,
771
+ AI: true
772
+ });
773
+ case 'ALBUM':
774
+ return await rahmi.handleAlbum(content, jid, options.quoted)
775
+ case 'EVENT':
776
+ return await rahmi.handleEvent(content, jid, options.quoted)
777
+ case 'POLL_RESULT':
778
+ return await rahmi.handlePollResult(content, jid, options.quoted)
779
+ case 'GROUP_STORY':
780
+ return await rahmi.handleGroupStory(content, jid, options.quoted)
781
+ }
782
+ }
783
+
784
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
785
+ logger,
786
+ userJid,
787
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
788
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
789
+ fetchOpts: {
790
+ timeout: 3000,
791
+ ...axiosOptions || {}
792
+ },
793
+ logger,
794
+ uploadImage: generateHighQualityLinkPreview
795
+ ? waUploadToServer
796
+ : undefined
797
+ }),
798
+ upload: async (readStream, opts) => {
799
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
800
+ mediaHandle = up.handle;
801
+ return up;
802
+ },
803
+ mediaCache: config.mediaCache,
804
+ options: config.options,
805
+ ...options,
806
+ });
807
+ const isDeleteMsg = 'delete' in content && !!content.delete;
808
+ const isEditMsg = 'edit' in content && !!content.edit;
809
+ const isAiMsg = 'ai' in content && !!content.ai;
810
+
811
+ // required for delete
812
+ if (isDeleteMsg) {
813
+ // if the chat is a group, and I am not the author, then delete the message as an admin
814
+ if (((0, WABinary_1.isJidGroup)(content.delete?.remoteJid) && !content.delete?.fromMe) || (0, WABinary_1.isJidNewsLetter)(jid)) {
815
+ additionalAttributes.edit = '8';
816
+ }
817
+ else {
818
+ additionalAttributes.edit = '7';
819
+ }
820
+ }
821
+ else if (isEditMsg) {
822
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsLetter)(jid) ? '3' : '1';
823
+ }
824
+
825
+ // AI Logic (Hybrid)
826
+ if (isAiMsg || options.AI) {
827
+ // For Private Chats: Use biz_bot (standard)
828
+ if ((0, WABinary_1.isJidUser)(jid)) {
829
+ additionalNodes.push({
830
+ attrs: {
831
+ biz_bot: '1'
832
+ },
833
+ tag: "bot"
834
+ });
835
+ }
836
+ // For Group Chats: Use supportPayload (safer, no drop)
837
+ else if ((0, WABinary_1.isJidGroup)(jid)) {
838
+ const msgType = Object.keys(fullMsg.message)[0];
839
+ if (msgType) {
840
+ fullMsg.message[msgType].messageContextInfo = fullMsg.message[msgType].messageContextInfo || {};
841
+ fullMsg.message[msgType].messageContextInfo.messageSecret = fullMsg.message[msgType].messageContextInfo.messageSecret || crypto.randomBytes(32);
842
+ fullMsg.message[msgType].messageContextInfo.supportPayload = JSON.stringify({
843
+ version: 1,
844
+ is_ai_message: true,
845
+ should_show_system_message: true,
846
+ ticket_id: crypto.randomBytes(16).toString('hex')
847
+ });
848
+ }
849
+ }
850
+ }
851
+
852
+ if (mediaHandle) {
853
+ additionalAttributes['media_id'] = mediaHandle;
854
+ }
855
+ if ('cachedGroupMetadata' in options) {
856
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
857
+ }
858
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalNodes, additionalAttributes, statusJidList: options.statusJidList });
859
+ if (config.emitOwnEvents) {
860
+ process.nextTick(() => {
861
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
862
+ });
863
+ }
864
+ return fullMsg;
865
+ }
866
+ }
867
+ };
868
+ exports.makeMessagesSocket = makeMessagesSocket;