lordceaser-baileys 2.0.11 → 2.0.13

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