@nexustechpro/baileys 2.0.2 → 2.0.5

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 (102) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +924 -1299
  3. package/lib/Defaults/baileys-version.json +6 -2
  4. package/lib/Defaults/index.js +172 -172
  5. package/lib/Signal/libsignal.js +380 -292
  6. package/lib/Signal/lid-mapping.js +264 -171
  7. package/lib/Socket/Client/index.js +2 -2
  8. package/lib/Socket/Client/types.js +10 -10
  9. package/lib/Socket/Client/websocket.js +45 -310
  10. package/lib/Socket/business.js +375 -375
  11. package/lib/Socket/chats.js +909 -963
  12. package/lib/Socket/communities.js +430 -430
  13. package/lib/Socket/groups.js +342 -342
  14. package/lib/Socket/index.js +22 -22
  15. package/lib/Socket/messages-recv.js +777 -743
  16. package/lib/Socket/messages-send.js +295 -305
  17. package/lib/Socket/mex.js +50 -50
  18. package/lib/Socket/newsletter.js +148 -148
  19. package/lib/Socket/nexus-handler.js +75 -261
  20. package/lib/Socket/socket.js +709 -1201
  21. package/lib/Store/index.js +5 -5
  22. package/lib/Store/make-cache-manager-store.js +81 -81
  23. package/lib/Store/make-in-memory-store.js +416 -416
  24. package/lib/Store/make-ordered-dictionary.js +81 -81
  25. package/lib/Store/object-repository.js +30 -30
  26. package/lib/Types/Auth.js +1 -1
  27. package/lib/Types/Bussines.js +1 -1
  28. package/lib/Types/Call.js +1 -1
  29. package/lib/Types/Chat.js +7 -7
  30. package/lib/Types/Contact.js +1 -1
  31. package/lib/Types/Events.js +1 -1
  32. package/lib/Types/GroupMetadata.js +1 -1
  33. package/lib/Types/Label.js +24 -24
  34. package/lib/Types/LabelAssociation.js +6 -6
  35. package/lib/Types/Message.js +10 -10
  36. package/lib/Types/Newsletter.js +28 -28
  37. package/lib/Types/Product.js +1 -1
  38. package/lib/Types/Signal.js +1 -1
  39. package/lib/Types/Socket.js +2 -2
  40. package/lib/Types/State.js +12 -12
  41. package/lib/Types/USync.js +1 -1
  42. package/lib/Types/index.js +25 -25
  43. package/lib/Utils/auth-utils.js +264 -256
  44. package/lib/Utils/baileys-event-stream.js +55 -55
  45. package/lib/Utils/browser-utils.js +27 -27
  46. package/lib/Utils/business.js +228 -230
  47. package/lib/Utils/chat-utils.js +694 -764
  48. package/lib/Utils/crypto.js +109 -135
  49. package/lib/Utils/decode-wa-message.js +310 -314
  50. package/lib/Utils/event-buffer.js +547 -547
  51. package/lib/Utils/generics.js +297 -297
  52. package/lib/Utils/history.js +91 -83
  53. package/lib/Utils/index.js +21 -20
  54. package/lib/Utils/key-store.js +17 -0
  55. package/lib/Utils/link-preview.js +97 -98
  56. package/lib/Utils/logger.js +2 -2
  57. package/lib/Utils/lt-hash.js +47 -47
  58. package/lib/Utils/make-mutex.js +39 -39
  59. package/lib/Utils/message-retry-manager.js +148 -148
  60. package/lib/Utils/messages-media.js +534 -534
  61. package/lib/Utils/messages.js +705 -705
  62. package/lib/Utils/noise-handler.js +255 -255
  63. package/lib/Utils/pre-key-manager.js +105 -105
  64. package/lib/Utils/process-message.js +412 -412
  65. package/lib/Utils/signal.js +160 -158
  66. package/lib/Utils/use-multi-file-auth-state.js +120 -120
  67. package/lib/Utils/validate-connection.js +194 -194
  68. package/lib/WABinary/constants.js +1300 -1300
  69. package/lib/WABinary/decode.js +237 -237
  70. package/lib/WABinary/encode.js +232 -232
  71. package/lib/WABinary/generic-utils.js +252 -211
  72. package/lib/WABinary/index.js +5 -5
  73. package/lib/WABinary/jid-utils.js +279 -95
  74. package/lib/WABinary/types.js +1 -1
  75. package/lib/WAM/BinaryInfo.js +9 -9
  76. package/lib/WAM/constants.js +22852 -22852
  77. package/lib/WAM/encode.js +149 -149
  78. package/lib/WAM/index.js +3 -3
  79. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -28
  80. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -53
  81. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -26
  82. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -37
  83. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  84. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -28
  85. package/lib/WAUSync/Protocols/index.js +4 -4
  86. package/lib/WAUSync/USyncQuery.js +93 -93
  87. package/lib/WAUSync/USyncUser.js +22 -22
  88. package/lib/WAUSync/index.js +3 -3
  89. package/lib/index.js +66 -66
  90. package/package.json +171 -144
  91. package/lib/Signal/Group/ciphertext-message.js +0 -12
  92. package/lib/Signal/Group/group-session-builder.js +0 -30
  93. package/lib/Signal/Group/group_cipher.js +0 -100
  94. package/lib/Signal/Group/index.js +0 -12
  95. package/lib/Signal/Group/keyhelper.js +0 -18
  96. package/lib/Signal/Group/sender-chain-key.js +0 -26
  97. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  98. package/lib/Signal/Group/sender-key-message.js +0 -66
  99. package/lib/Signal/Group/sender-key-name.js +0 -48
  100. package/lib/Signal/Group/sender-key-record.js +0 -41
  101. package/lib/Signal/Group/sender-key-state.js +0 -84
  102. package/lib/Signal/Group/sender-message-key.js +0 -26
@@ -1,963 +1,909 @@
1
- import NodeCache from '@cacheable/node-cache';
2
- import { Boom } from '@hapi/boom';
3
- import { proto } from '../../WAProto/index.js';
4
- import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
- import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
- import { SyncState } from '../Types/State.js';
7
- import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
8
- import { makeMutex } from '../Utils/make-mutex.js';
9
- import processMessage from '../Utils/process-message.js';
10
- import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
11
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
- import { makeSocket } from './socket.js';
13
- const MAX_SYNC_ATTEMPTS = 2;
14
- export const makeChatsSocket = (config) => {
15
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage } = config;
16
- const sock = makeSocket(config);
17
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError } = sock;
18
- let privacySettings;
19
- let syncState = SyncState.Connecting;
20
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
21
- const processingMutex = makeMutex();
22
- // Timeout for AwaitingInitialSync state
23
- let awaitingSyncTimeout;
24
- const placeholderResendCache = config.placeholderResendCache ||
25
- new NodeCache({
26
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
27
- useClones: false
28
- });
29
- if (!config.placeholderResendCache) {
30
- config.placeholderResendCache = placeholderResendCache;
31
- }
32
- /** helper function to fetch the given app state sync key */
33
- const getAppStateSyncKey = async (keyId) => {
34
- const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
35
- return key;
36
- };
37
- const fetchPrivacySettings = async (force = false) => {
38
- if (!privacySettings || force) {
39
- const { content } = await query({
40
- tag: 'iq',
41
- attrs: {
42
- xmlns: 'privacy',
43
- to: S_WHATSAPP_NET,
44
- type: 'get'
45
- },
46
- content: [{ tag: 'privacy', attrs: {} }]
47
- });
48
- privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
49
- }
50
- return privacySettings;
51
- };
52
- /** helper function to run a privacy IQ query */
53
- const privacyQuery = async (name, value) => {
54
- await query({
55
- tag: 'iq',
56
- attrs: {
57
- xmlns: 'privacy',
58
- to: S_WHATSAPP_NET,
59
- type: 'set'
60
- },
61
- content: [
62
- {
63
- tag: 'privacy',
64
- attrs: {},
65
- content: [
66
- {
67
- tag: 'category',
68
- attrs: { name, value }
69
- }
70
- ]
71
- }
72
- ]
73
- });
74
- };
75
- const updateMessagesPrivacy = async (value) => {
76
- await privacyQuery('messages', value);
77
- };
78
- const updateCallPrivacy = async (value) => {
79
- await privacyQuery('calladd', value);
80
- };
81
- const updateLastSeenPrivacy = async (value) => {
82
- await privacyQuery('last', value);
83
- };
84
- const updateOnlinePrivacy = async (value) => {
85
- await privacyQuery('online', value);
86
- };
87
- const updateProfilePicturePrivacy = async (value) => {
88
- await privacyQuery('profile', value);
89
- };
90
- const updateStatusPrivacy = async (value) => {
91
- await privacyQuery('status', value);
92
- };
93
- const updateReadReceiptsPrivacy = async (value) => {
94
- await privacyQuery('readreceipts', value);
95
- };
96
- const updateGroupsAddPrivacy = async (value) => {
97
- await privacyQuery('groupadd', value);
98
- };
99
- const updateDefaultDisappearingMode = async (duration) => {
100
- await query({
101
- tag: 'iq',
102
- attrs: {
103
- xmlns: 'disappearing_mode',
104
- to: S_WHATSAPP_NET,
105
- type: 'set'
106
- },
107
- content: [
108
- {
109
- tag: 'disappearing_mode',
110
- attrs: {
111
- duration: duration.toString()
112
- }
113
- }
114
- ]
115
- });
116
- };
117
- const getBotListV2 = async () => {
118
- const resp = await query({
119
- tag: 'iq',
120
- attrs: {
121
- xmlns: 'bot',
122
- to: S_WHATSAPP_NET,
123
- type: 'get'
124
- },
125
- content: [
126
- {
127
- tag: 'bot',
128
- attrs: {
129
- v: '2'
130
- }
131
- }
132
- ]
133
- });
134
- const botNode = getBinaryNodeChild(resp, 'bot');
135
- const botList = [];
136
- for (const section of getBinaryNodeChildren(botNode, 'section')) {
137
- if (section.attrs.type === 'all') {
138
- for (const bot of getBinaryNodeChildren(section, 'bot')) {
139
- botList.push({
140
- jid: bot.attrs.jid,
141
- personaId: bot.attrs['persona_id']
142
- });
143
- }
144
- }
145
- }
146
- return botList;
147
- };
148
- const fetchStatus = async (...jids) => {
149
- const usyncQuery = new USyncQuery().withStatusProtocol();
150
- for (const jid of jids) {
151
- usyncQuery.withUser(new USyncUser().withId(jid));
152
- }
153
- const result = await sock.executeUSyncQuery(usyncQuery);
154
- if (result) {
155
- return result.list;
156
- }
157
- };
158
- const fetchDisappearingDuration = async (...jids) => {
159
- const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
160
- for (const jid of jids) {
161
- usyncQuery.withUser(new USyncUser().withId(jid));
162
- }
163
- const result = await sock.executeUSyncQuery(usyncQuery);
164
- if (result) {
165
- return result.list;
166
- }
167
- };
168
- /** update the profile picture for yourself or a group */
169
- const updateProfilePicture = async (jid, content) => {
170
- let targetJid
171
-
172
- if (!jid) {
173
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
174
- }
175
-
176
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
177
- targetJid = jidNormalizedUser(jid) // in case it is someone other than us
178
- }
179
-
180
- const { img } = await generateProfilePicture(content)
181
-
182
- await query({
183
- tag: 'iq',
184
- attrs: {
185
- target: targetJid,
186
- to: S_WHATSAPP_NET,
187
- type: 'set',
188
- xmlns: 'w:profile:picture'
189
- },
190
- content: [
191
- {
192
- tag: 'picture',
193
- attrs: { type: 'image' },
194
- content: img
195
- }
196
- ]
197
- })
198
- }
199
- /** remove the profile picture for yourself or a group */
200
- const removeProfilePicture = async (jid) => {
201
- let targetJid;
202
- if (!jid) {
203
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
204
- }
205
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
206
- targetJid = jidNormalizedUser(jid); // in case it is someone other than us
207
- }
208
- else {
209
- targetJid = undefined;
210
- }
211
- await query({
212
- tag: 'iq',
213
- attrs: {
214
- to: S_WHATSAPP_NET,
215
- type: 'set',
216
- xmlns: 'w:profile:picture',
217
- ...(targetJid ? { target: targetJid } : {})
218
- }
219
- });
220
- };
221
- /** update the profile status for yourself */
222
- const updateProfileStatus = async (status) => {
223
- await query({
224
- tag: 'iq',
225
- attrs: {
226
- to: S_WHATSAPP_NET,
227
- type: 'set',
228
- xmlns: 'status'
229
- },
230
- content: [
231
- {
232
- tag: 'status',
233
- attrs: {},
234
- content: Buffer.from(status, 'utf-8')
235
- }
236
- ]
237
- });
238
- };
239
- const updateProfileName = async (name) => {
240
- await chatModify({ pushNameSetting: name }, '');
241
- };
242
- const fetchBlocklist = async () => {
243
- const result = await query({
244
- tag: 'iq',
245
- attrs: {
246
- xmlns: 'blocklist',
247
- to: S_WHATSAPP_NET,
248
- type: 'get'
249
- }
250
- });
251
- const listNode = getBinaryNodeChild(result, 'list');
252
- return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
253
- };
254
- const updateBlockStatus = async (jid, action) => {
255
- await query({
256
- tag: 'iq',
257
- attrs: {
258
- xmlns: 'blocklist',
259
- to: S_WHATSAPP_NET,
260
- type: 'set'
261
- },
262
- content: [
263
- {
264
- tag: 'item',
265
- attrs: {
266
- action,
267
- jid
268
- }
269
- }
270
- ]
271
- });
272
- };
273
- const getBusinessProfile = async (jid) => {
274
- const results = await query({
275
- tag: 'iq',
276
- attrs: {
277
- to: 's.whatsapp.net',
278
- xmlns: 'w:biz',
279
- type: 'get'
280
- },
281
- content: [
282
- {
283
- tag: 'business_profile',
284
- attrs: { v: '244' },
285
- content: [
286
- {
287
- tag: 'profile',
288
- attrs: { jid }
289
- }
290
- ]
291
- }
292
- ]
293
- });
294
- const profileNode = getBinaryNodeChild(results, 'business_profile');
295
- const profiles = getBinaryNodeChild(profileNode, 'profile');
296
- if (profiles) {
297
- const address = getBinaryNodeChild(profiles, 'address');
298
- const description = getBinaryNodeChild(profiles, 'description');
299
- const website = getBinaryNodeChild(profiles, 'website');
300
- const email = getBinaryNodeChild(profiles, 'email');
301
- const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
302
- const businessHours = getBinaryNodeChild(profiles, 'business_hours');
303
- const businessHoursConfig = businessHours
304
- ? getBinaryNodeChildren(businessHours, 'business_hours_config')
305
- : undefined;
306
- const websiteStr = website?.content?.toString();
307
- return {
308
- wid: profiles.attrs?.jid,
309
- address: address?.content?.toString(),
310
- description: description?.content?.toString() || '',
311
- website: websiteStr ? [websiteStr] : [],
312
- email: email?.content?.toString(),
313
- category: category?.content?.toString(),
314
- business_hours: {
315
- timezone: businessHours?.attrs?.timezone,
316
- business_config: businessHoursConfig?.map(({ attrs }) => attrs)
317
- }
318
- };
319
- }
320
- };
321
- const cleanDirtyBits = async (type, fromTimestamp) => {
322
- logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
323
- await sendNode({
324
- tag: 'iq',
325
- attrs: {
326
- to: S_WHATSAPP_NET,
327
- type: 'set',
328
- xmlns: 'urn:xmpp:whatsapp:dirty',
329
- id: generateMessageTag()
330
- },
331
- content: [
332
- {
333
- tag: 'clean',
334
- attrs: {
335
- type,
336
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
337
- }
338
- }
339
- ]
340
- });
341
- };
342
- const newAppStateChunkHandler = (isInitialSync) => {
343
- return {
344
- onMutation(mutation) {
345
- processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
346
- }
347
- };
348
- };
349
- const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
350
- // we use this to determine which events to fire
351
- // otherwise when we resync from scratch -- all notifications will fire
352
- const initialVersionMap = {};
353
- const globalMutationMap = {};
354
- await authState.keys.transaction(async () => {
355
- const collectionsToHandle = new Set(collections);
356
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
357
- const attemptsMap = {};
358
- // keep executing till all collections are done
359
- // sometimes a single patch request will not return all the patches (God knows why)
360
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
361
- while (collectionsToHandle.size) {
362
- const states = {};
363
- const nodes = [];
364
- for (const name of collectionsToHandle) {
365
- const result = await authState.keys.get('app-state-sync-version', [name]);
366
- let state = result[name];
367
- if (state) {
368
- if (typeof initialVersionMap[name] === 'undefined') {
369
- initialVersionMap[name] = state.version;
370
- }
371
- }
372
- else {
373
- state = newLTHashState();
374
- }
375
- states[name] = state;
376
- logger.info(`resyncing ${name} from v${state.version}`);
377
- nodes.push({
378
- tag: 'collection',
379
- attrs: {
380
- name,
381
- version: state.version.toString(),
382
- // return snapshot if being synced from scratch
383
- return_snapshot: (!state.version).toString()
384
- }
385
- });
386
- }
387
- const result = await query({
388
- tag: 'iq',
389
- attrs: {
390
- to: S_WHATSAPP_NET,
391
- xmlns: 'w:sync:app:state',
392
- type: 'set'
393
- },
394
- content: [
395
- {
396
- tag: 'sync',
397
- attrs: {},
398
- content: nodes
399
- }
400
- ]
401
- });
402
- // extract from binary node
403
- const decoded = await extractSyncdPatches(result, config?.options);
404
- for (const key in decoded) {
405
- const name = key;
406
- const { patches, hasMorePatches, snapshot } = decoded[name];
407
- try {
408
- if (snapshot) {
409
- const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
410
- states[name] = newState;
411
- Object.assign(globalMutationMap, mutationMap);
412
- logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
413
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
414
- }
415
- // only process if there are syncd patches
416
- if (patches.length) {
417
- const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
418
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
419
- logger.info(`synced ${name} to v${newState.version}`);
420
- initialVersionMap[name] = newState.version;
421
- Object.assign(globalMutationMap, mutationMap);
422
- }
423
- if (hasMorePatches) {
424
- logger.info(`${name} has more patches...`);
425
- }
426
- else {
427
- // collection is done with sync
428
- collectionsToHandle.delete(name);
429
- }
430
- }
431
- catch (error) {
432
- // if retry attempts overshoot
433
- // or key not found
434
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
435
- error.output?.statusCode === 404 ||
436
- error.name === 'TypeError';
437
- logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
438
- await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
439
- // increment number of retries
440
- attemptsMap[name] = (attemptsMap[name] || 0) + 1;
441
- if (isIrrecoverableError) {
442
- // stop retrying
443
- collectionsToHandle.delete(name);
444
- }
445
- }
446
- }
447
- }
448
- }, authState?.creds?.me?.id || 'resync-app-state');
449
- const { onMutation } = newAppStateChunkHandler(isInitialSync);
450
- for (const key in globalMutationMap) {
451
- onMutation(globalMutationMap[key]);
452
- }
453
- });
454
- /**
455
- * fetch the profile picture of a user/group
456
- * type = "preview" for a low res picture
457
- * type = "image for the high res picture"
458
- */
459
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
460
- // TOOD: Add support for tctoken, existingID, and newsletter + group options
461
- jid = jidNormalizedUser(jid);
462
- const result = await query({
463
- tag: 'iq',
464
- attrs: {
465
- target: jid,
466
- to: S_WHATSAPP_NET,
467
- type: 'get',
468
- xmlns: 'w:profile:picture'
469
- },
470
- content: [{ tag: 'picture', attrs: { type, query: 'url' } }]
471
- }, timeoutMs);
472
- const child = getBinaryNodeChild(result, 'picture');
473
- return child?.attrs?.url;
474
- };
475
- const createCallLink = async (type, event, timeoutMs) => {
476
- const result = await query({
477
- tag: 'call',
478
- attrs: {
479
- id: generateMessageTag(),
480
- to: '@call'
481
- },
482
- content: [
483
- {
484
- tag: 'link_create',
485
- attrs: { media: type },
486
- content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
487
- }
488
- ]
489
- }, timeoutMs);
490
- const child = getBinaryNodeChild(result, 'link_create');
491
- return child?.attrs?.token;
492
- };
493
- const sendPresenceUpdate = async (type, toJid) => {
494
- const me = authState.creds.me;
495
- if (type === 'available' || type === 'unavailable') {
496
- if (!me.name) {
497
- logger.warn('no name present, ignoring presence update request...');
498
- return;
499
- }
500
- ev.emit('connection.update', { isOnline: type === 'available' });
501
- await sendNode({
502
- tag: 'presence',
503
- attrs: {
504
- name: me.name.replace(/@/g, ''),
505
- type
506
- }
507
- });
508
- }
509
- else {
510
- const { server } = jidDecode(toJid);
511
- const isLid = server === 'lid';
512
- await sendNode({
513
- tag: 'chatstate',
514
- attrs: {
515
- from: isLid ? me.lid : me.id,
516
- to: toJid
517
- },
518
- content: [
519
- {
520
- tag: type === 'recording' ? 'composing' : type,
521
- attrs: type === 'recording' ? { media: 'audio' } : {}
522
- }
523
- ]
524
- });
525
- }
526
- };
527
- /**
528
- * @param toJid the jid to subscribe to
529
- * @param tcToken token for subscription, use if present
530
- */
531
- const presenceSubscribe = (toJid, tcToken) => sendNode({
532
- tag: 'presence',
533
- attrs: {
534
- to: toJid,
535
- id: generateMessageTag(),
536
- type: 'subscribe'
537
- },
538
- content: tcToken
539
- ? [
540
- {
541
- tag: 'tctoken',
542
- attrs: {},
543
- content: tcToken
544
- }
545
- ]
546
- : undefined
547
- });
548
- const handlePresenceUpdate = ({ tag, attrs, content }) => {
549
- let presence;
550
- const jid = attrs.from;
551
- const participant = attrs.participant || attrs.from;
552
- if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
553
- return;
554
- }
555
- if (tag === 'presence') {
556
- presence = {
557
- lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
558
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
559
- };
560
- }
561
- else if (Array.isArray(content)) {
562
- const [firstChild] = content;
563
- let type = firstChild.tag;
564
- if (type === 'paused') {
565
- type = 'available';
566
- }
567
- if (firstChild.attrs?.media === 'audio') {
568
- type = 'recording';
569
- }
570
- presence = { lastKnownPresence: type };
571
- }
572
- else {
573
- logger.error({ tag, attrs, content }, 'recv invalid presence node');
574
- }
575
- if (presence) {
576
- ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
577
- }
578
- };
579
- const appPatch = async (patchCreate) => {
580
- const name = patchCreate.type;
581
- const myAppStateKeyId = authState.creds.myAppStateKeyId;
582
- if (!myAppStateKeyId) {
583
- throw new Boom('App state key not present!', { statusCode: 400 });
584
- }
585
- let initial;
586
- let encodeResult;
587
- await processingMutex.mutex(async () => {
588
- await authState.keys.transaction(async () => {
589
- logger.debug({ patch: patchCreate }, 'applying app patch');
590
- await resyncAppState([name], false);
591
- const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
592
- initial = currentSyncVersion || newLTHashState();
593
- encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
594
- const { patch, state } = encodeResult;
595
- const node = {
596
- tag: 'iq',
597
- attrs: {
598
- to: S_WHATSAPP_NET,
599
- type: 'set',
600
- xmlns: 'w:sync:app:state'
601
- },
602
- content: [
603
- {
604
- tag: 'sync',
605
- attrs: {},
606
- content: [
607
- {
608
- tag: 'collection',
609
- attrs: {
610
- name,
611
- version: (state.version - 1).toString(),
612
- return_snapshot: 'false'
613
- },
614
- content: [
615
- {
616
- tag: 'patch',
617
- attrs: {},
618
- content: proto.SyncdPatch.encode(patch).finish()
619
- }
620
- ]
621
- }
622
- ]
623
- }
624
- ]
625
- };
626
- await query(node);
627
- await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
628
- }, authState?.creds?.me?.id || 'app-patch');
629
- });
630
- if (config.emitOwnEvents) {
631
- const { onMutation } = newAppStateChunkHandler(false);
632
- const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
633
- for (const key in mutationMap) {
634
- onMutation(mutationMap[key]);
635
- }
636
- }
637
- };
638
- /** sending non-abt props may fix QR scan fail if server expects */
639
- const fetchProps = async () => {
640
- //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
641
- const resultNode = await query({
642
- tag: 'iq',
643
- attrs: {
644
- to: S_WHATSAPP_NET,
645
- xmlns: 'w',
646
- type: 'get'
647
- },
648
- content: [
649
- {
650
- tag: 'props',
651
- attrs: {
652
- protocol: '2',
653
- hash: authState?.creds?.lastPropHash || ''
654
- }
655
- }
656
- ]
657
- });
658
- const propsNode = getBinaryNodeChild(resultNode, 'props');
659
- let props = {};
660
- if (propsNode) {
661
- if (propsNode.attrs?.hash) {
662
- // on some clients, the hash is returning as undefined
663
- authState.creds.lastPropHash = propsNode?.attrs?.hash;
664
- ev.emit('creds.update', authState.creds);
665
- }
666
- props = reduceBinaryNodeToDictionary(propsNode, 'prop');
667
- }
668
- logger.debug('fetched props');
669
- return props;
670
- };
671
- /**
672
- * modify a chat -- mark unread, read etc.
673
- * lastMessages must be sorted in reverse chronologically
674
- * requires the last messages till the last message received; required for archive & unread
675
- */
676
- const chatModify = (mod, jid) => {
677
- const patch = chatModificationToAppPatch(mod, jid);
678
- return appPatch(patch);
679
- };
680
- /**
681
- * Enable/Disable link preview privacy, not related to baileys link preview generation
682
- */
683
- const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
684
- return chatModify({
685
- disableLinkPreviews: { isPreviewsDisabled }
686
- }, '');
687
- };
688
- /**
689
- * Star or Unstar a message
690
- */
691
- const star = (jid, messages, star) => {
692
- return chatModify({
693
- star: {
694
- messages,
695
- star
696
- }
697
- }, jid);
698
- };
699
- /**
700
- * Add or Edit Contact
701
- */
702
- const addOrEditContact = (jid, contact) => {
703
- return chatModify({
704
- contact
705
- }, jid);
706
- };
707
- /**
708
- * Remove Contact
709
- */
710
- const removeContact = (jid) => {
711
- return chatModify({
712
- contact: null
713
- }, jid);
714
- };
715
- /**
716
- * Adds label
717
- */
718
- const addLabel = (jid, labels) => {
719
- return chatModify({
720
- addLabel: {
721
- ...labels
722
- }
723
- }, jid);
724
- };
725
- /**
726
- * Adds label for the chats
727
- */
728
- const addChatLabel = (jid, labelId) => {
729
- return chatModify({
730
- addChatLabel: {
731
- labelId
732
- }
733
- }, jid);
734
- };
735
- /**
736
- * Removes label for the chat
737
- */
738
- const removeChatLabel = (jid, labelId) => {
739
- return chatModify({
740
- removeChatLabel: {
741
- labelId
742
- }
743
- }, jid);
744
- };
745
- /**
746
- * Adds label for the message
747
- */
748
- const addMessageLabel = (jid, messageId, labelId) => {
749
- return chatModify({
750
- addMessageLabel: {
751
- messageId,
752
- labelId
753
- }
754
- }, jid);
755
- };
756
- /**
757
- * Removes label for the message
758
- */
759
- const removeMessageLabel = (jid, messageId, labelId) => {
760
- return chatModify({
761
- removeMessageLabel: {
762
- messageId,
763
- labelId
764
- }
765
- }, jid);
766
- };
767
- /**
768
- * Add or Edit Quick Reply
769
- */
770
- const addOrEditQuickReply = (quickReply) => {
771
- return chatModify({
772
- quickReply
773
- }, '');
774
- };
775
- /**
776
- * Remove Quick Reply
777
- */
778
- const removeQuickReply = (timestamp) => {
779
- return chatModify({
780
- quickReply: { timestamp, deleted: true }
781
- }, '');
782
- };
783
- /**
784
- * queries need to be fired on connection open
785
- * help ensure parity with WA Web
786
- * */
787
- const executeInitQueries = async () => {
788
- await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
789
- };
790
- const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
791
- ev.emit('messages.upsert', { messages: [msg], type });
792
- if (!!msg.pushName) {
793
- let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
794
- jid = jidNormalizedUser(jid);
795
- if (!msg.key.fromMe) {
796
- ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
797
- }
798
- // update our pushname too
799
- if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
800
- ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
801
- }
802
- }
803
- const historyMsg = getHistoryMsg(msg.message);
804
- const shouldProcessHistoryMsg = historyMsg
805
- ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
806
- : false;
807
- // State machine: decide on sync and flush
808
- if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
809
- if (awaitingSyncTimeout) {
810
- clearTimeout(awaitingSyncTimeout);
811
- awaitingSyncTimeout = undefined;
812
- }
813
- if (shouldProcessHistoryMsg) {
814
- syncState = SyncState.Syncing;
815
- logger.info('Transitioned to Syncing state');
816
- // Let doAppStateSync handle the final flush after it's done
817
- }
818
- else {
819
- syncState = SyncState.Online;
820
- logger.info('History sync skipped, transitioning to Online state and flushing buffer');
821
- ev.flush();
822
- }
823
- }
824
- const doAppStateSync = async () => {
825
- if (syncState === SyncState.Syncing) {
826
- logger.info('Doing app state sync');
827
- await resyncAppState(ALL_WA_PATCH_NAMES, true);
828
- // Sync is complete, go online and flush everything
829
- syncState = SyncState.Online;
830
- logger.info('App state sync complete, transitioning to Online state and flushing buffer');
831
- ev.flush();
832
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
833
- ev.emit('creds.update', { accountSyncCounter });
834
- }
835
- };
836
- await Promise.all([
837
- (async () => {
838
- if (shouldProcessHistoryMsg) {
839
- await doAppStateSync();
840
- }
841
- })(),
842
- processMessage(msg, {
843
- signalRepository,
844
- shouldProcessHistoryMsg,
845
- placeholderResendCache,
846
- ev,
847
- creds: authState.creds,
848
- keyStore: authState.keys,
849
- logger,
850
- options: config.options
851
- })
852
- ]);
853
- // If the app state key arrives and we are waiting to sync, trigger the sync now.
854
- if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
855
- logger.info('App state sync key arrived, triggering app state sync');
856
- await doAppStateSync();
857
- }
858
- });
859
- ws.on('CB:presence', handlePresenceUpdate);
860
- ws.on('CB:chatstate', handlePresenceUpdate);
861
- ws.on('CB:ib,,dirty', async (node) => {
862
- const { attrs } = getBinaryNodeChild(node, 'dirty');
863
- const type = attrs.type;
864
- switch (type) {
865
- case 'account_sync':
866
- if (attrs.timestamp) {
867
- let { lastAccountSyncTimestamp } = authState.creds;
868
- if (lastAccountSyncTimestamp) {
869
- await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
870
- }
871
- lastAccountSyncTimestamp = +attrs.timestamp;
872
- ev.emit('creds.update', { lastAccountSyncTimestamp });
873
- }
874
- break;
875
- case 'groups':
876
- // handled in groups.ts
877
- break;
878
- default:
879
- logger.info({ node }, 'received unknown sync');
880
- break;
881
- }
882
- });
883
- ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
884
- if (connection === 'open') {
885
- if (fireInitQueries) {
886
- executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
887
- }
888
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
889
- }
890
- if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
891
- return;
892
- }
893
- syncState = SyncState.AwaitingInitialSync;
894
- logger.info('Connection is now AwaitingInitialSync, buffering events');
895
- ev.buffer();
896
- const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
897
- syncType: proto.HistorySync.HistorySyncType.RECENT
898
- }));
899
- if (!willSyncHistory) {
900
- logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
901
- syncState = SyncState.Online;
902
- setTimeout(() => ev.flush(), 0);
903
- return;
904
- }
905
- logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
906
- if (awaitingSyncTimeout) {
907
- clearTimeout(awaitingSyncTimeout);
908
- }
909
- awaitingSyncTimeout = setTimeout(() => {
910
- if (syncState === SyncState.AwaitingInitialSync) {
911
- // TODO: investigate
912
- logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
913
- syncState = SyncState.Online;
914
- ev.flush();
915
- }
916
- }, 20000);
917
- });
918
- return {
919
- ...sock,
920
- createCallLink,
921
- getBotListV2,
922
- processingMutex,
923
- fetchPrivacySettings,
924
- upsertMessage,
925
- appPatch,
926
- sendPresenceUpdate,
927
- presenceSubscribe,
928
- profilePictureUrl,
929
- fetchBlocklist,
930
- fetchStatus,
931
- fetchDisappearingDuration,
932
- updateProfilePicture,
933
- removeProfilePicture,
934
- updateProfileStatus,
935
- updateProfileName,
936
- updateBlockStatus,
937
- updateDisableLinkPreviewsPrivacy,
938
- updateCallPrivacy,
939
- updateMessagesPrivacy,
940
- updateLastSeenPrivacy,
941
- updateOnlinePrivacy,
942
- updateProfilePicturePrivacy,
943
- updateStatusPrivacy,
944
- updateReadReceiptsPrivacy,
945
- updateGroupsAddPrivacy,
946
- updateDefaultDisappearingMode,
947
- getBusinessProfile,
948
- resyncAppState,
949
- chatModify,
950
- cleanDirtyBits,
951
- addOrEditContact,
952
- removeContact,
953
- addLabel,
954
- addChatLabel,
955
- removeChatLabel,
956
- addMessageLabel,
957
- removeMessageLabel,
958
- star,
959
- addOrEditQuickReply,
960
- removeQuickReply
961
- };
962
- };
963
- //# sourceMappingURL=chats.js.map
1
+ import NodeCache from '@cacheable/node-cache'
2
+ import { Boom } from '@hapi/boom'
3
+ import { proto } from '../../WAProto/index.js'
4
+ import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js'
5
+ import { ALL_WA_PATCH_NAMES } from '../Types/index.js'
6
+ import { SyncState } from '../Types/State.js'
7
+ import {
8
+ chatModificationToAppPatch,
9
+ decodePatches,
10
+ decodeSyncdSnapshot,
11
+ encodeSyncdPatch,
12
+ ensureLTHashStateVersion,
13
+ extractSyncdPatches,
14
+ generateProfilePicture,
15
+ getHistoryMsg,
16
+ newLTHashState,
17
+ processSyncAction
18
+ } from '../Utils/index.js'
19
+ import { makeMutex } from '../Utils/make-mutex.js'
20
+ import processMessage from '../Utils/process-message.js'
21
+ import {
22
+ getBinaryNodeChild,
23
+ getBinaryNodeChildren,
24
+ isLidUser,
25
+ jidDecode,
26
+ jidNormalizedUser,
27
+ reduceBinaryNodeToDictionary,
28
+ S_WHATSAPP_NET
29
+ } from '../WABinary/index.js'
30
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js'
31
+ import { makeSocket } from './socket.js'
32
+
33
+ const MAX_SYNC_ATTEMPTS = 2
34
+ const HISTORY_SYNC_PAUSED_TIMEOUT_MS = 120_000
35
+ const APP_STATE_RESYNC_COOLDOWN_MS = 60_000
36
+
37
+ export const makeChatsSocket = (config) => {
38
+ const {
39
+ logger,
40
+ markOnlineOnConnect,
41
+ fireInitQueries,
42
+ appStateMacVerification,
43
+ shouldIgnoreJid,
44
+ shouldSyncHistoryMessage,
45
+ getMessage
46
+ } = config
47
+
48
+ const sock = makeSocket(config)
49
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError } = sock
50
+
51
+ let privacySettings
52
+ let syncState = SyncState.Connecting
53
+ let awaitingSyncTimeout
54
+ let historySyncPausedTimeout
55
+
56
+ const historySyncStatus = { initialBootstrapComplete: false, recentSyncComplete: false }
57
+ const blockedCollections = new Set()
58
+
59
+ const processingMutex = makeMutex()
60
+ const messageMutex = makeMutex()
61
+ const receiptMutex = makeMutex()
62
+ const appStatePatchMutex = makeMutex()
63
+ const notificationMutex = makeMutex()
64
+
65
+ const placeholderResendCache = config.placeholderResendCache || new NodeCache({
66
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
67
+ useClones: false
68
+ })
69
+ if (!config.placeholderResendCache) config.placeholderResendCache = placeholderResendCache
70
+
71
+ const profilePictureUrlCache = config.profilePictureUrlCache || new NodeCache({
72
+ stdTTL: DEFAULT_CACHE_TTLS.PROFILE_PIC,
73
+ useClones: false
74
+ })
75
+ if (!config.profilePictureUrlCache) config.profilePictureUrlCache = profilePictureUrlCache
76
+
77
+ const inFlightProfilePictureUrl = new Map()
78
+ const appStateResyncCooldown = new Map()
79
+
80
+ // ─── Key helpers ────────────────────────────────────────────────────────────
81
+
82
+ const getAppStateSyncKey = async (keyId) => {
83
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
84
+ return key
85
+ }
86
+
87
+
88
+ const interactiveQuery = async (userNodes, queryNode) => {
89
+ const result = await query({
90
+ tag: 'iq',
91
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'usync' },
92
+ content: [{
93
+ tag: 'usync',
94
+ attrs: { sid: generateMessageTag(), mode: 'query', last: 'true', index: '0', context: 'interactive' },
95
+ content: [
96
+ { tag: 'query', attrs: {}, content: [queryNode] },
97
+ { tag: 'list', attrs: {}, content: userNodes }
98
+ ]
99
+ }]
100
+ })
101
+ const usyncNode = getBinaryNodeChild(result, 'usync')
102
+ const listNode = getBinaryNodeChild(usyncNode, 'list')
103
+ return getBinaryNodeChildren(listNode, 'user')
104
+ }
105
+
106
+ // ─── Privacy ─────────────────────────────────────────────────────────────────
107
+
108
+ const fetchPrivacySettings = async (force = false) => {
109
+ if (!privacySettings || force) {
110
+ const { content } = await query({
111
+ tag: 'iq',
112
+ attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'get' },
113
+ content: [{ tag: 'privacy', attrs: {} }]
114
+ })
115
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category')
116
+ }
117
+ return privacySettings
118
+ }
119
+
120
+ const privacyQuery = async (name, value) => {
121
+ await query({
122
+ tag: 'iq',
123
+ attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'set' },
124
+ content: [{ tag: 'privacy', attrs: {}, content: [{ tag: 'category', attrs: { name, value } }] }]
125
+ })
126
+ }
127
+
128
+ const updateMessagesPrivacy = (value) => privacyQuery('messages', value)
129
+ const updateCallPrivacy = (value) => privacyQuery('calladd', value)
130
+ const updateLastSeenPrivacy = (value) => privacyQuery('last', value)
131
+ const updateOnlinePrivacy = (value) => privacyQuery('online', value)
132
+ const updateProfilePicturePrivacy = (value) => privacyQuery('profile', value)
133
+ const updateStatusPrivacy = (value) => privacyQuery('status', value)
134
+ const updateReadReceiptsPrivacy = (value) => privacyQuery('readreceipts', value)
135
+ const updateGroupsAddPrivacy = (value) => privacyQuery('groupadd', value)
136
+
137
+ const updateDefaultDisappearingMode = async (duration) => {
138
+ await query({
139
+ tag: 'iq',
140
+ attrs: { xmlns: 'disappearing_mode', to: S_WHATSAPP_NET, type: 'set' },
141
+ content: [{ tag: 'disappearing_mode', attrs: { duration: duration.toString() } }]
142
+ })
143
+ }
144
+
145
+ // ─── Queries ─────────────────────────────────────────────────────────────────
146
+
147
+ const getBotListV2 = async () => {
148
+ const resp = await query({
149
+ tag: 'iq',
150
+ attrs: { xmlns: 'bot', to: S_WHATSAPP_NET, type: 'get' },
151
+ content: [{ tag: 'bot', attrs: { v: '2' } }]
152
+ })
153
+ const botNode = getBinaryNodeChild(resp, 'bot')
154
+ const botList = []
155
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
156
+ if (section.attrs.type === 'all') {
157
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
158
+ botList.push({ jid: bot.attrs.jid, personaId: bot.attrs['persona_id'] })
159
+ }
160
+ }
161
+ }
162
+ return botList
163
+ }
164
+
165
+ const fetchStatus = async (...jids) => {
166
+ const usyncQuery = new USyncQuery().withStatusProtocol()
167
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
168
+ const result = await sock.executeUSyncQuery(usyncQuery)
169
+ return result?.list
170
+ }
171
+
172
+ const fetchDisappearingDuration = async (...jids) => {
173
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol()
174
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
175
+ const result = await sock.executeUSyncQuery(usyncQuery)
176
+ return result?.list
177
+ }
178
+
179
+ const onWhatsApp = async (...jids) => {
180
+ const usyncQuery = new USyncQuery()
181
+ let contactEnabled = false
182
+
183
+ for (const jid of jids) {
184
+ if (isLidUser(jid)) {
185
+ logger.warn('LIDs not supported with onWhatsApp')
186
+ continue
187
+ }
188
+ if (!contactEnabled) {
189
+ contactEnabled = true
190
+ usyncQuery.withContactProtocol().withLIDProtocol()
191
+ }
192
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`
193
+ usyncQuery.withUser(new USyncUser().withPhone(phone))
194
+ }
195
+
196
+ if (usyncQuery.users.length === 0) return []
197
+
198
+ const results = await sock.executeUSyncQuery(usyncQuery)
199
+ if (!results) return []
200
+
201
+ return Promise.all(
202
+ results.list
203
+ .filter(a => a.contact === true)
204
+ .map(async ({ id, lid }) => {
205
+ try {
206
+ const businessProfile = await getBusinessProfile(id)
207
+ const isBusiness = businessProfile && Object.keys(businessProfile).length > 0
208
+ if (isBusiness) {
209
+ const { wid, ...businessInfo } = businessProfile
210
+ return { jid: id, exists: true, lid, status: 'business', businessInfo }
211
+ }
212
+ return { jid: id, exists: true, lid, status: 'regular' }
213
+ } catch (error) {
214
+ return { jid: id, exists: true, lid, status: 'error', error: error?.message }
215
+ }
216
+ })
217
+ )
218
+ }
219
+
220
+ const checkStatusWA = async (phoneNumber) => {
221
+ if (!phoneNumber) throw new Error('enter number')
222
+
223
+ let resultData = { isBanned: false, isNeedOfficialWa: false, number: phoneNumber }
224
+
225
+ let formattedNumber = phoneNumber.startsWith('+') ? phoneNumber : '+' + phoneNumber
226
+
227
+ const { parsePhoneNumber } = await import('libphonenumber-js')
228
+ const parsedNumber = parsePhoneNumber(formattedNumber)
229
+ const countryCode = parsedNumber.countryCallingCode
230
+ const nationalNumber = parsedNumber.nationalNumber
231
+
232
+ try {
233
+ const { useMultiFileAuthState, fetchLatestBaileysVersion, Browsers } = await import('../Utils/index.js')
234
+ const { state } = await useMultiFileAuthState('.npm')
235
+ const { version } = await fetchLatestBaileysVersion()
236
+ const { makeWASocket } = await import('../Socket/index.js')
237
+ const pino = (await import('pino')).default
238
+
239
+ const tempSock = makeWASocket({
240
+ version,
241
+ auth: state,
242
+ browser: Browsers.ubuntu('Chrome'),
243
+ logger: pino({ level: 'silent' }),
244
+ printQRInTerminal: false
245
+ })
246
+
247
+ await tempSock.requestRegistrationCode({
248
+ phoneNumber: formattedNumber,
249
+ phoneNumberCountryCode: countryCode,
250
+ phoneNumberNationalNumber: nationalNumber,
251
+ phoneNumberMobileCountryCode: '510',
252
+ phoneNumberMobileNetworkCode: '10',
253
+ method: 'sms'
254
+ })
255
+
256
+ if (tempSock.ws) tempSock.ws.close()
257
+ return JSON.stringify(resultData, null, 2)
258
+ } catch (err) {
259
+ if (err?.appeal_token) {
260
+ resultData.isBanned = true
261
+ resultData.data = {
262
+ violation_type: err.violation_type || null,
263
+ in_app_ban_appeal: err.in_app_ban_appeal || null,
264
+ appeal_token: err.appeal_token || null
265
+ }
266
+ } else if (err?.custom_block_screen || err?.reason === 'blocked') {
267
+ resultData.isNeedOfficialWa = true
268
+ }
269
+ return JSON.stringify(resultData, null, 2)
270
+ }
271
+ }
272
+
273
+
274
+ // ─── Profile ─────────────────────────────────────────────────────────────────
275
+
276
+ const updateProfilePicture = async (jid, content) => {
277
+ 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')
278
+ let targetJid
279
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) targetJid = jidNormalizedUser(jid)
280
+ const { img } = await generateProfilePicture(content)
281
+ await query({
282
+ tag: 'iq',
283
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) },
284
+ content: [{ tag: 'picture', attrs: { type: 'image' }, content: img }]
285
+ })
286
+ }
287
+
288
+ const removeProfilePicture = async (jid) => {
289
+ 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')
290
+ let targetJid
291
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) targetJid = jidNormalizedUser(jid)
292
+ await query({
293
+ tag: 'iq',
294
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) }
295
+ })
296
+ }
297
+
298
+ const updateProfileStatus = async (status) => {
299
+ await query({
300
+ tag: 'iq',
301
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'status' },
302
+ content: [{ tag: 'status', attrs: {}, content: Buffer.from(status, 'utf-8') }]
303
+ })
304
+ }
305
+
306
+ const updateProfileName = (name) => chatModify({ pushNameSetting: name }, '')
307
+
308
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
309
+ jid = jidNormalizedUser(jid)
310
+ const cacheKey = `${jid}:${type}`
311
+ const cached = profilePictureUrlCache.get(cacheKey)
312
+ if (typeof cached !== 'undefined') return cached || undefined
313
+ const inFlight = inFlightProfilePictureUrl.get(cacheKey)
314
+ if (inFlight) return inFlight
315
+ const fetchPromise = (async () => {
316
+ const result = await query({
317
+ tag: 'iq',
318
+ attrs: { target: jid, to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:profile:picture' },
319
+ content: [{ tag: 'picture', attrs: { type, query: 'url' } }]
320
+ }, timeoutMs)
321
+ const child = getBinaryNodeChild(result, 'picture')
322
+ const url = child?.attrs?.url
323
+ profilePictureUrlCache.set(cacheKey, url || null)
324
+ return url
325
+ })()
326
+ inFlightProfilePictureUrl.set(cacheKey, fetchPromise)
327
+ try {
328
+ return await fetchPromise
329
+ } finally {
330
+ inFlightProfilePictureUrl.delete(cacheKey)
331
+ }
332
+ }
333
+
334
+ // ─── Blocklist ────────────────────────────────────────────────────────────────
335
+
336
+ const fetchBlocklist = async () => {
337
+ const result = await query({ tag: 'iq', attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'get' } })
338
+ const listNode = getBinaryNodeChild(result, 'list')
339
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid)
340
+ }
341
+
342
+ const updateBlockStatus = async (jid, action) => {
343
+ await query({
344
+ tag: 'iq',
345
+ attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'set' },
346
+ content: [{ tag: 'item', attrs: { action, jid } }]
347
+ })
348
+ }
349
+
350
+ // ─── Business ────────────────────────────────────────────────────────────────
351
+
352
+ const getBusinessProfile = async (jid) => {
353
+ const results = await query({
354
+ tag: 'iq',
355
+ attrs: { to: 's.whatsapp.net', xmlns: 'w:biz', type: 'get' },
356
+ content: [{ tag: 'business_profile', attrs: { v: '244' }, content: [{ tag: 'profile', attrs: { jid } }] }]
357
+ })
358
+ const profileNode = getBinaryNodeChild(results, 'business_profile')
359
+ const profiles = getBinaryNodeChild(profileNode, 'profile')
360
+ if (profiles) {
361
+ const address = getBinaryNodeChild(profiles, 'address')
362
+ const description = getBinaryNodeChild(profiles, 'description')
363
+ const website = getBinaryNodeChild(profiles, 'website')
364
+ const email = getBinaryNodeChild(profiles, 'email')
365
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category')
366
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours')
367
+ const businessHoursConfig = businessHours ? getBinaryNodeChildren(businessHours, 'business_hours_config') : undefined
368
+ const websiteStr = website?.content?.toString()
369
+ return {
370
+ wid: profiles.attrs?.jid,
371
+ address: address?.content?.toString(),
372
+ description: description?.content?.toString() || '',
373
+ website: websiteStr ? [websiteStr] : [],
374
+ email: email?.content?.toString(),
375
+ category: category?.content?.toString(),
376
+ business_hours: { timezone: businessHours?.attrs?.timezone, business_config: businessHoursConfig?.map(({ attrs }) => attrs) }
377
+ }
378
+ }
379
+ }
380
+
381
+ // ─── App state ────────────────────────────────────────────────────────────────
382
+
383
+ const cleanDirtyBits = async (type, fromTimestamp) => {
384
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
385
+ await sendNode({
386
+ tag: 'iq',
387
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'urn:xmpp:whatsapp:dirty', id: generateMessageTag() },
388
+ content: [{ tag: 'clean', attrs: { type, ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null) } }]
389
+ })
390
+ }
391
+
392
+ const newAppStateChunkHandler = (isInitialSync) => ({
393
+ onMutation(mutation) {
394
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
395
+ }
396
+ })
397
+
398
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
399
+ const now = Date.now()
400
+ const collectionsToSync = collections.filter(name => (appStateResyncCooldown.get(name) || 0) <= now)
401
+ if (!collectionsToSync.length) return
402
+
403
+ // Per-invocation cache to avoid redundant key fetches within a single resync
404
+ const appStateSyncKeyCache = new Map()
405
+ const getCachedAppStateSyncKey = async (keyId) => {
406
+ if (appStateSyncKeyCache.has(keyId)) return appStateSyncKeyCache.get(keyId) ?? undefined
407
+ const key = await getAppStateSyncKey(keyId)
408
+ appStateSyncKeyCache.set(keyId, key ?? null)
409
+ return key
410
+ }
411
+
412
+ const initialVersionMap = {}
413
+ const globalMutationMap = {}
414
+
415
+ await authState.keys.transaction(async () => {
416
+ const collectionsToHandle = new Set(collectionsToSync)
417
+ const attemptsMap = {}
418
+ const forceSnapshotCollections = new Set()
419
+
420
+ while (collectionsToHandle.size) {
421
+ const states = {}
422
+ const nodes = []
423
+
424
+ for (const name of collectionsToHandle) {
425
+ const result = await authState.keys.get('app-state-sync-version', [name])
426
+ let state = result[name]
427
+ if (state) {
428
+ state = ensureLTHashStateVersion(state)
429
+ if (typeof initialVersionMap[name] === 'undefined') initialVersionMap[name] = state.version
430
+ } else {
431
+ state = newLTHashState()
432
+ }
433
+ states[name] = state
434
+
435
+ const shouldForceSnapshot = forceSnapshotCollections.has(name)
436
+ if (shouldForceSnapshot) forceSnapshotCollections.delete(name)
437
+
438
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`)
439
+ nodes.push({
440
+ tag: 'collection',
441
+ attrs: { name, version: state.version.toString(), return_snapshot: (shouldForceSnapshot || !state.version).toString() }
442
+ })
443
+ }
444
+
445
+ const result = await query({
446
+ tag: 'iq',
447
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:sync:app:state', type: 'set' },
448
+ content: [{ tag: 'sync', attrs: {}, content: nodes }]
449
+ })
450
+
451
+ const decoded = await extractSyncdPatches(result, config?.options)
452
+ for (const key in decoded) {
453
+ const name = key
454
+ const { patches, hasMorePatches, snapshot } = decoded[name]
455
+ try {
456
+ if (snapshot) {
457
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger)
458
+ states[name] = newState
459
+ Object.assign(globalMutationMap, mutationMap)
460
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
461
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
462
+ }
463
+ if (patches.length) {
464
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
465
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
466
+ logger.info(`synced ${name} to v${newState.version}`)
467
+ initialVersionMap[name] = newState.version
468
+ Object.assign(globalMutationMap, mutationMap)
469
+ }
470
+ if (hasMorePatches) {
471
+ logger.info(`${name} has more patches...`)
472
+ } else {
473
+ collectionsToHandle.delete(name)
474
+ }
475
+ } catch (error) {
476
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
477
+ const isMissingKey = error.output?.statusCode === 404
478
+ const isIrrecoverable = attemptsMap[name] >= MAX_SYNC_ATTEMPTS || error.name === 'TypeError'
479
+
480
+ logger.info({ name, error: error.stack, attempt: attemptsMap[name] }, `failed to sync ${name} from v${states[name].version}`)
481
+ if (!isMissingKey) {
482
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
483
+ }
484
+
485
+ if (isMissingKey) appStateResyncCooldown.set(name, Date.now() + APP_STATE_RESYNC_COOLDOWN_MS)
486
+
487
+ if (isMissingKey && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
488
+ logger.warn({ name }, `${name} blocked on missing key, parking until key arrives`)
489
+ blockedCollections.add(name)
490
+ collectionsToHandle.delete(name)
491
+ } else if (isMissingKey) {
492
+ forceSnapshotCollections.add(name)
493
+ } else if (isIrrecoverable) {
494
+ collectionsToHandle.delete(name)
495
+ } else {
496
+ forceSnapshotCollections.add(name)
497
+ }
498
+ }
499
+ }
500
+ }
501
+ }, authState?.creds?.me?.id || 'resync-app-state')
502
+
503
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
504
+ for (const key in globalMutationMap) onMutation(globalMutationMap[key])
505
+ })
506
+
507
+ // ─── Presence ─────────────────────────────────────────────────────────────────
508
+
509
+ const sendPresenceUpdate = async (type, toJid) => {
510
+ const me = authState.creds.me
511
+ if (type === 'available' || type === 'unavailable') {
512
+ if (!me.name) {
513
+ logger.warn('no name present, ignoring presence update request...')
514
+ return
515
+ }
516
+ ev.emit('connection.update', { isOnline: type === 'available' })
517
+ await sendNode({ tag: 'presence', attrs: { name: me.name.replace(/@/g, ''), type } })
518
+ } else {
519
+ const { server } = jidDecode(toJid)
520
+ const isLid = server === 'lid'
521
+ await sendNode({
522
+ tag: 'chatstate',
523
+ attrs: { from: isLid ? me.lid : me.id, to: toJid },
524
+ content: [{ tag: type === 'recording' ? 'composing' : type, attrs: type === 'recording' ? { media: 'audio' } : {} }]
525
+ })
526
+ }
527
+ }
528
+
529
+ const presenceSubscribe = (toJid, tcToken) => sendNode({
530
+ tag: 'presence',
531
+ attrs: { to: toJid, id: generateMessageTag(), type: 'subscribe' },
532
+ content: tcToken ? [{ tag: 'tctoken', attrs: {}, content: tcToken }] : undefined
533
+ })
534
+
535
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
536
+ let presence
537
+ const jid = attrs.from
538
+ const participant = attrs.participant || attrs.from
539
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) return
540
+ if (tag === 'presence') {
541
+ presence = {
542
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
543
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
544
+ }
545
+ } else if (Array.isArray(content)) {
546
+ const [firstChild] = content
547
+ let type = firstChild.tag
548
+ if (type === 'paused') type = 'available'
549
+ if (firstChild.attrs?.media === 'audio') type = 'recording'
550
+ presence = { lastKnownPresence: type }
551
+ } else {
552
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
553
+ }
554
+ if (presence) ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
555
+ }
556
+
557
+ // ─── App patch ────────────────────────────────────────────────────────────────
558
+
559
+ const appPatch = async (patchCreate) => {
560
+ const name = patchCreate.type
561
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
562
+ if (!myAppStateKeyId) throw new Boom('App state key not present!', { statusCode: 400 })
563
+
564
+ let initial
565
+ let encodeResult
566
+
567
+ await appStatePatchMutex.mutex(async () => {
568
+ await authState.keys.transaction(async () => {
569
+ logger.debug({ patch: patchCreate }, 'applying app patch')
570
+ await resyncAppState([name], false)
571
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
572
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState()
573
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
574
+ const { patch, state } = encodeResult
575
+ await query({
576
+ tag: 'iq',
577
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:sync:app:state' },
578
+ content: [{
579
+ tag: 'sync', attrs: {}, content: [{
580
+ tag: 'collection',
581
+ attrs: { name, version: (state.version - 1).toString(), return_snapshot: 'false' },
582
+ content: [{ tag: 'patch', attrs: {}, content: proto.SyncdPatch.encode(patch).finish() }]
583
+ }]
584
+ }]
585
+ })
586
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
587
+ }, authState?.creds?.me?.id || 'app-patch')
588
+ })
589
+
590
+ if (config.emitOwnEvents) {
591
+ const { onMutation } = newAppStateChunkHandler(false)
592
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger)
593
+ for (const key in mutationMap) onMutation(mutationMap[key])
594
+ }
595
+ }
596
+
597
+ // ─── Props ────────────────────────────────────────────────────────────────────
598
+
599
+ const fetchProps = async () => {
600
+ const resultNode = await query({
601
+ tag: 'iq',
602
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w', type: 'get' },
603
+ content: [{ tag: 'props', attrs: { protocol: '2', hash: authState?.creds?.lastPropHash || '' } }]
604
+ })
605
+ const propsNode = getBinaryNodeChild(resultNode, 'props')
606
+ let props = {}
607
+ if (propsNode) {
608
+ if (propsNode.attrs?.hash) {
609
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
610
+ ev.emit('creds.update', authState.creds)
611
+ }
612
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop')
613
+ }
614
+ logger.debug('fetched props')
615
+ return props
616
+ }
617
+
618
+ // ─── Chat modification helpers ────────────────────────────────────────────────
619
+
620
+ const chatModify = (mod, jid) => appPatch(chatModificationToAppPatch(mod, jid))
621
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '')
622
+ const star = (jid, messages, star) => chatModify({ star: { messages, star } }, jid)
623
+ const addOrEditContact = (jid, contact) => chatModify({ contact }, jid)
624
+ const removeContact = (jid) => chatModify({ contact: null }, jid)
625
+ const addLabel = (jid, labels) => chatModify({ addLabel: { ...labels } }, jid)
626
+ const addChatLabel = (jid, labelId) => chatModify({ addChatLabel: { labelId } }, jid)
627
+ const removeChatLabel = (jid, labelId) => chatModify({ removeChatLabel: { labelId } }, jid)
628
+ const addMessageLabel = (jid, messageId, labelId) => chatModify({ addMessageLabel: { messageId, labelId } }, jid)
629
+ const removeMessageLabel = (jid, messageId, labelId) => chatModify({ removeMessageLabel: { messageId, labelId } }, jid)
630
+ const addOrEditQuickReply = (quickReply) => chatModify({ quickReply }, '')
631
+ const removeQuickReply = (timestamp) => chatModify({ quickReply: { timestamp, deleted: true } }, '')
632
+
633
+ // ─── Call link ────────────────────────────────────────────────────────────────
634
+
635
+ const createCallLink = async (type, event, timeoutMs) => {
636
+ const result = await query({
637
+ tag: 'call',
638
+ attrs: { id: generateMessageTag(), to: '@call' },
639
+ content: [{ tag: 'link_create', attrs: { media: type }, content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined }]
640
+ }, timeoutMs)
641
+ return getBinaryNodeChild(result, 'link_create')?.attrs?.token
642
+ }
643
+
644
+ // ─── Init ─────────────────────────────────────────────────────────────────────
645
+
646
+ const executeInitQueries = () => Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()])
647
+
648
+ // ─── Message upsert ───────────────────────────────────────────────────────────
649
+
650
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
651
+ ev.emit('messages.upsert', { messages: [msg], type })
652
+
653
+ if (msg.pushName) {
654
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid
655
+ jid = jidNormalizedUser(jid)
656
+ if (!msg.key.fromMe) {
657
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
658
+ }
659
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
660
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
661
+ }
662
+ }
663
+
664
+ const historyMsg = getHistoryMsg(msg.message)
665
+ const shouldProcessHistoryMsg = historyMsg
666
+ ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
667
+ : false
668
+
669
+ // History sync progress tracking
670
+ if (historyMsg && shouldProcessHistoryMsg) {
671
+ const syncType = historyMsg.syncType
672
+
673
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP && !historySyncStatus.initialBootstrapComplete) {
674
+ historySyncStatus.initialBootstrapComplete = true
675
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
676
+ }
677
+
678
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && historyMsg.progress === 100 && !historySyncStatus.recentSyncComplete) {
679
+ historySyncStatus.recentSyncComplete = true
680
+ clearTimeout(historySyncPausedTimeout)
681
+ historySyncPausedTimeout = undefined
682
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
683
+ }
684
+
685
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
686
+ clearTimeout(historySyncPausedTimeout)
687
+ historySyncPausedTimeout = setTimeout(() => {
688
+ if (!historySyncStatus.recentSyncComplete) {
689
+ historySyncStatus.recentSyncComplete = true
690
+ ev.emit('messaging-history.status', { syncType: proto.HistorySync.HistorySyncType.RECENT, status: 'paused', explicit: false })
691
+ }
692
+ historySyncPausedTimeout = undefined
693
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS)
694
+ }
695
+ }
696
+
697
+ // SyncState machine
698
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
699
+ if (awaitingSyncTimeout) {
700
+ clearTimeout(awaitingSyncTimeout)
701
+ awaitingSyncTimeout = undefined
702
+ }
703
+ if (shouldProcessHistoryMsg) {
704
+ syncState = SyncState.Syncing
705
+ logger.info('Transitioned to Syncing state')
706
+ } else {
707
+ syncState = SyncState.Online
708
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
709
+ ev.flush()
710
+ }
711
+ }
712
+
713
+ const doAppStateSync = async () => {
714
+ if (syncState === SyncState.Syncing) {
715
+ blockedCollections.clear()
716
+ logger.info('Doing app state sync')
717
+ await resyncAppState(ALL_WA_PATCH_NAMES, true)
718
+ syncState = SyncState.Online
719
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
720
+ ev.flush()
721
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
722
+ ev.emit('creds.update', { accountSyncCounter })
723
+ }
724
+ }
725
+
726
+ await Promise.all([
727
+ (async () => { if (shouldProcessHistoryMsg) await doAppStateSync() })(),
728
+ processMessage(msg, {
729
+ signalRepository,
730
+ shouldProcessHistoryMsg,
731
+ placeholderResendCache,
732
+ ev,
733
+ creds: authState.creds,
734
+ keyStore: authState.keys,
735
+ logger,
736
+ options: config.options,
737
+ getMessage
738
+ })
739
+ ])
740
+
741
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare) {
742
+ if (blockedCollections.size > 0) {
743
+ const collections = [...blockedCollections]
744
+ blockedCollections.clear()
745
+ logger.info({ collections }, 'app state sync key arrived via protocol message, re-syncing blocked collections')
746
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync on key share'))
747
+ } else if (syncState === SyncState.Syncing) {
748
+ logger.info('App state sync key arrived, triggering app state sync')
749
+ await doAppStateSync()
750
+ }
751
+ }
752
+ })
753
+
754
+ // ─── WS handlers ──────────────────────────────────────────────────────────────
755
+
756
+ ws.on('CB:presence', handlePresenceUpdate)
757
+ ws.on('CB:chatstate', handlePresenceUpdate)
758
+
759
+ ws.on('CB:ib,,dirty', async (node) => {
760
+ const { attrs } = getBinaryNodeChild(node, 'dirty')
761
+ const type = attrs.type
762
+ switch (type) {
763
+ case 'account_sync':
764
+ if (attrs.timestamp) {
765
+ let { lastAccountSyncTimestamp } = authState.creds
766
+ if (lastAccountSyncTimestamp) await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
767
+ lastAccountSyncTimestamp = +attrs.timestamp
768
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
769
+ }
770
+ break
771
+ case 'groups':
772
+ break
773
+ default:
774
+ logger.info({ node }, 'received unknown sync')
775
+ break
776
+ }
777
+ })
778
+
779
+ // ─── Event listeners ──────────────────────────────────────────────────────────
780
+
781
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
782
+ if (connection === 'close') {
783
+ blockedCollections.clear()
784
+ clearTimeout(historySyncPausedTimeout)
785
+ historySyncPausedTimeout = undefined
786
+ }
787
+
788
+ if (connection === 'open') {
789
+ if (fireInitQueries) executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
790
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'))
791
+ }
792
+
793
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) return
794
+
795
+ historySyncStatus.initialBootstrapComplete = false
796
+ historySyncStatus.recentSyncComplete = false
797
+ clearTimeout(historySyncPausedTimeout)
798
+ historySyncPausedTimeout = undefined
799
+
800
+ syncState = SyncState.AwaitingInitialSync
801
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
802
+ ev.buffer()
803
+
804
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
805
+ syncType: proto.HistorySync.HistorySyncType.RECENT
806
+ }))
807
+
808
+ if (!willSyncHistory) {
809
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
810
+ syncState = SyncState.Online
811
+ setTimeout(() => ev.flush(), 0)
812
+ return
813
+ }
814
+
815
+ // On reconnection the server won't push history sync again — skip the wait
816
+ if (authState.creds.accountSyncCounter > 0) {
817
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.')
818
+ syncState = SyncState.Online
819
+ setTimeout(() => ev.flush(), 0)
820
+ return
821
+ }
822
+
823
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.')
824
+ if (awaitingSyncTimeout) clearTimeout(awaitingSyncTimeout)
825
+ awaitingSyncTimeout = setTimeout(() => {
826
+ if (syncState === SyncState.AwaitingInitialSync) {
827
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
828
+ syncState = SyncState.Online
829
+ ev.flush()
830
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
831
+ ev.emit('creds.update', { accountSyncCounter })
832
+ }
833
+ }, 20_000)
834
+ })
835
+
836
+ // Re-sync collections that were parked due to a missing app state key
837
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
838
+ if (!myAppStateKeyId || blockedCollections.size === 0) return
839
+ if (syncState === SyncState.Syncing) {
840
+ blockedCollections.clear()
841
+ return
842
+ }
843
+ const collections = [...blockedCollections]
844
+ blockedCollections.clear()
845
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections')
846
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'))
847
+ })
848
+
849
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
850
+ try {
851
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }])
852
+ } catch (error) {
853
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping')
854
+ }
855
+ })
856
+
857
+ // ─── Return ───────────────────────────────────────────────────────────────────
858
+
859
+ return {
860
+ ...sock,
861
+ createCallLink,
862
+ getBotListV2,
863
+ processingMutex,
864
+ messageMutex,
865
+ receiptMutex,
866
+ appStatePatchMutex,
867
+ notificationMutex,
868
+ fetchPrivacySettings,
869
+ upsertMessage,
870
+ appPatch,
871
+ sendPresenceUpdate,
872
+ presenceSubscribe,
873
+ profilePictureUrl,
874
+ fetchBlocklist,
875
+ fetchStatus,
876
+ fetchDisappearingDuration,
877
+ updateProfilePicture,
878
+ removeProfilePicture,
879
+ updateProfileStatus,
880
+ updateProfileName,
881
+ updateBlockStatus,
882
+ updateDisableLinkPreviewsPrivacy,
883
+ updateCallPrivacy,
884
+ updateMessagesPrivacy,
885
+ updateLastSeenPrivacy,
886
+ updateOnlinePrivacy,
887
+ updateProfilePicturePrivacy,
888
+ updateStatusPrivacy,
889
+ updateReadReceiptsPrivacy,
890
+ updateGroupsAddPrivacy,
891
+ updateDefaultDisappearingMode,
892
+ getBusinessProfile,
893
+ resyncAppState,
894
+ chatModify,
895
+ cleanDirtyBits,
896
+ addOrEditContact,
897
+ removeContact,
898
+ addLabel,
899
+ onWhatsApp,
900
+ checkStatusWA,
901
+ addChatLabel,
902
+ removeChatLabel,
903
+ addMessageLabel,
904
+ removeMessageLabel,
905
+ star,
906
+ addOrEditQuickReply,
907
+ removeQuickReply
908
+ }
909
+ }