@than-xs/baileys 2.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +422 -0
  3. package/WAProto/index.js +169661 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.js +147 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.js +64 -0
  10. package/lib/Signal/Group/group_cipher.js +96 -0
  11. package/lib/Signal/Group/index.js +57 -0
  12. package/lib/Signal/Group/keyhelper.js +55 -0
  13. package/lib/Signal/Group/queue-job.js +57 -0
  14. package/lib/Signal/Group/sender-chain-key.js +34 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-message.js +69 -0
  17. package/lib/Signal/Group/sender-key-name.js +51 -0
  18. package/lib/Signal/Group/sender-key-record.js +53 -0
  19. package/lib/Signal/Group/sender-key-state.js +99 -0
  20. package/lib/Signal/Group/sender-message-key.js +29 -0
  21. package/lib/Signal/libsignal.js +174 -0
  22. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  23. package/lib/Socket/Client/index.js +19 -0
  24. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  25. package/lib/Socket/Client/web-socket-client.js +62 -0
  26. package/lib/Socket/business.js +260 -0
  27. package/lib/Socket/chats.js +1002 -0
  28. package/lib/Socket/dugong.js +637 -0
  29. package/lib/Socket/groups.js +317 -0
  30. package/lib/Socket/index.js +11 -0
  31. package/lib/Socket/messages-recv.js +1110 -0
  32. package/lib/Socket/messages-send.js +831 -0
  33. package/lib/Socket/newsletter.js +459 -0
  34. package/lib/Socket/registration.js +166 -0
  35. package/lib/Socket/socket.js +662 -0
  36. package/lib/Socket/usync.js +70 -0
  37. package/lib/Store/index.js +10 -0
  38. package/lib/Store/make-cache-manager-store.js +83 -0
  39. package/lib/Store/make-in-memory-store.js +427 -0
  40. package/lib/Store/make-ordered-dictionary.js +81 -0
  41. package/lib/Store/object-repository.js +27 -0
  42. package/lib/Types/Auth.js +2 -0
  43. package/lib/Types/Call.js +2 -0
  44. package/lib/Types/Chat.js +4 -0
  45. package/lib/Types/Contact.js +2 -0
  46. package/lib/Types/Events.js +2 -0
  47. package/lib/Types/GroupMetadata.js +2 -0
  48. package/lib/Types/Label.js +27 -0
  49. package/lib/Types/LabelAssociation.js +9 -0
  50. package/lib/Types/Message.js +9 -0
  51. package/lib/Types/Newsletter.js +38 -0
  52. package/lib/Types/Product.js +2 -0
  53. package/lib/Types/Signal.js +2 -0
  54. package/lib/Types/Socket.js +2 -0
  55. package/lib/Types/State.js +2 -0
  56. package/lib/Types/USync.js +2 -0
  57. package/lib/Types/index.js +42 -0
  58. package/lib/Utils/auth-utils.js +206 -0
  59. package/lib/Utils/baileys-event-stream.js +63 -0
  60. package/lib/Utils/business.js +234 -0
  61. package/lib/Utils/chat-utils.js +729 -0
  62. package/lib/Utils/crypto.js +151 -0
  63. package/lib/Utils/decode-wa-message.js +198 -0
  64. package/lib/Utils/event-buffer.js +514 -0
  65. package/lib/Utils/generics.js +498 -0
  66. package/lib/Utils/history.js +96 -0
  67. package/lib/Utils/index.js +33 -0
  68. package/lib/Utils/link-preview.js +93 -0
  69. package/lib/Utils/logger.js +7 -0
  70. package/lib/Utils/lt-hash.js +51 -0
  71. package/lib/Utils/make-mutex.js +43 -0
  72. package/lib/Utils/messages-media.js +819 -0
  73. package/lib/Utils/messages.js +819 -0
  74. package/lib/Utils/noise-handler.js +155 -0
  75. package/lib/Utils/process-message.js +321 -0
  76. package/lib/Utils/signal.js +153 -0
  77. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  78. package/lib/Utils/validate-connection.js +229 -0
  79. package/lib/WABinary/constants.js +40 -0
  80. package/lib/WABinary/decode.js +252 -0
  81. package/lib/WABinary/encode.js +265 -0
  82. package/lib/WABinary/generic-utils.js +198 -0
  83. package/lib/WABinary/index.js +21 -0
  84. package/lib/WABinary/jid-utils.js +62 -0
  85. package/lib/WABinary/types.js +2 -0
  86. package/lib/WAM/BinaryInfo.js +13 -0
  87. package/lib/WAM/constants.js +15350 -0
  88. package/lib/WAM/encode.js +155 -0
  89. package/lib/WAM/index.js +19 -0
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  94. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  96. package/lib/WAUSync/Protocols/index.js +20 -0
  97. package/lib/WAUSync/USyncQuery.js +89 -0
  98. package/lib/WAUSync/USyncUser.js +26 -0
  99. package/lib/WAUSync/index.js +19 -0
  100. package/lib/index.js +84 -0
  101. package/package.json +110 -0
@@ -0,0 +1,1002 @@
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 checkBan = 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
+ const result = await query({
595
+ tag: 'iq',
596
+ attrs: {
597
+ target: jid,
598
+ to: WABinary_1.S_WHATSAPP_NET,
599
+ type: 'get',
600
+ xmlns: 'w:profile:picture'
601
+ },
602
+ content: [
603
+ { tag: 'picture', attrs: { type, query: 'url' } }
604
+ ]
605
+ }, timeoutMs);
606
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
607
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
608
+ };
609
+ const sendPresenceUpdate = async (type, toJid) => {
610
+ const me = authState.creds.me;
611
+ if (type === 'available' || type === 'unavailable') {
612
+ if (!me.name) {
613
+ logger.warn('no name present, ignoring presence update request...');
614
+ return;
615
+ }
616
+ ev.emit('connection.update', { isOnline: type === 'available' });
617
+ await sendNode({
618
+ tag: 'presence',
619
+ attrs: {
620
+ name: me.name,
621
+ type
622
+ }
623
+ });
624
+ }
625
+ else {
626
+ const { server } = (0, WABinary_1.jidDecode)(toJid);
627
+ const isLid = server === 'lid';
628
+ await sendNode({
629
+ tag: 'chatstate',
630
+ attrs: {
631
+ from: isLid ? me.lid : me.id,
632
+ to: toJid,
633
+ },
634
+ content: [
635
+ {
636
+ tag: type === 'recording' ? 'composing' : type,
637
+ attrs: type === 'recording' ? { media: 'audio' } : {}
638
+ }
639
+ ]
640
+ });
641
+ }
642
+ };
643
+ /**
644
+ * @param toJid the jid to subscribe to
645
+ * @param tcToken token for subscription, use if present
646
+ */
647
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
648
+ tag: 'presence',
649
+ attrs: {
650
+ to: toJid,
651
+ id: generateMessageTag(),
652
+ type: 'subscribe'
653
+ },
654
+ content: tcToken ?
655
+ [
656
+ {
657
+ tag: 'tctoken',
658
+ attrs: {},
659
+ content: tcToken
660
+ }
661
+ ] :
662
+ undefined
663
+ }));
664
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
665
+ var _a;
666
+ let presence;
667
+ const jid = attrs.from;
668
+ const participant = attrs.participant || attrs.from;
669
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
670
+ return;
671
+ }
672
+ if (tag === 'presence') {
673
+ presence = {
674
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
675
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
676
+ };
677
+ }
678
+ else if (Array.isArray(content)) {
679
+ const [firstChild] = content;
680
+ let type = firstChild.tag;
681
+ if (type === 'paused') {
682
+ type = 'available';
683
+ }
684
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
685
+ type = 'recording';
686
+ }
687
+ presence = { lastKnownPresence: type };
688
+ }
689
+ else {
690
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
691
+ }
692
+ if (presence) {
693
+ ev.emit('presence.update', { id: jid, presences: {
694
+ [participant]: presence
695
+ } });
696
+ }
697
+ };
698
+ const appPatch = async (patchCreate) => {
699
+ const name = patchCreate.type;
700
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
701
+ if (!myAppStateKeyId) {
702
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
703
+ }
704
+ let initial;
705
+ let encodeResult;
706
+ await processingMutex.mutex(async () => {
707
+ await authState.keys.transaction(async () => {
708
+ logger.debug({ patch: patchCreate }, 'applying app patch');
709
+ await resyncAppState([name], false);
710
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
711
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
712
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
713
+ const { patch, state } = encodeResult;
714
+ const node = {
715
+ tag: 'iq',
716
+ attrs: {
717
+ to: WABinary_1.S_WHATSAPP_NET,
718
+ type: 'set',
719
+ xmlns: 'w:sync:app:state'
720
+ },
721
+ content: [
722
+ {
723
+ tag: 'sync',
724
+ attrs: {},
725
+ content: [
726
+ {
727
+ tag: 'collection',
728
+ attrs: {
729
+ name,
730
+ version: (state.version - 1).toString(),
731
+ 'return_snapshot': 'false'
732
+ },
733
+ content: [
734
+ {
735
+ tag: 'patch',
736
+ attrs: {},
737
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
738
+ }
739
+ ]
740
+ }
741
+ ]
742
+ }
743
+ ]
744
+ };
745
+ await query(node);
746
+ await authState.keys.set({ 'app-state-sync-version': {
747
+ [name]: state
748
+ } });
749
+ });
750
+ });
751
+ if (config.emitOwnEvents) {
752
+ const { onMutation } = newAppStateChunkHandler(false);
753
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
754
+ for (const key in mutationMap) {
755
+ onMutation(mutationMap[key]);
756
+ }
757
+ }
758
+ };
759
+ /** sending non-abt props may fix QR scan fail if server expects */
760
+ const fetchProps = async () => {
761
+ var _a, _b;
762
+ const resultNode = await query({
763
+ tag: 'iq',
764
+ attrs: {
765
+ to: WABinary_1.S_WHATSAPP_NET,
766
+ xmlns: 'w',
767
+ type: 'get',
768
+ },
769
+ content: [
770
+ {
771
+ tag: 'props',
772
+ attrs: {
773
+ protocol: '2',
774
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
775
+ }
776
+ }
777
+ ]
778
+ });
779
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
780
+ let props = {};
781
+ if (propsNode) {
782
+ authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
783
+ ev.emit('creds.update', authState.creds);
784
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
785
+ }
786
+ logger.debug('fetched props');
787
+ return props;
788
+ };
789
+ /**
790
+ * modify a chat -- mark unread, read etc.
791
+ * lastMessages must be sorted in reverse chronologically
792
+ * requires the last messages till the last message received; required for archive & unread
793
+ */
794
+ const chatModify = (mod, jid) => {
795
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
796
+ return appPatch(patch);
797
+ };
798
+ /**
799
+ * Star or Unstar a message
800
+ */
801
+ const star = (jid, messages, star) => {
802
+ return chatModify({
803
+ star: {
804
+ messages,
805
+ star
806
+ }
807
+ }, jid);
808
+ };
809
+ /**
810
+ * Adds label for the chats
811
+ */
812
+ const addChatLabel = (jid, labelId) => {
813
+ return chatModify({
814
+ addChatLabel: {
815
+ labelId
816
+ }
817
+ }, jid);
818
+ };
819
+ /**
820
+ * Removes label for the chat
821
+ */
822
+ const removeChatLabel = (jid, labelId) => {
823
+ return chatModify({
824
+ removeChatLabel: {
825
+ labelId
826
+ }
827
+ }, jid);
828
+ };
829
+ /**
830
+ * Adds label for the message
831
+ */
832
+ const addMessageLabel = (jid, messageId, labelId) => {
833
+ return chatModify({
834
+ addMessageLabel: {
835
+ messageId,
836
+ labelId
837
+ }
838
+ }, jid);
839
+ };
840
+ /**
841
+ * Removes label for the message
842
+ */
843
+ const removeMessageLabel = (jid, messageId, labelId) => {
844
+ return chatModify({
845
+ removeMessageLabel: {
846
+ messageId,
847
+ labelId
848
+ }
849
+ }, jid);
850
+ };
851
+ /**
852
+ * queries need to be fired on connection open
853
+ * help ensure parity with WA Web
854
+ * */
855
+ const executeInitQueries = async () => {
856
+ await Promise.all([
857
+ fetchProps(),
858
+ fetchBlocklist(),
859
+ fetchPrivacySettings(),
860
+ ]);
861
+ };
862
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
863
+ var _a, _b, _c;
864
+ ev.emit('messages.upsert', { messages: [msg], type });
865
+ if (!!msg.pushName) {
866
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
867
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
868
+ if (!msg.key.fromMe) {
869
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
870
+ }
871
+ // update our pushname too
872
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
873
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
874
+ }
875
+ }
876
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
877
+ const shouldProcessHistoryMsg = historyMsg ?
878
+ (shouldSyncHistoryMessage(historyMsg) &&
879
+ Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
880
+ false;
881
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
882
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
883
+ pendingAppStateSync = true;
884
+ }
885
+ await Promise.all([
886
+ (async () => {
887
+ if (historyMsg &&
888
+ authState.creds.myAppStateKeyId) {
889
+ pendingAppStateSync = false;
890
+ await doAppStateSync();
891
+ }
892
+ })(),
893
+ (0, process_message_1.default)(msg, {
894
+ shouldProcessHistoryMsg,
895
+ ev,
896
+ creds: authState.creds,
897
+ keyStore: authState.keys,
898
+ logger,
899
+ options: config.options,
900
+ getMessage: config.getMessage,
901
+ })
902
+ ]);
903
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
904
+ pendingAppStateSync) {
905
+ await doAppStateSync();
906
+ pendingAppStateSync = false;
907
+ }
908
+ async function doAppStateSync() {
909
+ if (!authState.creds.accountSyncCounter) {
910
+ logger.info('doing initial app state sync');
911
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
912
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
913
+ ev.emit('creds.update', { accountSyncCounter });
914
+ if (needToFlushWithAppStateSync) {
915
+ logger.debug('flushing with app state sync');
916
+ ev.flush();
917
+ }
918
+ }
919
+ }
920
+ });
921
+ ws.on('CB:presence', handlePresenceUpdate);
922
+ ws.on('CB:chatstate', handlePresenceUpdate);
923
+ ws.on('CB:ib,,dirty', async (node) => {
924
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
925
+ const type = attrs.type;
926
+ switch (type) {
927
+ case 'account_sync':
928
+ if (attrs.timestamp) {
929
+ let { lastAccountSyncTimestamp } = authState.creds;
930
+ if (lastAccountSyncTimestamp) {
931
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
932
+ }
933
+ lastAccountSyncTimestamp = +attrs.timestamp;
934
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
935
+ }
936
+ break;
937
+ case 'groups':
938
+ // handled in groups.ts
939
+ break;
940
+ default:
941
+ logger.info({ node }, 'received unknown sync');
942
+ break;
943
+ }
944
+ });
945
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
946
+ var _a;
947
+ if (connection === 'open') {
948
+ if (fireInitQueries) {
949
+ executeInitQueries()
950
+ .catch(error => onUnexpectedError(error, 'init queries'));
951
+ }
952
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
953
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
954
+ }
955
+ if (receivedPendingNotifications) {
956
+ // if we don't have the app state key
957
+ // we keep buffering events until we finally have
958
+ // the key and can sync the messages
959
+ if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
960
+ ev.buffer();
961
+ needToFlushWithAppStateSync = true;
962
+ }
963
+ }
964
+ });
965
+ return {
966
+ ...sock,
967
+ processingMutex,
968
+ fetchPrivacySettings,
969
+ upsertMessage,
970
+ appPatch,
971
+ sendPresenceUpdate,
972
+ presenceSubscribe,
973
+ profilePictureUrl,
974
+ onWhatsApp,
975
+ fetchBlocklist,
976
+ fetchStatus,
977
+ updateProfilePicture,
978
+ removeProfilePicture,
979
+ updateProfileStatus,
980
+ updateProfileName,
981
+ updateBlockStatus,
982
+ updateLastSeenPrivacy,
983
+ updateOnlinePrivacy,
984
+ updateProfilePicturePrivacy,
985
+ updateStatusPrivacy,
986
+ updateReadReceiptsPrivacy,
987
+ updateGroupsAddPrivacy,
988
+ updateDefaultDisappearingMode,
989
+ getBusinessProfile,
990
+ resyncAppState,
991
+ chatModify,
992
+ cleanDirtyBits,
993
+ addChatLabel,
994
+ removeChatLabel,
995
+ addMessageLabel,
996
+ checkBan,
997
+ reqPairing,
998
+ removeMessageLabel,
999
+ star
1000
+ };
1001
+ };
1002
+ exports.makeChatsSocket = makeChatsSocket;