queenjusmy-baileys 3.0.8

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