dibosockets 1.0.2 → 1.0.3

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 (40) hide show
  1. package/WAProto/WAProto.proto +4775 -5619
  2. package/lib/Defaults/baileys-version.json +3 -3
  3. package/lib/Defaults/index.js +106 -122
  4. package/lib/Socket/RHandler.js +530 -448
  5. package/lib/Socket/business.js +260 -266
  6. package/lib/Socket/chats.js +908 -1137
  7. package/lib/Socket/index.js +10 -43
  8. package/lib/Socket/messages-recv.js +1054 -1065
  9. package/lib/Socket/messages-send.js +903 -881
  10. package/lib/Socket/newsletter.js +303 -286
  11. package/lib/Socket/socket.js +654 -666
  12. package/lib/Store/make-in-memory-store.js +439 -439
  13. package/lib/Types/Newsletter.js +38 -18
  14. package/lib/Utils/baileys-event-stream.js +63 -63
  15. package/lib/Utils/event-buffer.js +518 -518
  16. package/lib/Utils/generics.js +428 -432
  17. package/lib/Utils/index.js +36 -36
  18. package/lib/Utils/messages-media.js +887 -926
  19. package/lib/Utils/messages.js +1030 -1105
  20. package/lib/Utils/process-message.js +385 -404
  21. package/lib/Utils/use-multi-file-auth-state.js +125 -122
  22. package/lib/Utils/validate-connection.js +173 -229
  23. package/lib/WABinary/jid-utils.js +83 -85
  24. package/lib/index.js +86 -74
  25. package/package.json +2 -2
  26. package/lib/Api/Internet/growagarden.js +0 -28
  27. package/lib/Api/creator.json +0 -13
  28. package/lib/Api/downloader/tiktokdownload.js +0 -132
  29. package/lib/Api/index.js +0 -38
  30. package/lib/Api/nsfw/loli.js +0 -79
  31. package/lib/Api/stalker/githubstalk.js +0 -46
  32. package/lib/Api/stalker/stalkroblox.js +0 -94
  33. package/lib/Api/stalker/tiktokstalk.js +0 -68
  34. package/lib/Api/tools/ssweb.js +0 -38
  35. package/lib/Defaults/phonenumber_mcc.json +0 -223
  36. package/lib/Socket/communities.js +0 -441
  37. package/lib/Utils/async-iterable.js +0 -41
  38. package/lib/Utils/browser-utils.js +0 -35
  39. package/lib/Utils/message-retry-manager.js +0 -128
  40. package/lib/Utils/resolveJid.js +0 -52
@@ -1,1137 +1,908 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeChatsSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
- const WAProto_1 = require("../../WAProto");
10
- const Defaults_1 = require("../Defaults");
11
- const Types_1 = require("../Types");
12
- const Utils_1 = require("../Utils");
13
- const make_mutex_1 = require("../Utils/make-mutex");
14
- const process_message_1 = __importDefault(require("../Utils/process-message"));
15
- const WABinary_1 = require("../WABinary");
16
- const WAUSync_1 = require("../WAUSync");
17
- const usync_1 = require("./usync");
18
- const chalk = require('chalk');
19
- const MAX_SYNC_ATTEMPTS = 2;
20
- const SyncState = {
21
- Connecting: 'connecting',
22
- AwaitingInitialSync: 'awaiting_initial_sync',
23
- Syncing: 'syncing',
24
- Online: 'online'
25
- };
26
- const makeChatsSocket = (config) => {
27
- const {
28
- logger,
29
- markOnlineOnConnect,
30
- fireInitQueries,
31
- appStateMacVerification,
32
- shouldIgnoreJid,
33
- shouldSyncHistoryMessage,
34
- relayMessage, } = config;
35
- const sock = (0, usync_1.makeUSyncSocket)(config);
36
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, } = sock;
37
- let privacySettings;
38
- let syncState = SyncState.Connecting;
39
- let needToFlushWithAppStateSync = false;
40
- let pendingAppStateSync = false;
41
- let awaitingSyncTimeout;
42
- const processingMutex = (0, make_mutex_1.makeMutex)();
43
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
44
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
45
- useClones: false
46
- });
47
- if (!config.placeholderResendCache) {
48
- config.placeholderResendCache = placeholderResendCache;
49
- }
50
- const getAppStateSyncKey = async (keyId) => {
51
- const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
52
- return key;
53
- };
54
- const fetchPrivacySettings = async (force = false) => {
55
- if (!privacySettings || force) {
56
- const { content } = await query({
57
- tag: 'iq',
58
- attrs: {
59
- xmlns: 'privacy',
60
- to: WABinary_1.S_WHATSAPP_NET,
61
- type: 'get'
62
- },
63
- content: [
64
- { tag: 'privacy', attrs: {} }
65
- ]
66
- });
67
- privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
68
- }
69
- return privacySettings;
70
- };
71
- const privacyQuery = async (name, value) => {
72
- await query({
73
- tag: 'iq',
74
- attrs: {
75
- xmlns: 'privacy',
76
- to: WABinary_1.S_WHATSAPP_NET,
77
- type: 'set'
78
- },
79
- content: [{
80
- tag: 'privacy',
81
- attrs: {},
82
- content: [
83
- {
84
- tag: 'category',
85
- attrs: { name, value }
86
- }
87
- ]
88
- }]
89
- });
90
- };
91
- const updateMessagesPrivacy = async (value) => {
92
- await privacyQuery('messages', value);
93
- };
94
- const updateCallPrivacy = async (value) => {
95
- await privacyQuery('calladd', value);
96
- };
97
- const updateLastSeenPrivacy = async (value) => {
98
- await privacyQuery('last', value);
99
- };
100
- const updateOnlinePrivacy = async (value) => {
101
- await privacyQuery('online', value);
102
- };
103
- const updateProfilePicturePrivacy = async (value) => {
104
- await privacyQuery('profile', value);
105
- };
106
- const updateStatusPrivacy = async (value) => {
107
- await privacyQuery('status', value);
108
- };
109
- const updateReadReceiptsPrivacy = async (value) => {
110
- await privacyQuery('readreceipts', value);
111
- };
112
- const updateGroupsAddPrivacy = async (value) => {
113
- await privacyQuery('groupadd', value);
114
- };
115
- const updateDisableLinkPreviewsPrivacy = async (isPreviewsDisabled) => {
116
- return chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '');
117
- };
118
- const updateDefaultDisappearingMode = async (duration) => {
119
- await query({
120
- tag: 'iq',
121
- attrs: {
122
- xmlns: 'disappearing_mode',
123
- to: WABinary_1.S_WHATSAPP_NET,
124
- type: 'set'
125
- },
126
- content: [{
127
- tag: 'disappearing_mode',
128
- attrs: {
129
- duration: duration.toString()
130
- }
131
- }]
132
- });
133
- };
134
- const getBotListV2 = async () => {
135
- const resp = await query({
136
- tag: 'iq',
137
- attrs: {
138
- xmlns: 'bot',
139
- to: WABinary_1.S_WHATSAPP_NET,
140
- type: 'get'
141
- },
142
- content: [{
143
- tag: 'bot',
144
- attrs: {
145
- v: '2'
146
- }
147
- }]
148
- });
149
- const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
150
- const botList = [];
151
- for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
152
- if (section.attrs.type === 'all') {
153
- for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
154
- botList.push({
155
- jid: bot.attrs.jid,
156
- personaId: bot.attrs['persona_id']
157
- });
158
- }
159
- }
160
- }
161
- return botList;
162
- };
163
- const onWhatsApp = async (...jids) => {
164
- const usyncQuery = new WAUSync_1.USyncQuery()
165
- .withContactProtocol()
166
- .withLIDProtocol();
167
- for (const jid of jids) {
168
- const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
169
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
170
- }
171
- const results = await sock.executeUSyncQuery(usyncQuery);
172
- if (results) {
173
- return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
174
- }
175
- };
176
- const fetchStatus = async (...jids) => {
177
- const usyncQuery = new WAUSync_1.USyncQuery()
178
- .withStatusProtocol();
179
- for (const jid of jids) {
180
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
181
- }
182
- const result = await sock.executeUSyncQuery(usyncQuery);
183
- if (result) {
184
- return result.list;
185
- }
186
- };
187
- const cekid = async (link) => {
188
- try {
189
- let url;
190
- try {
191
- url = new URL(link);
192
- } catch {
193
- return {
194
- link,
195
- jid: "-",
196
- exists: false,
197
- IsBanned: true,
198
- metadata: "-",
199
- error: "Invalid link format"
200
- };
201
- }
202
-
203
- const isChannel =
204
- url.hostname === "whatsapp.com" &&
205
- url.pathname.startsWith("/channel/");
206
-
207
- if (!isChannel) {
208
- return {
209
- link,
210
- jid: "-",
211
- exists: false,
212
- IsBanned: true,
213
- metadata: "-",
214
- error: "Link bukan link channel WhatsApp"
215
- };
216
- }
217
-
218
- const code = url.pathname.split("/channel/")[1]?.split("/")[0];
219
-
220
- if (!code) {
221
- return {
222
- link,
223
- jid: "-",
224
- exists: false,
225
- IsBanned: true,
226
- metadata: "-",
227
- error: "Invalid channel code"
228
- };
229
- }
230
-
231
- let data = null;
232
-
233
- try {
234
- data = await conn.newsletterMetadata("invite", code);
235
- } catch {
236
- data = await conn.newsletterMetadata(code).catch(() => null);
237
- }
238
-
239
- if (!data?.id) {
240
- return {
241
- link,
242
- jid: "-",
243
- exists: false,
244
- IsBanned: true,
245
- metadata: "-",
246
- error: "Gagal mengambil metadata channel"
247
- };
248
- }
249
-
250
- return {
251
- link,
252
- jid: data.id,
253
- exists: true,
254
- IsBanned: false,
255
- metadata: {
256
- id: data.id || "-",
257
- name: data.name || "-",
258
- description: data.description || "-",
259
- subscribers: data.subscribers || "-",
260
- ownerJid: data.ownerJid || "-",
261
- invite: data.invite || "-",
262
- verification: data.verification || "-",
263
- state: data.state || "-",
264
- creation: data.creation || "-"
265
- },
266
- error: null
267
- };
268
-
269
- } catch (e) {
270
- return {
271
- link,
272
- jid: "-",
273
- exists: false,
274
- IsBanned: true,
275
- metadata: "-",
276
- error: e.message
277
- };
278
- }
279
- };
280
- const checkStatusWA = async (numberOrJid) => {
281
- try {
282
- const jid = numberOrJid.includes('@s.whatsapp.net')
283
- ? numberOrJid
284
- : numberOrJid.replace(/[^0-9]/g, '') + '@s.whatsapp.net'
285
-
286
- const exists = await onWhatsApp(jid)
287
- if (!exists || !exists[0]?.exists) {
288
- return {
289
- jid,
290
- IsBanned: true,
291
- Statusbio: "-",
292
- setAt: "-",
293
- businessProfile: {
294
- wid: "-",
295
- address: "-",
296
- description: "-",
297
- website: "-",
298
- email: "-",
299
- category: "-",
300
- business_hours: "-"
301
- }
302
- }
303
- }
304
-
305
- const fetched = await fetchStatus(jid).catch(() => [])
306
- const status = fetched?.[0]?.status?.status || "-"
307
- const setAt = fetched?.[0]?.status?.setAt || "-"
308
-
309
- const business = await getBusinessProfile(jid).catch(() => null)
310
-
311
- const businessProfile = business ? {
312
- wid: business.wid || "-",
313
- address: business.address || "-",
314
- description: business.description || "-",
315
- website: business.website?.[0] || "-",
316
- email: business.email || "-",
317
- category: business.category || "-",
318
- business_hours: business.business_hours || "-"
319
- } : {
320
- wid: "-",
321
- address: "-",
322
- description: "-",
323
- website: "-",
324
- email: "-",
325
- category: "-",
326
- business_hours: "-"
327
- }
328
-
329
- return {
330
- jid,
331
- IsBanned: false,
332
- Statusbio: status,
333
- setAt,
334
- businessProfile
335
- }
336
- } catch (e) {
337
- return {
338
- jid: numberOrJid,
339
- IsBanned: true,
340
- Statusbio: "-",
341
- setAt: "-",
342
- businessProfile: {
343
- wid: "-",
344
- address: "-",
345
- description: "-",
346
- website: "-",
347
- email: "-",
348
- category: "-",
349
- business_hours: "-"
350
- },
351
- error: e.message
352
- }
353
- }
354
- };
355
- const getBusinessProfile = async (jid) => {
356
- var _a, _b, _c, _d, _e, _f, _g;
357
- const results = await query({
358
- tag: 'iq',
359
- attrs: {
360
- to: 's.whatsapp.net',
361
- xmlns: 'w:biz',
362
- type: 'get'
363
- },
364
- content: [{
365
- tag: 'business_profile',
366
- attrs: { v: '244' },
367
- content: [{
368
- tag: 'profile',
369
- attrs: { jid }
370
- }]
371
- }]
372
- });
373
- const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
374
- const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
375
- if (profiles) {
376
- const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
377
- const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
378
- const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
379
- const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
380
- const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
381
- const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
382
- const businessHoursConfig = businessHours ?
383
- (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config') :
384
- undefined;
385
- const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
386
- return {
387
- wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
388
- address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
389
- description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
390
- website: websiteStr ? [websiteStr] : [],
391
- email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
392
- category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
393
- 'business_hours': {
394
- timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
395
- 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
396
- }
397
- };
398
- }
399
- };
400
-
401
-
402
- const fetchDisappearingDuration = async (...jids) => {
403
- const usyncQuery = new WAUSync_1.USyncQuery()
404
- .withDisappearingModeProtocol();
405
- for (const jid of jids) {
406
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
407
- }
408
- const result = await sock.executeUSyncQuery(usyncQuery);
409
- if (result) {
410
- return result.list;
411
- }
412
- };
413
- const updateProfilePicture = async (jid, content, dimensions) => {
414
- let targetJid;
415
- if (!jid) {
416
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
417
- }
418
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
419
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
420
- }
421
- const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions);
422
- await query({
423
- tag: 'iq',
424
- attrs: {
425
- target: targetJid,
426
- to: WABinary_1.S_WHATSAPP_NET,
427
- type: 'set',
428
- xmlns: 'w:profile:picture'
429
- },
430
- content: [
431
- {
432
- tag: 'picture',
433
- attrs: { type: 'image' },
434
- content: img
435
- }
436
- ]
437
- });
438
- };
439
- const removeProfilePicture = async (jid) => {
440
- let targetJid;
441
- if (!jid) {
442
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
443
- }
444
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
445
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
446
- }
447
- await query({
448
- tag: 'iq',
449
- attrs: {
450
- target: targetJid,
451
- to: WABinary_1.S_WHATSAPP_NET,
452
- type: 'set',
453
- xmlns: 'w:profile:picture'
454
- }
455
- });
456
- };
457
- const updateProfileStatus = async (status) => {
458
- await query({
459
- tag: 'iq',
460
- attrs: {
461
- to: WABinary_1.S_WHATSAPP_NET,
462
- type: 'set',
463
- xmlns: 'status'
464
- },
465
- content: [
466
- {
467
- tag: 'status',
468
- attrs: {},
469
- content: Buffer.from(status, 'utf-8')
470
- }
471
- ]
472
- });
473
- };
474
- const updateProfileName = async (name) => {
475
- await chatModify({ pushNameSetting: name }, '');
476
- };
477
- const fetchBlocklist = async () => {
478
- const result = await query({
479
- tag: 'iq',
480
- attrs: {
481
- xmlns: 'blocklist',
482
- to: WABinary_1.S_WHATSAPP_NET,
483
- type: 'get'
484
- }
485
- });
486
- const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
487
- return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
488
- .map(n => n.attrs.jid);
489
- };
490
- const updateBlockStatus = async (jid, action) => {
491
- await query({
492
- tag: 'iq',
493
- attrs: {
494
- xmlns: 'blocklist',
495
- to: WABinary_1.S_WHATSAPP_NET,
496
- type: 'set'
497
- },
498
- content: [
499
- {
500
- tag: 'item',
501
- attrs: {
502
- action,
503
- jid
504
- }
505
- }
506
- ]
507
- });
508
- };
509
-
510
- const cleanDirtyBits = async (type, fromTimestamp) => {
511
- logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
512
- await sendNode({
513
- tag: 'iq',
514
- attrs: {
515
- to: WABinary_1.S_WHATSAPP_NET,
516
- type: 'set',
517
- xmlns: 'urn:xmpp:whatsapp:dirty',
518
- id: generateMessageTag(),
519
- },
520
- content: [
521
- {
522
- tag: 'clean',
523
- attrs: {
524
- type,
525
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
526
- }
527
- }
528
- ]
529
- });
530
- };
531
- const newAppStateChunkHandler = (isInitialSync) => {
532
- return {
533
- onMutation(mutation) {
534
- (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
535
- }
536
- };
537
- };
538
- const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
539
- const initialVersionMap = {};
540
- const globalMutationMap = {};
541
- await authState.keys.transaction(async () => {
542
- var _a;
543
- const collectionsToHandle = new Set(collections);
544
- const attemptsMap = {};
545
- while (collectionsToHandle.size) {
546
- const states = {};
547
- const nodes = [];
548
- for (const name of collectionsToHandle) {
549
- const result = await authState.keys.get('app-state-sync-version', [name]);
550
- let state = result[name];
551
- if (state) {
552
- if (typeof initialVersionMap[name] === 'undefined') {
553
- initialVersionMap[name] = state.version;
554
- }
555
- }
556
- else {
557
- state = (0, Utils_1.newLTHashState)();
558
- }
559
- states[name] = state;
560
- logger.info(`resyncing ${name} from v${state.version}`);
561
- nodes.push({
562
- tag: 'collection',
563
- attrs: {
564
- name,
565
- version: state.version.toString(),
566
- 'return_snapshot': (!state.version).toString()
567
- }
568
- });
569
- }
570
- const result = await query({
571
- tag: 'iq',
572
- attrs: {
573
- to: WABinary_1.S_WHATSAPP_NET,
574
- xmlns: 'w:sync:app:state',
575
- type: 'set'
576
- },
577
- content: [
578
- {
579
- tag: 'sync',
580
- attrs: {},
581
- content: nodes
582
- }
583
- ]
584
- });
585
- const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
586
- for (const key in decoded) {
587
- const name = key;
588
- const { patches, hasMorePatches, snapshot } = decoded[name];
589
- try {
590
- if (snapshot) {
591
- const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
592
- states[name] = newState;
593
- Object.assign(globalMutationMap, mutationMap);
594
- logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
595
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
596
- }
597
- if (patches.length) {
598
- const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
599
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
600
- logger.info(`synced ${name} to v${newState.version}`);
601
- initialVersionMap[name] = newState.version;
602
- Object.assign(globalMutationMap, mutationMap);
603
- }
604
- if (hasMorePatches) {
605
- logger.info(`${name} has more patches...`);
606
- }
607
- else {
608
- collectionsToHandle.delete(name);
609
- }
610
- }
611
- catch (error) {
612
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
613
- || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
614
- || error.name === 'TypeError';
615
- logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
616
- await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
617
- attemptsMap[name] = (attemptsMap[name] || 0) + 1;
618
- if (isIrrecoverableError) {
619
- collectionsToHandle.delete(name);
620
- }
621
- }
622
- }
623
- }
624
- });
625
- const { onMutation } = newAppStateChunkHandler(isInitialSync);
626
- for (const key in globalMutationMap) {
627
- onMutation(globalMutationMap[key]);
628
- }
629
- });
630
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
631
- var _a;
632
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
633
- try {
634
- const result = await query({
635
- tag: 'iq',
636
- attrs: {
637
- target: jid,
638
- to: WABinary_1.S_WHATSAPP_NET,
639
- type: 'get',
640
- xmlns: 'w:profile:picture'
641
- },
642
- content: [
643
- { tag: 'picture', attrs: { type, query: 'url' } }
644
- ]
645
- }, timeoutMs);
646
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
647
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
648
- } catch (error) {
649
- if (error.message?.includes('item-not-found') ||
650
- error.output?.payload?.statusCode === 404 ||
651
- error.statusCode === 404) {
652
- logger.info(chalk.gray(`[INFO] Profile pic not found for ${jid}, using fallback`));
653
- return {
654
- eurl: undefined,
655
- id: jid.split('@')[0],
656
- status: null,
657
- img: null
658
- };
659
- }
660
- throw error;
661
- }
662
- };
663
- const createCallLink = async (type, event, timeoutMs) => {
664
- const result = await query({
665
- tag: 'call',
666
- attrs: {
667
- id: generateMessageTag(),
668
- to: '@call'
669
- },
670
- content: [
671
- {
672
- tag: 'link_create',
673
- attrs: { media: type },
674
- content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
675
- }
676
- ]
677
- }, timeoutMs);
678
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'link_create');
679
- return child?.attrs?.token;
680
- };
681
- const sendPresenceUpdate = async (type, toJid) => {
682
- const me = authState.creds.me;
683
- if (type === 'available' || type === 'unavailable') {
684
- if (!me.name) {
685
- logger.warn('no name present, ignoring presence update request...');
686
- return;
687
- }
688
- ev.emit('connection.update', { isOnline: type === 'available' });
689
- await sendNode({
690
- tag: 'presence',
691
- attrs: {
692
- name: me.name.replace(/@/g, ''),
693
- type
694
- }
695
- });
696
- }
697
- else {
698
- const { server } = (0, WABinary_1.jidDecode)(toJid);
699
- const isLid = server === 'lid';
700
- await sendNode({
701
- tag: 'chatstate',
702
- attrs: {
703
- from: isLid ? me.lid : me.id,
704
- to: toJid,
705
- },
706
- content: [
707
- {
708
- tag: type === 'recording' ? 'composing' : type,
709
- attrs: type === 'recording' ? { media: 'audio' } : {}
710
- }
711
- ]
712
- });
713
- }
714
- };
715
- const presenceSubscribe = (toJid, tcToken) => (sendNode({
716
- tag: 'presence',
717
- attrs: {
718
- to: toJid,
719
- id: generateMessageTag(),
720
- type: 'subscribe'
721
- },
722
- content: tcToken
723
- ? [
724
- {
725
- tag: 'tctoken',
726
- attrs: {},
727
- content: tcToken
728
- }
729
- ]
730
- : undefined
731
- }));
732
- const handlePresenceUpdate = ({ tag, attrs, content }) => {
733
- var _a;
734
- let presence;
735
- const jid = attrs.from;
736
- const participant = attrs.participant || attrs.from;
737
- if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
738
- return;
739
- }
740
- if (tag === 'presence') {
741
- presence = {
742
- lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
743
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
744
- };
745
- }
746
- else if (Array.isArray(content)) {
747
- const [firstChild] = content;
748
- let type = firstChild.tag;
749
- if (type === 'paused') {
750
- type = 'available';
751
- }
752
- if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
753
- type = 'recording';
754
- }
755
- presence = { lastKnownPresence: type };
756
- }
757
- else {
758
- logger.error({ tag, attrs, content }, 'recv invalid presence node');
759
- }
760
- if (presence) {
761
- ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
762
- }
763
- };
764
- const appPatch = async (patchCreate) => {
765
- const name = patchCreate.type;
766
- const myAppStateKeyId = authState.creds.myAppStateKeyId;
767
- if (!myAppStateKeyId) {
768
- throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
769
- }
770
- let initial;
771
- let encodeResult;
772
- await processingMutex.mutex(async () => {
773
- await authState.keys.transaction(async () => {
774
- logger.debug({ patch: patchCreate }, 'applying app patch');
775
- await resyncAppState([name], false);
776
- const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
777
- initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
778
- encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
779
- const { patch, state } = encodeResult;
780
- const node = {
781
- tag: 'iq',
782
- attrs: {
783
- to: WABinary_1.S_WHATSAPP_NET,
784
- type: 'set',
785
- xmlns: 'w:sync:app:state'
786
- },
787
- content: [
788
- {
789
- tag: 'sync',
790
- attrs: {},
791
- content: [
792
- {
793
- tag: 'collection',
794
- attrs: {
795
- name,
796
- version: (state.version - 1).toString(),
797
- 'return_snapshot': 'false'
798
- },
799
- content: [
800
- {
801
- tag: 'patch',
802
- attrs: {},
803
- content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
804
- }
805
- ]
806
- }
807
- ]
808
- }
809
- ]
810
- };
811
- await query(node);
812
- await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
813
- });
814
- });
815
- if (config.emitOwnEvents) {
816
- const { onMutation } = newAppStateChunkHandler(false);
817
- const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
818
- for (const key in mutationMap) {
819
- onMutation(mutationMap[key]);
820
- }
821
- }
822
- };
823
- const fetchProps = async () => {
824
- var _a, _b, _c;
825
- const resultNode = await query({
826
- tag: 'iq',
827
- attrs: {
828
- to: WABinary_1.S_WHATSAPP_NET,
829
- xmlns: 'w',
830
- type: 'get',
831
- },
832
- content: [
833
- { tag: 'props', attrs: {
834
- protocol: '2',
835
- hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
836
- } }
837
- ]
838
- });
839
- const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
840
- let props = {};
841
- if (propsNode) {
842
- if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) {
843
- authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
844
- ev.emit('creds.update', authState.creds);
845
- }
846
- props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
847
- }
848
- logger.debug('fetched props');
849
- return props;
850
- };
851
- const chatModify = (mod, jid) => {
852
- const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
853
- return appPatch(patch);
854
- };
855
- const star = (jid, messages, star) => {
856
- return chatModify({
857
- star: {
858
- messages,
859
- star
860
- }
861
- }, jid);
862
- };
863
- const addOrEditContact = (jid, contact) => {
864
- return chatModify({ contact }, jid);
865
- };
866
- const removeContact = (jid) => {
867
- return chatModify({ contact: null }, jid);
868
- };
869
-
870
- const addLabelMember = async (jid, label, timestamp = Date.now()) => {
871
- try {
872
- return await relayMessage(
873
- jid,
874
- {
875
- protocolMessage: {
876
- type: 30,
877
- memberLabel: {
878
- label,
879
- labelTimestamp: timestamp
880
- }
881
- }
882
- },
883
- {}
884
- )
885
- } catch (e) {
886
- logger.error('Failed addLabelMember: ' + e)
887
- throw e
888
- }
889
- }
890
-
891
- const removeLabelMember = async (jid) => {
892
- try {
893
- return await relayMessage(
894
- jid,
895
- {
896
- protocolMessage: {
897
- type: 30,
898
- memberLabel: {
899
- label: ''
900
- }
901
- }
902
- },
903
- {}
904
- )
905
- } catch (e) {
906
- logger.error('Failed removeLabelMember: ' + e)
907
- throw e
908
- }
909
- }
910
- const addLabel = (jid, labels) => {
911
- return chatModify({ addLabel: { ...labels } }, jid);
912
- };
913
- const addChatLabel = (jid, labelId) => {
914
- return chatModify({
915
- addChatLabel: {
916
- labelId
917
- }
918
- }, jid);
919
- };
920
- const removeChatLabel = (jid, labelId) => {
921
- return chatModify({
922
- removeChatLabel: {
923
- labelId
924
- }
925
- }, jid);
926
- };
927
- const addMessageLabel = (jid, messageId, labelId) => {
928
- return chatModify({
929
- addMessageLabel: {
930
- messageId,
931
- labelId
932
- }
933
- }, jid);
934
- };
935
- const removeMessageLabel = (jid, messageId, labelId) => {
936
- return chatModify({
937
- removeMessageLabel: {
938
- messageId,
939
- labelId
940
- }
941
- }, jid);
942
- };
943
- const executeInitQueries = async () => {
944
- await Promise.all([
945
- fetchProps(),
946
- fetchBlocklist(),
947
- fetchPrivacySettings(),
948
- ]);
949
- };
950
- const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
951
- var _a, _b, _c;
952
- ev.emit('messages.upsert', { messages: [msg], type });
953
- if (!!msg.pushName) {
954
- let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
955
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
956
- if (!msg.key.fromMe) {
957
- ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
958
- }
959
- if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
960
- ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
961
- }
962
- }
963
- const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
964
- const shouldProcessHistoryMsg = historyMsg
965
- ? (shouldSyncHistoryMessage(historyMsg)
966
- && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
967
- : false;
968
- if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
969
- if (awaitingSyncTimeout) {
970
- clearTimeout(awaitingSyncTimeout);
971
- awaitingSyncTimeout = undefined;
972
- }
973
- if (shouldProcessHistoryMsg) {
974
- syncState = SyncState.Syncing;
975
- logger.info('Transitioned to Syncing state');
976
- } else {
977
- syncState = SyncState.Online;
978
- logger.info('History sync skipped, transitioning to Online state and flushing buffer');
979
- ev.flush();
980
- }
981
- }
982
- const doAppStateSync = async () => {
983
- if (syncState === SyncState.Syncing) {
984
- logger.info('Doing app state sync');
985
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
986
- syncState = SyncState.Online;
987
- logger.info('App state sync complete, transitioning to Online state and flushing buffer');
988
- ev.flush();
989
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
990
- ev.emit('creds.update', { accountSyncCounter });
991
- }
992
- };
993
- if (historyMsg && !authState.creds.myAppStateKeyId) {
994
- logger.warn('skipping app state sync, as myAppStateKeyId is not set');
995
- pendingAppStateSync = true;
996
- }
997
- await Promise.all([
998
- (async () => {
999
- if (historyMsg
1000
- && authState.creds.myAppStateKeyId) {
1001
- pendingAppStateSync = false;
1002
- await doAppStateSync();
1003
- }
1004
- })(),
1005
- (0, process_message_1.default)(msg, {
1006
- signalRepository,
1007
- shouldProcessHistoryMsg,
1008
- placeholderResendCache,
1009
- ev,
1010
- creds: authState.creds,
1011
- keyStore: authState.keys,
1012
- logger,
1013
- options: config.options,
1014
- getMessage: config.getMessage,
1015
- })
1016
- ]);
1017
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
1018
- && pendingAppStateSync) {
1019
- await doAppStateSync();
1020
- pendingAppStateSync = false;
1021
- }
1022
- });
1023
- ws.on('CB:presence', handlePresenceUpdate);
1024
- ws.on('CB:chatstate', handlePresenceUpdate);
1025
- ws.on('CB:ib,,dirty', async (node) => {
1026
- const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
1027
- const type = attrs.type;
1028
- switch (type) {
1029
- case 'account_sync':
1030
- if (attrs.timestamp) {
1031
- let { lastAccountSyncTimestamp } = authState.creds;
1032
- if (lastAccountSyncTimestamp) {
1033
- await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
1034
- }
1035
- lastAccountSyncTimestamp = +attrs.timestamp;
1036
- ev.emit('creds.update', { lastAccountSyncTimestamp });
1037
- }
1038
- break;
1039
- case 'groups':
1040
- break;
1041
- default:
1042
- logger.info({ node }, 'received unknown sync');
1043
- break;
1044
- }
1045
- });
1046
- ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1047
- var _a;
1048
- if (connection === 'open') {
1049
- if (fireInitQueries) {
1050
- executeInitQueries()
1051
- .catch(error => onUnexpectedError(error, 'init queries'));
1052
- }
1053
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
1054
- .catch(error => onUnexpectedError(error, 'presence update requests'));
1055
- }
1056
- if (receivedPendingNotifications &&
1057
- !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
1058
- ev.buffer();
1059
- needToFlushWithAppStateSync = true;
1060
- }
1061
- if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1062
- return;
1063
- }
1064
- syncState = SyncState.AwaitingInitialSync;
1065
- logger.info('Connection is now AwaitingInitialSync, buffering events');
1066
- ev.buffer();
1067
- const willSyncHistory = shouldSyncHistoryMessage(
1068
- WAProto_1.proto.Message.HistorySyncNotification.create({
1069
- syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
1070
- })
1071
- );
1072
- if (!willSyncHistory) {
1073
- logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1074
- syncState = SyncState.Online;
1075
- setTimeout(() => ev.flush(), 0);
1076
- return;
1077
- }
1078
- logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1079
- if (awaitingSyncTimeout) {
1080
- clearTimeout(awaitingSyncTimeout);
1081
- }
1082
- awaitingSyncTimeout = setTimeout(() => {
1083
- if (syncState === SyncState.AwaitingInitialSync) {
1084
- logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1085
- syncState = SyncState.Online;
1086
- ev.flush();
1087
- }
1088
- }, 20000);
1089
- });
1090
- return {
1091
- ...sock,
1092
- createCallLink,
1093
- getBotListV2,
1094
- processingMutex,
1095
- fetchPrivacySettings,
1096
- upsertMessage,
1097
- appPatch,
1098
- sendPresenceUpdate,
1099
- presenceSubscribe,
1100
- profilePictureUrl,
1101
- onWhatsApp,
1102
- checkStatusWA,
1103
- fetchBlocklist,
1104
- fetchDisappearingDuration,
1105
- fetchStatus,
1106
- updateProfilePicture,
1107
- removeProfilePicture,
1108
- updateProfileStatus,
1109
- updateProfileName,
1110
- updateBlockStatus,
1111
- updateDisableLinkPreviewsPrivacy,
1112
- updateCallPrivacy,
1113
- updateMessagesPrivacy,
1114
- updateLastSeenPrivacy,
1115
- updateOnlinePrivacy,
1116
- updateProfilePicturePrivacy,
1117
- updateStatusPrivacy,
1118
- updateReadReceiptsPrivacy,
1119
- updateGroupsAddPrivacy,
1120
- updateDefaultDisappearingMode,
1121
- getBusinessProfile,
1122
- resyncAppState,
1123
- chatModify,
1124
- cleanDirtyBits,
1125
- addOrEditContact,
1126
- removeContact,
1127
- addLabel,
1128
- addChatLabel,
1129
- removeChatLabel,
1130
- addMessageLabel,
1131
- removeMessageLabel,
1132
- star,
1133
- addLabelMember,
1134
- removeLabelMember
1135
- };
1136
- };
1137
- exports.makeChatsSocket = makeChatsSocket;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeChatsSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Types_1 = require("../Types");
12
+ const Utils_1 = require("../Utils");
13
+ const make_mutex_1 = require("../Utils/make-mutex");
14
+ const process_message_1 = __importDefault(require("../Utils/process-message"));
15
+ const WABinary_1 = require("../WABinary");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const usync_1 = require("./usync");
18
+ const MAX_SYNC_ATTEMPTS = 2;
19
+ const makeChatsSocket = (config) => {
20
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
+ const sock = (0, usync_1.makeUSyncSocket)(config);
22
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
23
+ let privacySettings;
24
+ let needToFlushWithAppStateSync = false;
25
+ let pendingAppStateSync = false;
26
+ /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
27
+ const processingMutex = (0, make_mutex_1.makeMutex)();
28
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
29
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
30
+ useClones: false
31
+ });
32
+ if (!config.placeholderResendCache) {
33
+ config.placeholderResendCache = placeholderResendCache;
34
+ }
35
+ /** helper function to fetch the given app state sync key */
36
+ const getAppStateSyncKey = async (keyId) => {
37
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
38
+ return key;
39
+ };
40
+ const fetchPrivacySettings = async (force = false) => {
41
+ if (!privacySettings || force) {
42
+ const { content } = await query({
43
+ tag: 'iq',
44
+ attrs: {
45
+ xmlns: 'privacy',
46
+ to: WABinary_1.S_WHATSAPP_NET,
47
+ type: 'get'
48
+ },
49
+ content: [
50
+ { tag: 'privacy', attrs: {} }
51
+ ]
52
+ });
53
+ privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
54
+ }
55
+ return privacySettings;
56
+ };
57
+ /** helper function to run a privacy IQ query */
58
+ const privacyQuery = async (name, value) => {
59
+ await query({
60
+ tag: 'iq',
61
+ attrs: {
62
+ xmlns: 'privacy',
63
+ to: WABinary_1.S_WHATSAPP_NET,
64
+ type: 'set'
65
+ },
66
+ content: [{
67
+ tag: 'privacy',
68
+ attrs: {},
69
+ content: [
70
+ {
71
+ tag: 'category',
72
+ attrs: { name, value }
73
+ }
74
+ ]
75
+ }]
76
+ });
77
+ };
78
+ const updateMessagesPrivacy = async (value) => {
79
+ await privacyQuery('messages', value);
80
+ };
81
+ const updateCallPrivacy = async (value) => {
82
+ await privacyQuery('calladd', value);
83
+ };
84
+ const updateLastSeenPrivacy = async (value) => {
85
+ await privacyQuery('last', value);
86
+ };
87
+ const updateOnlinePrivacy = async (value) => {
88
+ await privacyQuery('online', value);
89
+ };
90
+ const updateProfilePicturePrivacy = async (value) => {
91
+ await privacyQuery('profile', value);
92
+ };
93
+ const updateStatusPrivacy = async (value) => {
94
+ await privacyQuery('status', value);
95
+ };
96
+ const updateReadReceiptsPrivacy = async (value) => {
97
+ await privacyQuery('readreceipts', value);
98
+ };
99
+ const updateGroupsAddPrivacy = async (value) => {
100
+ await privacyQuery('groupadd', value);
101
+ };
102
+ const updateDefaultDisappearingMode = async (duration) => {
103
+ await query({
104
+ tag: 'iq',
105
+ attrs: {
106
+ xmlns: 'disappearing_mode',
107
+ to: WABinary_1.S_WHATSAPP_NET,
108
+ type: 'set'
109
+ },
110
+ content: [{
111
+ tag: 'disappearing_mode',
112
+ attrs: {
113
+ duration: duration.toString()
114
+ }
115
+ }]
116
+ });
117
+ };
118
+ const getBotListV2 = async () => {
119
+ const resp = await query({
120
+ tag: 'iq',
121
+ attrs: {
122
+ xmlns: 'bot',
123
+ to: WABinary_1.S_WHATSAPP_NET,
124
+ type: 'get'
125
+ },
126
+ content: [{
127
+ tag: 'bot',
128
+ attrs: {
129
+ v: '2'
130
+ }
131
+ }]
132
+ });
133
+ const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
134
+ const botList = [];
135
+ for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
136
+ if (section.attrs.type === 'all') {
137
+ for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
138
+ botList.push({
139
+ jid: bot.attrs.jid,
140
+ personaId: bot.attrs['persona_id']
141
+ });
142
+ }
143
+ }
144
+ }
145
+ return botList;
146
+ };
147
+ const onWhatsApp = async (...jids) => {
148
+ const usyncQuery = new WAUSync_1.USyncQuery()
149
+ .withContactProtocol()
150
+ .withLIDProtocol();
151
+ for (const jid of jids) {
152
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
153
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
154
+ }
155
+ const results = await sock.executeUSyncQuery(usyncQuery);
156
+ if (results) {
157
+ return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
158
+ }
159
+ };
160
+ const fetchStatus = async (...jids) => {
161
+ const usyncQuery = new WAUSync_1.USyncQuery()
162
+ .withStatusProtocol();
163
+ for (const jid of jids) {
164
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
165
+ }
166
+ const result = await sock.executeUSyncQuery(usyncQuery);
167
+ if (result) {
168
+ return result.list;
169
+ }
170
+ };
171
+ const checkStatusWA = async (numberOrJid) => {
172
+ try {
173
+ const jid = numberOrJid.includes('@s.whatsapp.net')
174
+ ? numberOrJid
175
+ : numberOrJid.replace(/[^0-9]/g, '') + '@s.whatsapp.net'
176
+
177
+ const exists = await onWhatsApp(jid)
178
+ if (!exists || !exists[0]?.exists) {
179
+ return {
180
+ jid,
181
+ IsBanned: true,
182
+ Statusbio: null,
183
+ setAt: null
184
+ }
185
+ }
186
+
187
+ const fetched = await fetchStatus(jid).catch(() => [])
188
+ const status = fetched?.[0]?.status?.status || null
189
+ const setAt = fetched?.[0]?.status?.setAt || null
190
+
191
+ return {
192
+ jid,
193
+ IsBanned: false,
194
+ Statusbio: status,
195
+ setAt
196
+ }
197
+ } catch (e) {
198
+ return {
199
+ jid: numberOrJid,
200
+ IsBanned: true,
201
+ Statusbio: null,
202
+ setAt: null,
203
+ error: e.message
204
+ }
205
+ }
206
+ }
207
+ const fetchDisappearingDuration = async (...jids) => {
208
+ const usyncQuery = new WAUSync_1.USyncQuery()
209
+ .withDisappearingModeProtocol();
210
+ for (const jid of jids) {
211
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
212
+ }
213
+ const result = await sock.executeUSyncQuery(usyncQuery);
214
+ if (result) {
215
+ return result.list;
216
+ }
217
+ };
218
+ /** update the profile picture for yourself or a group */
219
+ const updateProfilePicture = async (jid, content) => {
220
+ let targetJid;
221
+ if (!jid) {
222
+ throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
223
+ }
224
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
225
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
226
+ }
227
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
228
+ await query({
229
+ tag: 'iq',
230
+ attrs: {
231
+ target: targetJid,
232
+ to: WABinary_1.S_WHATSAPP_NET,
233
+ type: 'set',
234
+ xmlns: 'w:profile:picture'
235
+ },
236
+ content: [
237
+ {
238
+ tag: 'picture',
239
+ attrs: { type: 'image' },
240
+ content: img
241
+ }
242
+ ]
243
+ });
244
+ };
245
+ /** remove the profile picture for yourself or a group */
246
+ const removeProfilePicture = async (jid) => {
247
+ let targetJid;
248
+ if (!jid) {
249
+ throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
250
+ }
251
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
252
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
253
+ }
254
+ await query({
255
+ tag: 'iq',
256
+ attrs: {
257
+ target: targetJid,
258
+ to: WABinary_1.S_WHATSAPP_NET,
259
+ type: 'set',
260
+ xmlns: 'w:profile:picture'
261
+ }
262
+ });
263
+ };
264
+ /** update the profile status for yourself */
265
+ const updateProfileStatus = async (status) => {
266
+ await query({
267
+ tag: 'iq',
268
+ attrs: {
269
+ to: WABinary_1.S_WHATSAPP_NET,
270
+ type: 'set',
271
+ xmlns: 'status'
272
+ },
273
+ content: [
274
+ {
275
+ tag: 'status',
276
+ attrs: {},
277
+ content: Buffer.from(status, 'utf-8')
278
+ }
279
+ ]
280
+ });
281
+ };
282
+ const updateProfileName = async (name) => {
283
+ await chatModify({ pushNameSetting: name }, '');
284
+ };
285
+ const fetchBlocklist = async () => {
286
+ const result = await query({
287
+ tag: 'iq',
288
+ attrs: {
289
+ xmlns: 'blocklist',
290
+ to: WABinary_1.S_WHATSAPP_NET,
291
+ type: 'get'
292
+ }
293
+ });
294
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
295
+ return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
296
+ .map(n => n.attrs.jid);
297
+ };
298
+ const updateBlockStatus = async (jid, action) => {
299
+ await query({
300
+ tag: 'iq',
301
+ attrs: {
302
+ xmlns: 'blocklist',
303
+ to: WABinary_1.S_WHATSAPP_NET,
304
+ type: 'set'
305
+ },
306
+ content: [
307
+ {
308
+ tag: 'item',
309
+ attrs: {
310
+ action,
311
+ jid
312
+ }
313
+ }
314
+ ]
315
+ });
316
+ };
317
+ const getBusinessProfile = async (jid) => {
318
+ var _a, _b, _c, _d, _e, _f, _g;
319
+ const results = await query({
320
+ tag: 'iq',
321
+ attrs: {
322
+ to: 's.whatsapp.net',
323
+ xmlns: 'w:biz',
324
+ type: 'get'
325
+ },
326
+ content: [{
327
+ tag: 'business_profile',
328
+ attrs: { v: '244' },
329
+ content: [{
330
+ tag: 'profile',
331
+ attrs: { jid }
332
+ }]
333
+ }]
334
+ });
335
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
336
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
337
+ if (profiles) {
338
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
339
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
340
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
341
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
342
+ const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
343
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
344
+ const businessHoursConfig = businessHours
345
+ ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
346
+ : undefined;
347
+ const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
348
+ return {
349
+ wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
350
+ address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
351
+ description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
352
+ website: websiteStr ? [websiteStr] : [],
353
+ email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
354
+ category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
355
+ 'business_hours': {
356
+ timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
357
+ 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
358
+ }
359
+ };
360
+ }
361
+ };
362
+ const cleanDirtyBits = async (type, fromTimestamp) => {
363
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
364
+ await sendNode({
365
+ tag: 'iq',
366
+ attrs: {
367
+ to: WABinary_1.S_WHATSAPP_NET,
368
+ type: 'set',
369
+ xmlns: 'urn:xmpp:whatsapp:dirty',
370
+ id: generateMessageTag(),
371
+ },
372
+ content: [
373
+ {
374
+ tag: 'clean',
375
+ attrs: {
376
+ type,
377
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
378
+ }
379
+ }
380
+ ]
381
+ });
382
+ };
383
+ const newAppStateChunkHandler = (isInitialSync) => {
384
+ return {
385
+ onMutation(mutation) {
386
+ (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
387
+ }
388
+ };
389
+ };
390
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
391
+ // we use this to determine which events to fire
392
+ // otherwise when we resync from scratch -- all notifications will fire
393
+ const initialVersionMap = {};
394
+ const globalMutationMap = {};
395
+ await authState.keys.transaction(async () => {
396
+ var _a;
397
+ const collectionsToHandle = new Set(collections);
398
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
399
+ const attemptsMap = {};
400
+ // keep executing till all collections are done
401
+ // sometimes a single patch request will not return all the patches (God knows why)
402
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
403
+ while (collectionsToHandle.size) {
404
+ const states = {};
405
+ const nodes = [];
406
+ for (const name of collectionsToHandle) {
407
+ const result = await authState.keys.get('app-state-sync-version', [name]);
408
+ let state = result[name];
409
+ if (state) {
410
+ if (typeof initialVersionMap[name] === 'undefined') {
411
+ initialVersionMap[name] = state.version;
412
+ }
413
+ }
414
+ else {
415
+ state = (0, Utils_1.newLTHashState)();
416
+ }
417
+ states[name] = state;
418
+ logger.info(`resyncing ${name} from v${state.version}`);
419
+ nodes.push({
420
+ tag: 'collection',
421
+ attrs: {
422
+ name,
423
+ version: state.version.toString(),
424
+ // return snapshot if being synced from scratch
425
+ 'return_snapshot': (!state.version).toString()
426
+ }
427
+ });
428
+ }
429
+ const result = await query({
430
+ tag: 'iq',
431
+ attrs: {
432
+ to: WABinary_1.S_WHATSAPP_NET,
433
+ xmlns: 'w:sync:app:state',
434
+ type: 'set'
435
+ },
436
+ content: [
437
+ {
438
+ tag: 'sync',
439
+ attrs: {},
440
+ content: nodes
441
+ }
442
+ ]
443
+ });
444
+ // extract from binary node
445
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
446
+ for (const key in decoded) {
447
+ const name = key;
448
+ const { patches, hasMorePatches, snapshot } = decoded[name];
449
+ try {
450
+ if (snapshot) {
451
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
452
+ states[name] = newState;
453
+ Object.assign(globalMutationMap, mutationMap);
454
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
455
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
456
+ }
457
+ // only process if there are syncd patches
458
+ if (patches.length) {
459
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
460
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
461
+ logger.info(`synced ${name} to v${newState.version}`);
462
+ initialVersionMap[name] = newState.version;
463
+ Object.assign(globalMutationMap, mutationMap);
464
+ }
465
+ if (hasMorePatches) {
466
+ logger.info(`${name} has more patches...`);
467
+ }
468
+ else { // collection is done with sync
469
+ collectionsToHandle.delete(name);
470
+ }
471
+ }
472
+ catch (error) {
473
+ // if retry attempts overshoot
474
+ // or key not found
475
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
476
+ || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
477
+ || error.name === 'TypeError';
478
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
479
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
480
+ // increment number of retries
481
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
482
+ if (isIrrecoverableError) {
483
+ // stop retrying
484
+ collectionsToHandle.delete(name);
485
+ }
486
+ }
487
+ }
488
+ }
489
+ });
490
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
491
+ for (const key in globalMutationMap) {
492
+ onMutation(globalMutationMap[key]);
493
+ }
494
+ });
495
+ /**
496
+ * fetch the profile picture of a user/group
497
+ * type = "preview" for a low res picture
498
+ * type = "image for the high res picture"
499
+ */
500
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
501
+ var _a;
502
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
503
+ const result = await query({
504
+ tag: 'iq',
505
+ attrs: {
506
+ target: jid,
507
+ to: WABinary_1.S_WHATSAPP_NET,
508
+ type: 'get',
509
+ xmlns: 'w:profile:picture'
510
+ },
511
+ content: [
512
+ { tag: 'picture', attrs: { type, query: 'url' } }
513
+ ]
514
+ }, timeoutMs);
515
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
516
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
517
+ };
518
+ const sendPresenceUpdate = async (type, toJid) => {
519
+ const me = authState.creds.me;
520
+ if (type === 'available' || type === 'unavailable') {
521
+ if (!me.name) {
522
+ logger.warn('no name present, ignoring presence update request...');
523
+ return;
524
+ }
525
+ ev.emit('connection.update', { isOnline: type === 'available' });
526
+ await sendNode({
527
+ tag: 'presence',
528
+ attrs: {
529
+ name: me.name.replace(/@/g, ''),
530
+ type
531
+ }
532
+ });
533
+ }
534
+ else {
535
+ const { server } = (0, WABinary_1.jidDecode)(toJid);
536
+ const isLid = server === 'lid';
537
+ await sendNode({
538
+ tag: 'chatstate',
539
+ attrs: {
540
+ from: isLid ? me.lid : me.id,
541
+ to: toJid,
542
+ },
543
+ content: [
544
+ {
545
+ tag: type === 'recording' ? 'composing' : type,
546
+ attrs: type === 'recording' ? { media: 'audio' } : {}
547
+ }
548
+ ]
549
+ });
550
+ }
551
+ };
552
+ /**
553
+ * @param toJid the jid to subscribe to
554
+ * @param tcToken token for subscription, use if present
555
+ */
556
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
557
+ tag: 'presence',
558
+ attrs: {
559
+ to: toJid,
560
+ id: generateMessageTag(),
561
+ type: 'subscribe'
562
+ },
563
+ content: tcToken
564
+ ? [
565
+ {
566
+ tag: 'tctoken',
567
+ attrs: {},
568
+ content: tcToken
569
+ }
570
+ ]
571
+ : undefined
572
+ }));
573
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
574
+ var _a;
575
+ let presence;
576
+ const jid = attrs.from;
577
+ const participant = attrs.participant || attrs.from;
578
+ if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
579
+ return;
580
+ }
581
+ if (tag === 'presence') {
582
+ presence = {
583
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
584
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
585
+ };
586
+ }
587
+ else if (Array.isArray(content)) {
588
+ const [firstChild] = content;
589
+ let type = firstChild.tag;
590
+ if (type === 'paused') {
591
+ type = 'available';
592
+ }
593
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
594
+ type = 'recording';
595
+ }
596
+ presence = { lastKnownPresence: type };
597
+ }
598
+ else {
599
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
600
+ }
601
+ if (presence) {
602
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
603
+ }
604
+ };
605
+ const appPatch = async (patchCreate) => {
606
+ const name = patchCreate.type;
607
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
608
+ if (!myAppStateKeyId) {
609
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
610
+ }
611
+ let initial;
612
+ let encodeResult;
613
+ await processingMutex.mutex(async () => {
614
+ await authState.keys.transaction(async () => {
615
+ logger.debug({ patch: patchCreate }, 'applying app patch');
616
+ await resyncAppState([name], false);
617
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
618
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
619
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
620
+ const { patch, state } = encodeResult;
621
+ const node = {
622
+ tag: 'iq',
623
+ attrs: {
624
+ to: WABinary_1.S_WHATSAPP_NET,
625
+ type: 'set',
626
+ xmlns: 'w:sync:app:state'
627
+ },
628
+ content: [
629
+ {
630
+ tag: 'sync',
631
+ attrs: {},
632
+ content: [
633
+ {
634
+ tag: 'collection',
635
+ attrs: {
636
+ name,
637
+ version: (state.version - 1).toString(),
638
+ 'return_snapshot': 'false'
639
+ },
640
+ content: [
641
+ {
642
+ tag: 'patch',
643
+ attrs: {},
644
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
645
+ }
646
+ ]
647
+ }
648
+ ]
649
+ }
650
+ ]
651
+ };
652
+ await query(node);
653
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
654
+ });
655
+ });
656
+ if (config.emitOwnEvents) {
657
+ const { onMutation } = newAppStateChunkHandler(false);
658
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
659
+ for (const key in mutationMap) {
660
+ onMutation(mutationMap[key]);
661
+ }
662
+ }
663
+ };
664
+ /** sending non-abt props may fix QR scan fail if server expects */
665
+ const fetchProps = async () => {
666
+ var _a, _b, _c;
667
+ const resultNode = await query({
668
+ tag: 'iq',
669
+ attrs: {
670
+ to: WABinary_1.S_WHATSAPP_NET,
671
+ xmlns: 'w',
672
+ type: 'get',
673
+ },
674
+ content: [
675
+ { tag: 'props', attrs: {
676
+ protocol: '2',
677
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
678
+ } }
679
+ ]
680
+ });
681
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
682
+ let props = {};
683
+ if (propsNode) {
684
+ if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) { // on some clients, the hash is returning as undefined
685
+ authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
686
+ ev.emit('creds.update', authState.creds);
687
+ }
688
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
689
+ }
690
+ logger.debug('fetched props');
691
+ return props;
692
+ };
693
+ /**
694
+ * modify a chat -- mark unread, read etc.
695
+ * lastMessages must be sorted in reverse chronologically
696
+ * requires the last messages till the last message received; required for archive & unread
697
+ */
698
+ const chatModify = (mod, jid) => {
699
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
700
+ return appPatch(patch);
701
+ };
702
+ /**
703
+ * Star or Unstar a message
704
+ */
705
+ const star = (jid, messages, star) => {
706
+ return chatModify({
707
+ star: {
708
+ messages,
709
+ star
710
+ }
711
+ }, jid);
712
+ };
713
+ /**
714
+ * Adds label for the chats
715
+ */
716
+ const addChatLabel = (jid, labelId) => {
717
+ return chatModify({
718
+ addChatLabel: {
719
+ labelId
720
+ }
721
+ }, jid);
722
+ };
723
+ /**
724
+ * Removes label for the chat
725
+ */
726
+ const removeChatLabel = (jid, labelId) => {
727
+ return chatModify({
728
+ removeChatLabel: {
729
+ labelId
730
+ }
731
+ }, jid);
732
+ };
733
+ /**
734
+ * Adds label for the message
735
+ */
736
+ const addMessageLabel = (jid, messageId, labelId) => {
737
+ return chatModify({
738
+ addMessageLabel: {
739
+ messageId,
740
+ labelId
741
+ }
742
+ }, jid);
743
+ };
744
+ /**
745
+ * Removes label for the message
746
+ */
747
+ const removeMessageLabel = (jid, messageId, labelId) => {
748
+ return chatModify({
749
+ removeMessageLabel: {
750
+ messageId,
751
+ labelId
752
+ }
753
+ }, jid);
754
+ };
755
+ /**
756
+ * queries need to be fired on connection open
757
+ * help ensure parity with WA Web
758
+ * */
759
+ const executeInitQueries = async () => {
760
+ await Promise.all([
761
+ fetchProps(),
762
+ fetchBlocklist(),
763
+ fetchPrivacySettings(),
764
+ ]);
765
+ };
766
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
767
+ var _a, _b, _c;
768
+ ev.emit('messages.upsert', { messages: [msg], type });
769
+ if (!!msg.pushName) {
770
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
771
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
772
+ if (!msg.key.fromMe) {
773
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
774
+ }
775
+ // update our pushname too
776
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
777
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
778
+ }
779
+ }
780
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
781
+ const shouldProcessHistoryMsg = historyMsg
782
+ ? (shouldSyncHistoryMessage(historyMsg)
783
+ && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
784
+ : false;
785
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
786
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
787
+ pendingAppStateSync = true;
788
+ }
789
+ await Promise.all([
790
+ (async () => {
791
+ if (historyMsg
792
+ && authState.creds.myAppStateKeyId) {
793
+ pendingAppStateSync = false;
794
+ await doAppStateSync();
795
+ }
796
+ })(),
797
+ (0, process_message_1.default)(msg, {
798
+ shouldProcessHistoryMsg,
799
+ placeholderResendCache,
800
+ ev,
801
+ creds: authState.creds,
802
+ keyStore: authState.keys,
803
+ logger,
804
+ options: config.options,
805
+ getMessage: config.getMessage,
806
+ })
807
+ ]);
808
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
809
+ && pendingAppStateSync) {
810
+ await doAppStateSync();
811
+ pendingAppStateSync = false;
812
+ }
813
+ async function doAppStateSync() {
814
+ if (!authState.creds.accountSyncCounter) {
815
+ logger.info('doing initial app state sync');
816
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
817
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
818
+ ev.emit('creds.update', { accountSyncCounter });
819
+ if (needToFlushWithAppStateSync) {
820
+ logger.debug('flushing with app state sync');
821
+ ev.flush();
822
+ }
823
+ }
824
+ }
825
+ });
826
+ ws.on('CB:presence', handlePresenceUpdate);
827
+ ws.on('CB:chatstate', handlePresenceUpdate);
828
+ ws.on('CB:ib,,dirty', async (node) => {
829
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
830
+ const type = attrs.type;
831
+ switch (type) {
832
+ case 'account_sync':
833
+ if (attrs.timestamp) {
834
+ let { lastAccountSyncTimestamp } = authState.creds;
835
+ if (lastAccountSyncTimestamp) {
836
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
837
+ }
838
+ lastAccountSyncTimestamp = +attrs.timestamp;
839
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
840
+ }
841
+ break;
842
+ case 'groups':
843
+ // handled in groups.ts
844
+ break;
845
+ default:
846
+ logger.info({ node }, 'received unknown sync');
847
+ break;
848
+ }
849
+ });
850
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
851
+ var _a;
852
+ if (connection === 'open') {
853
+ if (fireInitQueries) {
854
+ executeInitQueries()
855
+ .catch(error => onUnexpectedError(error, 'init queries'));
856
+ }
857
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
858
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
859
+ }
860
+ if (receivedPendingNotifications && // if we don't have the app state key
861
+ // we keep buffering events until we finally have
862
+ // the key and can sync the messages
863
+ !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
864
+ ev.buffer();
865
+ needToFlushWithAppStateSync = true;
866
+ }
867
+ });
868
+ return {
869
+ ...sock,
870
+ getBotListV2,
871
+ processingMutex,
872
+ fetchPrivacySettings,
873
+ upsertMessage,
874
+ appPatch,
875
+ sendPresenceUpdate,
876
+ presenceSubscribe,
877
+ profilePictureUrl,
878
+ onWhatsApp,
879
+ fetchBlocklist,
880
+ fetchDisappearingDuration,
881
+ fetchStatus,
882
+ updateProfilePicture,
883
+ removeProfilePicture,
884
+ updateProfileStatus,
885
+ updateProfileName,
886
+ updateBlockStatus,
887
+ updateCallPrivacy,
888
+ updateMessagesPrivacy,
889
+ updateLastSeenPrivacy,
890
+ updateOnlinePrivacy,
891
+ updateProfilePicturePrivacy,
892
+ updateStatusPrivacy,
893
+ updateReadReceiptsPrivacy,
894
+ updateGroupsAddPrivacy,
895
+ updateDefaultDisappearingMode,
896
+ getBusinessProfile,
897
+ resyncAppState,
898
+ chatModify,
899
+ cleanDirtyBits,
900
+ addChatLabel,
901
+ removeChatLabel,
902
+ addMessageLabel,
903
+ removeMessageLabel,
904
+ star,
905
+ checkStatusWA
906
+ };
907
+ };
908
+ exports.makeChatsSocket = makeChatsSocket;