@zannstore/baileys 2.2.6

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