@hiroosy/baileys-lite 0.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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,674 @@
1
+ /**
2
+ * Chats socket layer (wraps makeSocket). Combines what used to be Socket/chats.js.
3
+ */
4
+ import { proto } from '../../WAProto/index.js'
5
+ import { Boom } from '../foundation/boom.js'
6
+ import { Cache } from '../foundation/cache.js'
7
+ import { makeMutex } from '../foundation/concurrency.js'
8
+ import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../defaults.js'
9
+ import { ALL_WA_PATCH_NAMES, SyncState } from '../constants.js'
10
+ import {
11
+ chatModificationToAppPatch,
12
+ decodePatches,
13
+ decodeSyncdSnapshot,
14
+ encodeSyncdPatch,
15
+ ensureLTHashStateVersion,
16
+ extractSyncdPatches,
17
+ newLTHashState,
18
+ processSyncAction
19
+ } from '../utils/chat-sync.js'
20
+ import { isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS } from '../utils/chat-sync.js'
21
+ import { generateProfilePicture } from '../utils/media.js'
22
+ import processMessage, { getHistoryMsg } from '../utils/message-processing.js'
23
+ import { buildTcTokenFromJid } from '../utils/auth-state-core.js'
24
+ import {
25
+ getBinaryNodeChild,
26
+ getBinaryNodeChildren,
27
+ isHostedLidUser,
28
+ isHostedPnUser,
29
+ isLidUser,
30
+ isPnUser,
31
+ jidDecode,
32
+ jidNormalizedUser,
33
+ reduceBinaryNodeToDictionary,
34
+ S_WHATSAPP_NET
35
+ } from '../binary/wa-binary.js'
36
+ import { USyncQuery, USyncUser } from './usync.js'
37
+ import { makeSocket } from './socket-core.js'
38
+
39
+ export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
40
+ const picture = { tag: 'picture', attrs: { type, query: 'url' } }
41
+ if (tcTokenContent?.length) picture.content = tcTokenContent
42
+ return [picture]
43
+ }
44
+
45
+ export const makeChatsSocket = config => {
46
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config
47
+ const sock = makeSocket(config)
48
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock
49
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
50
+ let privacySettings
51
+ /** Server-assigned AB props for protocol behavior. */
52
+ const serverProps = {
53
+ privacyTokenOn1to1: true,
54
+ profilePicPrivacyToken: true,
55
+ lidTrustedTokenIssueToLid: false
56
+ }
57
+ let syncState = SyncState.Connecting
58
+ const messageMutex = makeMutex()
59
+ const receiptMutex = makeMutex()
60
+ const appStatePatchMutex = makeMutex()
61
+ const notificationMutex = makeMutex()
62
+ let awaitingSyncTimeout
63
+ const historySyncStatus = { initialBootstrapComplete: false, recentSyncComplete: false }
64
+ let historySyncPausedTimeout
65
+ const blockedCollections = new Set()
66
+ const placeholderResendCache = config.placeholderResendCache || new Cache({ ttl: DEFAULT_CACHE_TTLS.MSG_RETRY * 1000 })
67
+
68
+ const getAppStateSyncKey = async keyId => {
69
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
70
+ return key
71
+ }
72
+ const fetchPrivacySettings = async (force = false) => {
73
+ if (!privacySettings || force) {
74
+ const { content } = await query({ tag: 'iq', attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'get' }, content: [{ tag: 'privacy', attrs: {} }] })
75
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category')
76
+ }
77
+ return privacySettings
78
+ }
79
+ const privacyQuery = async (name, value) => {
80
+ await query({ tag: 'iq', attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'set' }, content: [{ tag: 'privacy', attrs: {}, content: [{ tag: 'category', attrs: { name, value } }] }] })
81
+ }
82
+ const updateMessagesPrivacy = async value => privacyQuery('messages', value)
83
+ const updateCallPrivacy = async value => privacyQuery('calladd', value)
84
+ const updateLastSeenPrivacy = async value => privacyQuery('last', value)
85
+ const updateOnlinePrivacy = async value => privacyQuery('online', value)
86
+ const updateProfilePicturePrivacy = async value => privacyQuery('profile', value)
87
+ const updateStatusPrivacy = async value => privacyQuery('status', value)
88
+ const updateReadReceiptsPrivacy = async value => privacyQuery('readreceipts', value)
89
+ const updateGroupsAddPrivacy = async value => privacyQuery('groupadd', value)
90
+ const updateDefaultDisappearingMode = async duration => {
91
+ await query({ tag: 'iq', attrs: { xmlns: 'disappearing_mode', to: S_WHATSAPP_NET, type: 'set' }, content: [{ tag: 'disappearing_mode', attrs: { duration: duration.toString() } }] })
92
+ }
93
+ const getBotListV2 = async () => {
94
+ const resp = await query({ tag: 'iq', attrs: { xmlns: 'bot', to: S_WHATSAPP_NET, type: 'get' }, content: [{ tag: 'bot', attrs: { v: '2' } }] })
95
+ const botNode = getBinaryNodeChild(resp, 'bot')
96
+ const botList = []
97
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
98
+ if (section.attrs.type === 'all') {
99
+ for (const bot of getBinaryNodeChildren(section, 'bot')) botList.push({ jid: bot.attrs.jid, personaId: bot.attrs['persona_id'] })
100
+ }
101
+ }
102
+ return botList
103
+ }
104
+ const fetchStatus = async (...jids) => {
105
+ const usyncQuery = new USyncQuery().withStatusProtocol()
106
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
107
+ const result = await sock.executeUSyncQuery(usyncQuery)
108
+ if (result) return result.list
109
+ }
110
+ const fetchDisappearingDuration = async (...jids) => {
111
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol()
112
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
113
+ const result = await sock.executeUSyncQuery(usyncQuery)
114
+ if (result) return result.list
115
+ }
116
+ const findUserId = async pnLid => {
117
+ const normalizedJid = jidNormalizedUser(pnLid)
118
+ const userId = { lid: undefined, phoneNumber: undefined }
119
+ if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
120
+ userId.phoneNumber = normalizedJid
121
+ userId.lid = jidNormalizedUser((await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid)
122
+ } else if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
123
+ userId.lid = normalizedJid
124
+ userId.phoneNumber = jidNormalizedUser((await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn)
125
+ } else {
126
+ throw new Boom('Invalid id input to find user ids', { statusCode: 400 })
127
+ }
128
+ return userId
129
+ }
130
+ /** update the profile picture for yourself or a group */
131
+ const updateProfilePicture = async (jid, content, dimensions) => {
132
+ let targetJid
133
+ if (!jid) throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
134
+ targetJid = jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id) ? jidNormalizedUser(jid) : undefined
135
+ const { img } = await generateProfilePicture(content, dimensions)
136
+ await query({
137
+ tag: 'iq',
138
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) },
139
+ content: [{ tag: 'picture', attrs: { type: 'image' }, content: img }]
140
+ })
141
+ }
142
+ /** remove the profile picture for yourself or a group */
143
+ const removeProfilePicture = async jid => {
144
+ let targetJid
145
+ if (!jid) throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
146
+ targetJid = jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id) ? jidNormalizedUser(jid) : undefined
147
+ await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) } })
148
+ }
149
+ const updateProfileStatus = async status => {
150
+ await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'status' }, content: [{ tag: 'status', attrs: {}, content: Buffer.from(status, 'utf-8') }] })
151
+ }
152
+ const updateProfileName = async name => chatModify({ pushNameSetting: name }, '')
153
+ const fetchBlocklist = async () => {
154
+ const result = await query({ tag: 'iq', attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'get' } })
155
+ const listNode = getBinaryNodeChild(result, 'list')
156
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid)
157
+ }
158
+ const updateBlockStatus = async (jid, action) => {
159
+ const normalizedJid = jidNormalizedUser(jid)
160
+ let lid, pn_jid
161
+ if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
162
+ lid = normalizedJid
163
+ if (action === 'block') {
164
+ const pn = (await findUserId(normalizedJid)).phoneNumber
165
+ if (!pn) throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 })
166
+ pn_jid = jidNormalizedUser(pn)
167
+ }
168
+ } else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
169
+ const mapped = (await findUserId(normalizedJid)).lid
170
+ if (!mapped) throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 })
171
+ lid = mapped
172
+ if (action === 'block') pn_jid = jidNormalizedUser(normalizedJid)
173
+ } else {
174
+ throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 })
175
+ }
176
+ const itemAttrs = { action, jid: lid }
177
+ if (action === 'block') {
178
+ if (!pn_jid) throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 })
179
+ itemAttrs.pn_jid = pn_jid
180
+ }
181
+ await query({ tag: 'iq', attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'set' }, content: [{ tag: 'item', attrs: itemAttrs }] })
182
+ }
183
+ const getBusinessProfile = async jid => {
184
+ const results = await query({
185
+ tag: 'iq',
186
+ attrs: { to: 's.whatsapp.net', xmlns: 'w:biz', type: 'get' },
187
+ content: [{ tag: 'business_profile', attrs: { v: '244' }, content: [{ tag: 'profile', attrs: { jid } }] }]
188
+ })
189
+ const profileNode = getBinaryNodeChild(results, 'business_profile')
190
+ const profiles = getBinaryNodeChild(profileNode, 'profile')
191
+ if (profiles) {
192
+ const address = getBinaryNodeChild(profiles, 'address')
193
+ const description = getBinaryNodeChild(profiles, 'description')
194
+ const website = getBinaryNodeChild(profiles, 'website')
195
+ const email = getBinaryNodeChild(profiles, 'email')
196
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category')
197
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours')
198
+ const businessHoursConfig = businessHours ? getBinaryNodeChildren(businessHours, 'business_hours_config') : undefined
199
+ const websiteStr = website?.content?.toString()
200
+ return {
201
+ wid: profiles.attrs?.jid,
202
+ address: address?.content?.toString(),
203
+ description: description?.content?.toString() || '',
204
+ website: websiteStr ? [websiteStr] : [],
205
+ email: email?.content?.toString(),
206
+ category: category?.content?.toString(),
207
+ business_hours: { timezone: businessHours?.attrs?.timezone, business_config: businessHoursConfig?.map(({ attrs }) => attrs) }
208
+ }
209
+ }
210
+ }
211
+ const cleanDirtyBits = async (type, fromTimestamp) => {
212
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
213
+ await sendNode({
214
+ tag: 'iq',
215
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'urn:xmpp:whatsapp:dirty', id: generateMessageTag() },
216
+ content: [{ tag: 'clean', attrs: { type, ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null) } }]
217
+ })
218
+ }
219
+ const newAppStateChunkHandler = isInitialSync => ({
220
+ onMutation(mutation) {
221
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
222
+ }
223
+ })
224
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
225
+ const appStateSyncKeyCache = new Map()
226
+ const getCachedAppStateSyncKey = async keyId => {
227
+ if (appStateSyncKeyCache.has(keyId)) return appStateSyncKeyCache.get(keyId) ?? undefined
228
+ const key = await getAppStateSyncKey(keyId)
229
+ appStateSyncKeyCache.set(keyId, key ?? null)
230
+ return key
231
+ }
232
+ const initialVersionMap = {}
233
+ const globalMutationMap = {}
234
+ await authState.keys.transaction(async () => {
235
+ const collectionsToHandle = new Set(collections)
236
+ const attemptsMap = {}
237
+ const forceSnapshotCollections = new Set()
238
+ while (collectionsToHandle.size) {
239
+ const states = {}
240
+ const nodes = []
241
+ for (const name of collectionsToHandle) {
242
+ const result = await authState.keys.get('app-state-sync-version', [name])
243
+ let state = result[name]
244
+ if (state) {
245
+ state = ensureLTHashStateVersion(state)
246
+ if (typeof initialVersionMap[name] === 'undefined') initialVersionMap[name] = state.version
247
+ } else {
248
+ state = newLTHashState()
249
+ }
250
+ states[name] = state
251
+ const shouldForceSnapshot = forceSnapshotCollections.has(name)
252
+ if (shouldForceSnapshot) forceSnapshotCollections.delete(name)
253
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`)
254
+ nodes.push({ tag: 'collection', attrs: { name, version: state.version.toString(), return_snapshot: (shouldForceSnapshot || !state.version).toString() } })
255
+ }
256
+ const result = await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, xmlns: 'w:sync:app:state', type: 'set' }, content: [{ tag: 'sync', attrs: {}, content: nodes }] })
257
+ const decoded = await extractSyncdPatches(result, config?.options)
258
+ for (const key in decoded) {
259
+ const name = key
260
+ const { patches, hasMorePatches, snapshot } = decoded[name]
261
+ try {
262
+ if (snapshot) {
263
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger)
264
+ states[name] = newState
265
+ Object.assign(globalMutationMap, mutationMap)
266
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
267
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
268
+ }
269
+ if (patches.length) {
270
+ const { state: newState, mutationMap } = await decodePatches(
271
+ name,
272
+ patches,
273
+ states[name],
274
+ getCachedAppStateSyncKey,
275
+ config.options,
276
+ initialVersionMap[name],
277
+ logger,
278
+ appStateMacVerification.patch
279
+ )
280
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
281
+ logger.info(`synced ${name} to v${newState.version}`)
282
+ initialVersionMap[name] = newState.version
283
+ Object.assign(globalMutationMap, mutationMap)
284
+ }
285
+ if (hasMorePatches) logger.info(`${name} has more patches...`)
286
+ else collectionsToHandle.delete(name)
287
+ } catch (error) {
288
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
289
+ const logData = { name, attempt: attemptsMap[name], version: states[name].version, statusCode: error.output?.statusCode, errorType: error.name, error: error.stack }
290
+ if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
291
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`)
292
+ blockedCollections.add(name)
293
+ collectionsToHandle.delete(name)
294
+ } else if (isMissingKeyError(error)) {
295
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`)
296
+ forceSnapshotCollections.add(name)
297
+ } else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
298
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`)
299
+ collectionsToHandle.delete(name)
300
+ } else {
301
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`)
302
+ forceSnapshotCollections.add(name)
303
+ }
304
+ }
305
+ }
306
+ }
307
+ }, authState?.creds?.me?.id || 'resync-app-state')
308
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
309
+ for (const key in globalMutationMap) onMutation(globalMutationMap[key])
310
+ })
311
+ /** fetch the profile picture of a user/group */
312
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = true) => {
313
+ const normalizedJid = jidNormalizedUser(jid)
314
+ const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid)
315
+ const me = authState.creds.me
316
+ const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)))
317
+ let tcTokenContent
318
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
319
+ tcTokenContent = await buildTcTokenFromJid({ authState, jid: normalizedJid, getLIDForPN })
320
+ }
321
+ jid = jidNormalizedUser(jid)
322
+ const result = await query(
323
+ { tag: 'iq', attrs: { target: jid, to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:profile:picture' }, content: buildProfilePictureQueryContent(type, tcTokenContent) },
324
+ timeoutMs
325
+ )
326
+ const child = getBinaryNodeChild(result, 'picture')
327
+ return child?.attrs?.url
328
+ }
329
+ const createCallLink = async (type, event, timeoutMs) => {
330
+ const result = await query(
331
+ { tag: 'call', attrs: { id: generateMessageTag(), to: '@call' }, content: [{ tag: 'link_create', attrs: { media: type }, content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined }] },
332
+ timeoutMs
333
+ )
334
+ const child = getBinaryNodeChild(result, 'link_create')
335
+ return child?.attrs?.token
336
+ }
337
+ const sendPresenceUpdate = async (type, toJid) => {
338
+ const me = authState.creds.me
339
+ const isAvailableType = type === 'available'
340
+ if (isAvailableType || type === 'unavailable') {
341
+ if (!me.name) {
342
+ logger.warn('no name present, ignoring presence update request...')
343
+ return
344
+ }
345
+ ev.emit('connection.update', { isOnline: isAvailableType })
346
+ if (isAvailableType) void sendUnifiedSession()
347
+ await sendNode({ tag: 'presence', attrs: { name: me.name.replace(/@/g, ''), type } })
348
+ } else {
349
+ const { server } = jidDecode(toJid)
350
+ const isLid = server === 'lid'
351
+ await sendNode({ tag: 'chatstate', attrs: { from: isLid ? me.lid : me.id, to: toJid }, content: [{ tag: type === 'recording' ? 'composing' : type, attrs: type === 'recording' ? { media: 'audio' } : {} }] })
352
+ }
353
+ }
354
+ const presenceSubscribe = async toJid => {
355
+ const normalizedToJid = jidNormalizedUser(toJid)
356
+ const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid)
357
+ const tcTokenContent = isUserJid ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN }) : undefined
358
+ return sendNode({ tag: 'presence', attrs: { to: toJid, id: generateMessageTag(), type: 'subscribe' }, content: tcTokenContent })
359
+ }
360
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
361
+ let presence
362
+ const jid = attrs.from
363
+ const participant = attrs.participant || attrs.from
364
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) return
365
+ if (tag === 'presence') {
366
+ presence = { lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available', lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined, groupOnlineCount: attrs.count ? +attrs.count : undefined }
367
+ } else if (Array.isArray(content)) {
368
+ const [firstChild] = content
369
+ let type = firstChild.tag
370
+ if (type === 'paused') type = 'available'
371
+ if (firstChild.attrs?.media === 'audio') type = 'recording'
372
+ presence = { lastKnownPresence: type }
373
+ } else {
374
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
375
+ }
376
+ if (presence) ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
377
+ }
378
+ const appPatch = async patchCreate => {
379
+ const name = patchCreate.type
380
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
381
+ if (!myAppStateKeyId) throw new Boom('App state key not present!', { statusCode: 400 })
382
+ let initial, encodeResult
383
+ await appStatePatchMutex.mutex(async () => {
384
+ await authState.keys.transaction(async () => {
385
+ logger.debug({ patch: patchCreate }, 'applying app patch')
386
+ await resyncAppState([name], false)
387
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
388
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState()
389
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
390
+ const { patch, state } = encodeResult
391
+ const node = {
392
+ tag: 'iq',
393
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:sync:app:state' },
394
+ content: [
395
+ {
396
+ tag: 'sync',
397
+ attrs: {},
398
+ content: [{ tag: 'collection', attrs: { name, version: (state.version - 1).toString(), return_snapshot: 'false' }, content: [{ tag: 'patch', attrs: {}, content: proto.SyncdPatch.encode(patch).finish() }] }]
399
+ }
400
+ ]
401
+ }
402
+ await query(node)
403
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
404
+ }, authState?.creds?.me?.id || 'app-patch')
405
+ })
406
+ if (config.emitOwnEvents) {
407
+ const { onMutation } = newAppStateChunkHandler(false)
408
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger)
409
+ for (const key in mutationMap) onMutation(mutationMap[key])
410
+ }
411
+ }
412
+ /** fetch AB props */
413
+ const fetchProps = async () => {
414
+ const resultNode = await query({
415
+ tag: 'iq',
416
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'abt', type: 'get' },
417
+ content: [{ tag: 'props', attrs: { protocol: '1', ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {}) } }]
418
+ })
419
+ const propsNode = getBinaryNodeChild(resultNode, 'props')
420
+ let props = {}
421
+ if (propsNode) {
422
+ if (propsNode.attrs?.hash) {
423
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
424
+ ev.emit('creds.update', authState.creds)
425
+ }
426
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop')
427
+ }
428
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages']
429
+ if (privacyTokenProp !== undefined) serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1'
430
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq']
431
+ if (profilePicProp !== undefined) serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1'
432
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid']
433
+ if (lidIssueProp !== undefined) serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1'
434
+ logger.debug({ serverProps }, 'fetched props')
435
+ return props
436
+ }
437
+ const chatModify = (mod, jid) => appPatch(chatModificationToAppPatch(mod, jid))
438
+ const updateDisableLinkPreviewsPrivacy = isPreviewsDisabled => chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '')
439
+ const star = (jid, messages, star) => chatModify({ star: { messages, star } }, jid)
440
+ const addOrEditContact = (jid, contact) => chatModify({ contact }, jid)
441
+ const removeContact = jid => chatModify({ contact: null }, jid)
442
+ const addLabel = (jid, labels) => chatModify({ addLabel: { ...labels } }, jid)
443
+ const addChatLabel = (jid, labelId) => chatModify({ addChatLabel: { labelId } }, jid)
444
+ const removeChatLabel = (jid, labelId) => chatModify({ removeChatLabel: { labelId } }, jid)
445
+ const addMessageLabel = (jid, messageId, labelId) => chatModify({ addMessageLabel: { messageId, labelId } }, jid)
446
+ const removeMessageLabel = (jid, messageId, labelId) => chatModify({ removeMessageLabel: { messageId, labelId } }, jid)
447
+ const addOrEditQuickReply = quickReply => chatModify({ quickReply }, '')
448
+ const removeQuickReply = timestamp => chatModify({ quickReply: { timestamp, deleted: true } }, '')
449
+ const executeInitQueries = async () => {
450
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()])
451
+ }
452
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
453
+ ev.emit('messages.upsert', { messages: [msg], type })
454
+ if (!!msg.pushName) {
455
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid
456
+ jid = jidNormalizedUser(jid)
457
+ if (!msg.key.fromMe) ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
458
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
459
+ }
460
+ const historyMsg = getHistoryMsg(msg.message)
461
+ const shouldProcessHistoryMsg = historyMsg ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType) : false
462
+ if (historyMsg && shouldProcessHistoryMsg) {
463
+ const syncType = historyMsg.syncType
464
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP && !historySyncStatus.initialBootstrapComplete) {
465
+ historySyncStatus.initialBootstrapComplete = true
466
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
467
+ }
468
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && historyMsg.progress === 100 && !historySyncStatus.recentSyncComplete) {
469
+ historySyncStatus.recentSyncComplete = true
470
+ clearTimeout(historySyncPausedTimeout)
471
+ historySyncPausedTimeout = undefined
472
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
473
+ }
474
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
475
+ clearTimeout(historySyncPausedTimeout)
476
+ historySyncPausedTimeout = setTimeout(() => {
477
+ if (!historySyncStatus.recentSyncComplete) {
478
+ historySyncStatus.recentSyncComplete = true
479
+ ev.emit('messaging-history.status', { syncType: proto.HistorySync.HistorySyncType.RECENT, status: 'paused', explicit: false })
480
+ }
481
+ historySyncPausedTimeout = undefined
482
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS)
483
+ }
484
+ }
485
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
486
+ if (awaitingSyncTimeout) {
487
+ clearTimeout(awaitingSyncTimeout)
488
+ awaitingSyncTimeout = undefined
489
+ }
490
+ if (shouldProcessHistoryMsg) {
491
+ syncState = SyncState.Syncing
492
+ logger.info('Transitioned to Syncing state')
493
+ } else {
494
+ syncState = SyncState.Online
495
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
496
+ ev.flush()
497
+ }
498
+ }
499
+ const doAppStateSync = async () => {
500
+ if (syncState === SyncState.Syncing) {
501
+ blockedCollections.clear()
502
+ logger.info('Doing app state sync')
503
+ await resyncAppState(ALL_WA_PATCH_NAMES, true)
504
+ syncState = SyncState.Online
505
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
506
+ ev.flush()
507
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
508
+ ev.emit('creds.update', { accountSyncCounter })
509
+ }
510
+ }
511
+ await Promise.all([
512
+ (async () => {
513
+ if (shouldProcessHistoryMsg) await doAppStateSync()
514
+ })(),
515
+ processMessage(msg, {
516
+ signalRepository,
517
+ shouldProcessHistoryMsg,
518
+ placeholderResendCache,
519
+ ev,
520
+ creds: authState.creds,
521
+ keyStore: authState.keys,
522
+ logger,
523
+ options: config.options,
524
+ getMessage
525
+ })
526
+ ])
527
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
528
+ logger.info('App state sync key arrived, triggering app state sync')
529
+ await doAppStateSync()
530
+ }
531
+ })
532
+ ws.on('CB:presence', handlePresenceUpdate)
533
+ ws.on('CB:chatstate', handlePresenceUpdate)
534
+ ws.on('CB:ib,,dirty', async node => {
535
+ const { attrs } = getBinaryNodeChild(node, 'dirty')
536
+ const type = attrs.type
537
+ switch (type) {
538
+ case 'account_sync':
539
+ if (attrs.timestamp) {
540
+ let { lastAccountSyncTimestamp } = authState.creds
541
+ if (lastAccountSyncTimestamp) await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
542
+ lastAccountSyncTimestamp = +attrs.timestamp
543
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
544
+ }
545
+ break
546
+ case 'groups':
547
+ break
548
+ default:
549
+ logger.info({ node }, 'received unknown sync')
550
+ break
551
+ }
552
+ })
553
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
554
+ if (connection === 'close') {
555
+ blockedCollections.clear()
556
+ clearTimeout(historySyncPausedTimeout)
557
+ historySyncPausedTimeout = undefined
558
+ }
559
+ if (connection === 'open') {
560
+ if (fireInitQueries) executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
561
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'))
562
+ }
563
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) return
564
+ historySyncStatus.initialBootstrapComplete = false
565
+ historySyncStatus.recentSyncComplete = false
566
+ clearTimeout(historySyncPausedTimeout)
567
+ historySyncPausedTimeout = undefined
568
+ syncState = SyncState.AwaitingInitialSync
569
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
570
+ ev.buffer()
571
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({ syncType: proto.HistorySync.HistorySyncType.RECENT }))
572
+ if (!willSyncHistory) {
573
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
574
+ syncState = SyncState.Online
575
+ setTimeout(() => ev.flush(), 0)
576
+ return
577
+ }
578
+ if (authState.creds.accountSyncCounter > 0) {
579
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.')
580
+ syncState = SyncState.Online
581
+ setTimeout(() => ev.flush(), 0)
582
+ return
583
+ }
584
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.')
585
+ if (awaitingSyncTimeout) clearTimeout(awaitingSyncTimeout)
586
+ awaitingSyncTimeout = setTimeout(() => {
587
+ if (syncState === SyncState.AwaitingInitialSync) {
588
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
589
+ syncState = SyncState.Online
590
+ ev.flush()
591
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
592
+ ev.emit('creds.update', { accountSyncCounter })
593
+ }
594
+ }, 20000)
595
+ })
596
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
597
+ if (!myAppStateKeyId || blockedCollections.size === 0) return
598
+ if (syncState === SyncState.Syncing) {
599
+ blockedCollections.clear()
600
+ return
601
+ }
602
+ const collections = [...blockedCollections]
603
+ blockedCollections.clear()
604
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections')
605
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'))
606
+ })
607
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
608
+ try {
609
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }])
610
+ } catch (error) {
611
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping')
612
+ }
613
+ })
614
+ registerSocketEndHandler(() => {
615
+ if (awaitingSyncTimeout) {
616
+ clearTimeout(awaitingSyncTimeout)
617
+ awaitingSyncTimeout = undefined
618
+ }
619
+ if (!config.placeholderResendCache && placeholderResendCache.close) placeholderResendCache.close()
620
+ syncState = SyncState.Connecting
621
+ privacySettings = undefined
622
+ })
623
+
624
+ return {
625
+ ...sock,
626
+ findUserId,
627
+ serverProps,
628
+ createCallLink,
629
+ getBotListV2,
630
+ messageMutex,
631
+ receiptMutex,
632
+ appStatePatchMutex,
633
+ notificationMutex,
634
+ fetchPrivacySettings,
635
+ upsertMessage,
636
+ appPatch,
637
+ sendPresenceUpdate,
638
+ presenceSubscribe,
639
+ profilePictureUrl,
640
+ fetchBlocklist,
641
+ fetchStatus,
642
+ fetchDisappearingDuration,
643
+ updateProfilePicture,
644
+ removeProfilePicture,
645
+ updateProfileStatus,
646
+ updateProfileName,
647
+ updateBlockStatus,
648
+ updateDisableLinkPreviewsPrivacy,
649
+ updateCallPrivacy,
650
+ updateMessagesPrivacy,
651
+ updateLastSeenPrivacy,
652
+ updateOnlinePrivacy,
653
+ updateProfilePicturePrivacy,
654
+ updateStatusPrivacy,
655
+ updateReadReceiptsPrivacy,
656
+ updateGroupsAddPrivacy,
657
+ updateDefaultDisappearingMode,
658
+ getBusinessProfile,
659
+ resyncAppState,
660
+ chatModify,
661
+ cleanDirtyBits,
662
+ addOrEditContact,
663
+ removeContact,
664
+ placeholderResendCache,
665
+ addLabel,
666
+ addChatLabel,
667
+ removeChatLabel,
668
+ addMessageLabel,
669
+ removeMessageLabel,
670
+ star,
671
+ addOrEditQuickReply,
672
+ removeQuickReply
673
+ }
674
+ }