@zervonex/baileys 0.0.0-stage → 3.0.1

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 (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3203 -2
  3. package/WAProto/WAProtoCompile.js +291 -0
  4. package/WAProto/fetcher.js +69 -0
  5. package/WAProto/index.js +88 -0
  6. package/WAProto/parser.js +313 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Builders/AIRich.js +590 -0
  9. package/lib/Builders/base.js +130 -0
  10. package/lib/Builders/builders.js +448 -0
  11. package/lib/Builders/index.js +3 -0
  12. package/lib/Defaults/index.js +225 -0
  13. package/lib/Defaults/phonenumber-mcc.json +223 -0
  14. package/lib/Signal/index.js +2 -0
  15. package/lib/Signal/libsignal.js +523 -0
  16. package/lib/Signal/lid-mapping.js +283 -0
  17. package/lib/Socket/Client/index.js +2 -0
  18. package/lib/Socket/Client/types.js +10 -0
  19. package/lib/Socket/Client/websocket.js +84 -0
  20. package/lib/Socket/business.js +152 -0
  21. package/lib/Socket/chats.js +855 -0
  22. package/lib/Socket/communities.js +147 -0
  23. package/lib/Socket/groups.js +294 -0
  24. package/lib/Socket/index.js +15 -0
  25. package/lib/Socket/messages-recv.js +904 -0
  26. package/lib/Socket/messages-send.js +693 -0
  27. package/lib/Socket/mex.js +34 -0
  28. package/lib/Socket/newsletter.js +752 -0
  29. package/lib/Socket/nexus-handler.js +55 -0
  30. package/lib/Socket/registration.js +155 -0
  31. package/lib/Socket/socket.js +798 -0
  32. package/lib/Socket/spam-report.js +65 -0
  33. package/lib/Socket/username.js +82 -0
  34. package/lib/Store/index.js +6 -0
  35. package/lib/Store/make-cache-manager-store.js +81 -0
  36. package/lib/Store/make-in-memory-store.js +425 -0
  37. package/lib/Store/make-ordered-dictionary.js +82 -0
  38. package/lib/Store/object-repository.js +31 -0
  39. package/lib/Store/reporting-info-store.js +38 -0
  40. package/lib/Types/Auth.js +2 -0
  41. package/lib/Types/Bussines.js +2 -0
  42. package/lib/Types/Call.js +2 -0
  43. package/lib/Types/Chat.js +8 -0
  44. package/lib/Types/Contact.js +2 -0
  45. package/lib/Types/Events.js +2 -0
  46. package/lib/Types/GroupMetadata.js +2 -0
  47. package/lib/Types/Label.js +25 -0
  48. package/lib/Types/LabelAssociation.js +7 -0
  49. package/lib/Types/Message.js +15 -0
  50. package/lib/Types/Newsletter.js +100 -0
  51. package/lib/Types/Product.js +2 -0
  52. package/lib/Types/Signal.js +2 -0
  53. package/lib/Types/Socket.js +14 -0
  54. package/lib/Types/State.js +26 -0
  55. package/lib/Types/USync.js +2 -0
  56. package/lib/Types/index.js +30 -0
  57. package/lib/Utils/auth-utils.js +142 -0
  58. package/lib/Utils/baileys-event-stream.js +33 -0
  59. package/lib/Utils/bot-capabilities.js +40 -0
  60. package/lib/Utils/bot-planning-replay.js +44 -0
  61. package/lib/Utils/browser-utils.js +26 -0
  62. package/lib/Utils/business.js +75 -0
  63. package/lib/Utils/chat-utils.js +316 -0
  64. package/lib/Utils/companion-reg-client-utils.js +20 -0
  65. package/lib/Utils/consumer-application.js +38 -0
  66. package/lib/Utils/crypto.js +52 -0
  67. package/lib/Utils/decode-wa-message.js +197 -0
  68. package/lib/Utils/event-buffer.js +273 -0
  69. package/lib/Utils/extras.js +186 -0
  70. package/lib/Utils/generics.js +195 -0
  71. package/lib/Utils/history.js +51 -0
  72. package/lib/Utils/identity-change-handler.js +19 -0
  73. package/lib/Utils/index.js +39 -0
  74. package/lib/Utils/key-store.js +3 -0
  75. package/lib/Utils/link-preview.js +51 -0
  76. package/lib/Utils/logger.js +2 -0
  77. package/lib/Utils/lt-hash.js +3 -0
  78. package/lib/Utils/make-mutex.js +16 -0
  79. package/lib/Utils/message-composer.js +59 -0
  80. package/lib/Utils/message-retry-manager.js +48 -0
  81. package/lib/Utils/messages-media.js +520 -0
  82. package/lib/Utils/messages.js +742 -0
  83. package/lib/Utils/meta-ai-msmsg.js +122 -0
  84. package/lib/Utils/meta-compositing.js +75 -0
  85. package/lib/Utils/modern-messages.js +235 -0
  86. package/lib/Utils/native-flow.js +55 -0
  87. package/lib/Utils/noise-handler.js +161 -0
  88. package/lib/Utils/pre-key-manager.js +76 -0
  89. package/lib/Utils/process-message.js +399 -0
  90. package/lib/Utils/reporting-utils.js +171 -0
  91. package/lib/Utils/signal.js +167 -0
  92. package/lib/Utils/spam-report-utils.js +142 -0
  93. package/lib/Utils/sync-action-utils.js +33 -0
  94. package/lib/Utils/tc-token-utils.js +102 -0
  95. package/lib/Utils/use-multi-file-auth-state.js +307 -0
  96. package/lib/Utils/validate-connection.js +181 -0
  97. package/lib/WABinary/constants.js +1321 -0
  98. package/lib/WABinary/decode.js +152 -0
  99. package/lib/WABinary/encode.js +140 -0
  100. package/lib/WABinary/generic-utils.js +179 -0
  101. package/lib/WABinary/index.js +6 -0
  102. package/lib/WABinary/jid-utils.js +235 -0
  103. package/lib/WABinary/types.js +4 -0
  104. package/lib/WAM/BinaryInfo.js +10 -0
  105. package/lib/WAM/constants.js +22853 -0
  106. package/lib/WAM/encode.js +150 -0
  107. package/lib/WAM/index.js +3 -0
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
  120. package/lib/WAUSync/Protocols/index.js +12 -0
  121. package/lib/WAUSync/USyncQuery.js +100 -0
  122. package/lib/WAUSync/USyncUser.js +20 -0
  123. package/lib/WAUSync/index.js +3 -0
  124. package/lib/index.js +68 -0
  125. package/package.json +216 -5
@@ -0,0 +1,283 @@
1
+ import { LRUCache } from 'lru-cache'
2
+ import { isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, WAJIDDomains } from '../WABinary/index.js'
3
+
4
+ export class LIDMappingStore {
5
+ constructor(keys, logger, pnToLIDFunc) {
6
+ this.mappingCache = new LRUCache({ ttl: 3 * 24 * 60 * 60 * 1000, ttlAutopurge: true, updateAgeOnGet: true })
7
+ this.inflightLIDLookups = new Map()
8
+ this.inflightPNLookups = new Map()
9
+ this.keys = keys
10
+ this.logger = logger
11
+ this.pnToLIDFunc = pnToLIDFunc
12
+ }
13
+
14
+ async storeLIDPNMappings(pairs) {
15
+ if (!pairs.length) return
16
+
17
+ const validatedPairs = []
18
+ for (const { lid, pn } of pairs) {
19
+ if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
20
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`)
21
+ continue
22
+ }
23
+ const lidDecoded = jidDecode(lid)
24
+ const pnDecoded = jidDecode(pn)
25
+ if (!lidDecoded || !pnDecoded) continue // fixed: was `return`, skips only this pair
26
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user })
27
+ }
28
+
29
+ if (!validatedPairs.length) return
30
+
31
+ // Batch check all cache misses in one DB call (forward AND reverse)
32
+ const cacheMissSet = new Set()
33
+ const existingMappings = new Map()
34
+ const existingReverse = new Map()
35
+
36
+ for (const { pnUser } of validatedPairs) {
37
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
38
+ if (cached) existingMappings.set(pnUser, cached)
39
+ else cacheMissSet.add(pnUser)
40
+ }
41
+
42
+ if (cacheMissSet.size > 0) {
43
+ this.logger.trace(`Batch fetching ${cacheMissSet.size} LID mappings from database`)
44
+ const stored = await this.keys.get('lid-mapping', [...cacheMissSet])
45
+ for (const pnUser of cacheMissSet) {
46
+ const lidUser = stored[pnUser]
47
+ if (lidUser) {
48
+ existingMappings.set(pnUser, lidUser)
49
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
50
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
51
+ }
52
+ }
53
+ }
54
+
55
+ // Separately verify the reverse entry actually exists on disk for every
56
+ // pair whose forward mapping we found — a forward file existing does NOT
57
+ // guarantee its `_reverse` sibling was ever written (e.g. when only the
58
+ // recipient side of a fromMe message was resolved, never the sender side).
59
+ const reverseKeysToCheck = []
60
+ for (const { pnUser, lidUser } of validatedPairs) {
61
+ if (existingMappings.get(pnUser) === lidUser) reverseKeysToCheck.push(`${lidUser}_reverse`)
62
+ }
63
+ if (reverseKeysToCheck.length) {
64
+ const storedReverse = await this.keys.get('lid-mapping', reverseKeysToCheck)
65
+ for (const key of reverseKeysToCheck) {
66
+ if (storedReverse[key]) existingReverse.set(key, storedReverse[key])
67
+ }
68
+ }
69
+
70
+ const pairMap = {}
71
+ for (const { pnUser, lidUser } of validatedPairs) {
72
+ const forwardExists = existingMappings.get(pnUser) === lidUser
73
+ const reverseExists = existingReverse.has(`${lidUser}_reverse`)
74
+ if (forwardExists && reverseExists) {
75
+ continue
76
+ }
77
+ if (forwardExists && !reverseExists) {
78
+ this.logger.debug({ pnUser, lidUser }, 'forward mapping exists but reverse is missing, repairing')
79
+ }
80
+ pairMap[pnUser] = lidUser
81
+ }
82
+ if (!Object.keys(pairMap).length) return
83
+
84
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`)
85
+
86
+ // Single batched keys.set inside transaction
87
+ const batchData = {}
88
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
89
+ batchData[pnUser] = lidUser
90
+ batchData[`${lidUser}_reverse`] = pnUser
91
+ }
92
+
93
+ await this.keys.transaction(async () => {
94
+ await this.keys.set({ 'lid-mapping': batchData })
95
+ }, 'lid-mapping')
96
+
97
+ // Update cache only after successful DB write
98
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
99
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
100
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
101
+ }
102
+ }
103
+
104
+ async getLIDForPN(pn) {
105
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null
106
+ }
107
+
108
+ async getLIDsForPNs(pns) {
109
+ if (!pns.length) return null
110
+ const sortedPns = [...new Set(pns)].sort()
111
+ const cacheKey = sortedPns.join(',')
112
+
113
+ const inflight = this.inflightLIDLookups.get(cacheKey)
114
+ if (inflight) {
115
+ this.logger.trace(`Coalescing getLIDsForPNs for ${sortedPns.length} PNs`)
116
+ return inflight
117
+ }
118
+
119
+ const promise = this._getLIDsForPNsImpl(pns)
120
+ this.inflightLIDLookups.set(cacheKey, promise)
121
+ try {
122
+ return await promise
123
+ } finally {
124
+ this.inflightLIDLookups.delete(cacheKey)
125
+ }
126
+ }
127
+
128
+ async _getLIDsForPNsImpl(pns) {
129
+ const usyncFetch = {}
130
+ const successfulPairs = {}
131
+ const pending = []
132
+
133
+ const addResolvedPair = (pn, decoded, lidUser) => {
134
+ const normalizedLidUser = lidUser.toString()
135
+ if (!normalizedLidUser) {
136
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`)
137
+ return false
138
+ }
139
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0
140
+ const deviceSpecificLid = `${normalizedLidUser}${pnDevice ? `:${pnDevice}` : ''}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`
141
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`)
142
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn }
143
+ return true
144
+ }
145
+
146
+ for (const pn of pns) {
147
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) continue
148
+ const decoded = jidDecode(pn)
149
+ if (!decoded) continue
150
+ const pnUser = decoded.user
151
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
152
+ if (cached) {
153
+ addResolvedPair(pn, decoded, cached)
154
+ } else {
155
+ pending.push({ pn, pnUser, decoded })
156
+ }
157
+ }
158
+
159
+ if (pending.length) {
160
+ // Single batched DB fetch for all cache misses
161
+ const pnUsers = [...new Set(pending.map(p => p.pnUser))]
162
+ const stored = await this.keys.get('lid-mapping', pnUsers)
163
+
164
+ for (const pnUser of pnUsers) {
165
+ const lidUser = stored[pnUser]
166
+ if (lidUser) {
167
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
168
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
169
+ }
170
+ }
171
+
172
+ for (const { pn, pnUser, decoded } of pending) {
173
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
174
+ if (cached) {
175
+ addResolvedPair(pn, decoded, cached)
176
+ } else {
177
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`)
178
+ const device = decoded.device || 0
179
+ let normalizedPn = jidNormalizedUser(pn)
180
+ if (isHostedPnUser(normalizedPn)) normalizedPn = `${pnUser}@s.whatsapp.net`
181
+ if (!usyncFetch[normalizedPn]) usyncFetch[normalizedPn] = [device]
182
+ else usyncFetch[normalizedPn].push(device)
183
+ }
184
+ }
185
+ }
186
+
187
+ if (Object.keys(usyncFetch).length > 0) {
188
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch))
189
+ if (result?.length > 0) {
190
+ await this.storeLIDPNMappings(result) // fixed: was fire-and-forget
191
+ for (const pair of result) {
192
+ const pnDecoded = jidDecode(pair.pn)
193
+ const pnUser = pnDecoded?.user
194
+ if (!pnUser) continue
195
+ const lidUser = jidDecode(pair.lid)?.user
196
+ if (!lidUser) continue
197
+ for (const device of usyncFetch[pair.pn] || []) {
198
+ const deviceSpecificLid = `${lidUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted.lid' : 'lid'}`
199
+ const deviceSpecificPn = `${pnUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`
200
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`)
201
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn }
202
+ }
203
+ }
204
+ } else {
205
+ return null
206
+ }
207
+ }
208
+
209
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null
210
+ }
211
+
212
+ async getPNForLID(lid) {
213
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null
214
+ }
215
+
216
+ async getPNsForLIDs(lids) {
217
+ if (!lids.length) return null
218
+ const sortedLids = [...new Set(lids)].sort()
219
+ const cacheKey = sortedLids.join(',')
220
+
221
+ const inflight = this.inflightPNLookups.get(cacheKey)
222
+ if (inflight) {
223
+ this.logger.trace(`Coalescing getPNsForLIDs for ${sortedLids.length} LIDs`)
224
+ return inflight
225
+ }
226
+
227
+ const promise = this._getPNsForLIDsImpl(lids)
228
+ this.inflightPNLookups.set(cacheKey, promise)
229
+ try {
230
+ return await promise
231
+ } finally {
232
+ this.inflightPNLookups.delete(cacheKey)
233
+ }
234
+ }
235
+
236
+ async _getPNsForLIDsImpl(lids) {
237
+ const successfulPairs = {}
238
+ const pending = []
239
+
240
+ const addResolvedPair = (lid, decoded, pnUser) => {
241
+ if (!pnUser || typeof pnUser !== 'string') return false
242
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0
243
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`
244
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`)
245
+ successfulPairs[lid] = { lid, pn: pnJid }
246
+ return true
247
+ }
248
+
249
+ for (const lid of lids) {
250
+ if (!isLidUser(lid)) continue
251
+ const decoded = jidDecode(lid)
252
+ if (!decoded) continue
253
+ const lidUser = decoded.user
254
+ const cached = this.mappingCache.get(`lid:${lidUser}`)
255
+ if (cached) {
256
+ addResolvedPair(lid, decoded, cached)
257
+ } else {
258
+ pending.push({ lid, lidUser, decoded })
259
+ }
260
+ }
261
+
262
+ if (pending.length) {
263
+ // Single batched DB fetch for all cache misses
264
+ const reverseKeys = [...new Set(pending.map(p => `${p.lidUser}_reverse`))]
265
+ const stored = await this.keys.get('lid-mapping', reverseKeys)
266
+
267
+ for (const { lid, lidUser, decoded } of pending) {
268
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`)
269
+ if (!pnUser || typeof pnUser !== 'string') {
270
+ pnUser = stored[`${lidUser}_reverse`]
271
+ if (pnUser && typeof pnUser === 'string') {
272
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
273
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
274
+ }
275
+ }
276
+ if (pnUser) addResolvedPair(lid, decoded, pnUser)
277
+ else this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`)
278
+ }
279
+ }
280
+
281
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null
282
+ }
283
+ }
@@ -0,0 +1,2 @@
1
+ export * from './types.js'
2
+ export * from './websocket.js'
@@ -0,0 +1,10 @@
1
+ import { EventEmitter } from 'events'
2
+
3
+ export class AbstractSocketClient extends EventEmitter {
4
+ constructor(url, config) {
5
+ super()
6
+ this.url = url
7
+ this.config = config
8
+ this.setMaxListeners(0)
9
+ }
10
+ }
@@ -0,0 +1,84 @@
1
+ import WebSocket from 'ws'
2
+ import { DEFAULT_ORIGIN } from '../../Defaults/index.js'
3
+ import { AbstractSocketClient } from './types.js'
4
+
5
+ const MAX_CONNECT_RETRIES = 5
6
+ const BASE_RETRY_DELAY = 1000
7
+
8
+ export class WebSocketClient extends AbstractSocketClient {
9
+ constructor() {
10
+ super(...arguments)
11
+ this.socket = null
12
+ this._connectRetries = 0
13
+ this._connectTimer = null
14
+ this._dead = false
15
+ }
16
+
17
+ get isOpen() { return this.socket?.readyState === WebSocket.OPEN }
18
+ get isClosed() { return this.socket === null || this.socket?.readyState === WebSocket.CLOSED }
19
+ get isClosing() { return this.socket === null || this.socket?.readyState === WebSocket.CLOSING }
20
+ get isConnecting() { return this.socket?.readyState === WebSocket.CONNECTING }
21
+
22
+ connect() {
23
+ if (this.socket || this._dead) return
24
+ this._tryConnect()
25
+ }
26
+
27
+ _tryConnect() {
28
+ if (this._dead) return
29
+ let didOpen = false
30
+ this.socket = new WebSocket(this.url, {
31
+ origin: DEFAULT_ORIGIN,
32
+ headers: this.config.options?.headers,
33
+ handshakeTimeout: this.config.connectTimeoutMs,
34
+ timeout: this.config.connectTimeoutMs,
35
+ agent: this.config.agent,
36
+ family: 4,
37
+ })
38
+ this.socket.setMaxListeners(0)
39
+
40
+ for (const event of ['close', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response']) {
41
+ this.socket.on(event, (...args) => this.emit(event, ...args))
42
+ }
43
+
44
+ this.socket.once('open', () => {
45
+ didOpen = true
46
+ this._connectRetries = 0
47
+ })
48
+
49
+ this.socket.on('error', (err) => {
50
+ const isConnectError = !didOpen && ['ETIMEDOUT', 'ECONNREFUSED', 'ENETUNREACH', 'ENOTFOUND', 'EAI_AGAIN'].includes(err.code)
51
+ if (isConnectError && this._connectRetries < MAX_CONNECT_RETRIES) {
52
+ this._connectRetries++
53
+ const delay = Math.min(BASE_RETRY_DELAY * Math.pow(2, this._connectRetries - 1), 30000)
54
+ this.socket = null
55
+ this._connectTimer = setTimeout(() => this._tryConnect(), delay)
56
+ } else {
57
+ this.emit('error', err)
58
+ }
59
+ })
60
+ }
61
+
62
+ async close() {
63
+ this._dead = true
64
+ clearTimeout(this._connectTimer)
65
+ if (!this.socket) return
66
+ const closePromise = new Promise(resolve => { this.socket?.once('close', resolve) })
67
+ this.socket.close()
68
+ await closePromise
69
+ this.socket = null
70
+ }
71
+
72
+ reset() {
73
+ this._dead = false
74
+ this._connectRetries = 0
75
+ clearTimeout(this._connectTimer)
76
+ }
77
+
78
+ send(str, cb) {
79
+ this.socket?.send(str, cb)
80
+ return Boolean(this.socket)
81
+ }
82
+ }
83
+
84
+ export default WebSocketClient
@@ -0,0 +1,152 @@
1
+ import { parseCatalogNode, getRawMediaUploadData, parseCollectionsNode, parseOrderDetailsNode, parseProductNode, toProductNode, uploadingNecessaryImagesOfProduct } from '../Utils/index.js'
2
+ import { jidNormalizedUser, S_WHATSAPP_NET, getBinaryNodeChild } from '../WABinary/index.js'
3
+ import { makeMessagesRecvSocket } from './messages-recv.js'
4
+
5
+ export const makeBusinessSocket = (config) => {
6
+ const sock = makeMessagesRecvSocket(config)
7
+ const { authState, query, waUploadToServer } = sock
8
+
9
+ const updateBussinesProfile = async (args) => {
10
+ const node = []
11
+ for (const key of ['address', 'email', 'description']) {
12
+ if (args[key]) node.push({ tag: key, attrs: {}, content: args[key] })
13
+ }
14
+ if (args.websites) {
15
+ node.push(...args.websites.map(website => ({ tag: 'website', attrs: {}, content: website })))
16
+ }
17
+ if (args.hours) {
18
+ node.push({
19
+ tag: 'business_hours',
20
+ attrs: { timezone: args.hours.timezone },
21
+ content: args.hours.days.map(cfg => {
22
+ const base = { tag: 'business_hours_config', attrs: { day_of_week: cfg.day, mode: cfg.mode } }
23
+ if (cfg.mode === 'specific_hours') {
24
+ return { ...base, attrs: { ...base.attrs, open_time: cfg.openTimeInMinutes, close_time: cfg.closeTimeInMinutes } }
25
+ }
26
+ return base
27
+ })
28
+ })
29
+ }
30
+ return query({
31
+ tag: 'iq',
32
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:biz' },
33
+ content: [{ tag: 'business_profile', attrs: { v: '3', mutation_type: 'delta' }, content: node }]
34
+ })
35
+ }
36
+
37
+ const updateCoverPhoto = async (photo) => {
38
+ const { fileSha256, filePath } = await getRawMediaUploadData(photo, 'biz-cover-photo')
39
+ const { meta_hmac, fbid, ts } = await waUploadToServer(filePath, {
40
+ fileEncSha256B64: fileSha256.toString('base64'),
41
+ mediaType: 'biz-cover-photo'
42
+ })
43
+ await query({
44
+ tag: 'iq',
45
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:biz' },
46
+ content: [{ tag: 'business_profile', attrs: { v: '3', mutation_type: 'delta' }, content: [{ tag: 'cover_photo', attrs: { id: String(fbid), op: 'update', token: meta_hmac, ts: String(ts) } }] }]
47
+ })
48
+ return fbid
49
+ }
50
+
51
+ const removeCoverPhoto = async (id) =>
52
+ query({
53
+ tag: 'iq',
54
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:biz' },
55
+ content: [{ tag: 'business_profile', attrs: { v: '3', mutation_type: 'delta' }, content: [{ tag: 'cover_photo', attrs: { op: 'delete', id } }] }]
56
+ })
57
+
58
+ const getCatalog = async ({ jid, limit, cursor } = {}) => {
59
+ jid = jidNormalizedUser(jid || authState.creds.me?.id)
60
+ const queryParamNodes = [
61
+ { tag: 'limit', attrs: {}, content: Buffer.from((limit || 10).toString()) },
62
+ { tag: 'width', attrs: {}, content: Buffer.from('100') },
63
+ { tag: 'height', attrs: {}, content: Buffer.from('100') }
64
+ ]
65
+ if (cursor) queryParamNodes.push({ tag: 'after', attrs: {}, content: cursor })
66
+ const result = await query({
67
+ tag: 'iq',
68
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:biz:catalog' },
69
+ content: [{ tag: 'product_catalog', attrs: { jid, allow_shop_source: 'true' }, content: queryParamNodes }]
70
+ })
71
+ return parseCatalogNode(result)
72
+ }
73
+
74
+ const getCollections = async (jid, limit = 51) => {
75
+ jid = jidNormalizedUser(jid || authState.creds.me?.id)
76
+ const result = await query({
77
+ tag: 'iq',
78
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:biz:catalog', smax_id: '35' },
79
+ content: [{
80
+ tag: 'collections',
81
+ attrs: { biz_jid: jid },
82
+ content: [
83
+ { tag: 'collection_limit', attrs: {}, content: Buffer.from(limit.toString()) },
84
+ { tag: 'item_limit', attrs: {}, content: Buffer.from(limit.toString()) },
85
+ { tag: 'width', attrs: {}, content: Buffer.from('100') },
86
+ { tag: 'height', attrs: {}, content: Buffer.from('100') }
87
+ ]
88
+ }]
89
+ })
90
+ return parseCollectionsNode(result)
91
+ }
92
+
93
+ const getOrderDetails = async (orderId, tokenBase64) => {
94
+ const result = await query({
95
+ tag: 'iq',
96
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'fb:thrift_iq', smax_id: '5' },
97
+ content: [{
98
+ tag: 'order',
99
+ attrs: { op: 'get', id: orderId },
100
+ content: [
101
+ { tag: 'image_dimensions', attrs: {}, content: [{ tag: 'width', attrs: {}, content: Buffer.from('100') }, { tag: 'height', attrs: {}, content: Buffer.from('100') }] },
102
+ { tag: 'token', attrs: {}, content: Buffer.from(tokenBase64) }
103
+ ]
104
+ }]
105
+ })
106
+ return parseOrderDetailsNode(result)
107
+ }
108
+
109
+ const productUpdate = async (productId, update) => {
110
+ update = await uploadingNecessaryImagesOfProduct(update, waUploadToServer)
111
+ const result = await query({
112
+ tag: 'iq',
113
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:biz:catalog' },
114
+ content: [{ tag: 'product_catalog_edit', attrs: { v: '1' }, content: [toProductNode(productId, update), { tag: 'width', attrs: {}, content: '100' }, { tag: 'height', attrs: {}, content: '100' }] }]
115
+ })
116
+ return parseProductNode(getBinaryNodeChild(getBinaryNodeChild(result, 'product_catalog_edit'), 'product'))
117
+ }
118
+
119
+ const productCreate = async (create) => {
120
+ create.isHidden = !!create.isHidden
121
+ create = await uploadingNecessaryImagesOfProduct(create, waUploadToServer)
122
+ const result = await query({
123
+ tag: 'iq',
124
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:biz:catalog' },
125
+ content: [{ tag: 'product_catalog_add', attrs: { v: '1' }, content: [toProductNode(undefined, create), { tag: 'width', attrs: {}, content: '100' }, { tag: 'height', attrs: {}, content: '100' }] }]
126
+ })
127
+ return parseProductNode(getBinaryNodeChild(getBinaryNodeChild(result, 'product_catalog_add'), 'product'))
128
+ }
129
+
130
+ const productDelete = async (productIds) => {
131
+ const result = await query({
132
+ tag: 'iq',
133
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:biz:catalog' },
134
+ content: [{ tag: 'product_catalog_delete', attrs: { v: '1' }, content: productIds.map(id => ({ tag: 'product', attrs: {}, content: [{ tag: 'id', attrs: {}, content: Buffer.from(id) }] })) }]
135
+ })
136
+ return { deleted: +(getBinaryNodeChild(result, 'product_catalog_delete')?.attrs.deleted_count || 0) }
137
+ }
138
+
139
+ return {
140
+ ...sock,
141
+ logger: config.logger,
142
+ getOrderDetails,
143
+ getCatalog,
144
+ getCollections,
145
+ productCreate,
146
+ productDelete,
147
+ productUpdate,
148
+ updateBussinesProfile,
149
+ updateCoverPhoto,
150
+ removeCoverPhoto
151
+ }
152
+ }