@chatbridge-it/baileys 0.0.0-stage → 1.0.0

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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +705 -2
  3. package/WAProto/index.js +169661 -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/Signal/Group/ciphertext-message.js +15 -0
  8. package/lib/Signal/Group/group-session-builder.js +64 -0
  9. package/lib/Signal/Group/group_cipher.js +96 -0
  10. package/lib/Signal/Group/index.js +57 -0
  11. package/lib/Signal/Group/keyhelper.js +55 -0
  12. package/lib/Signal/Group/queue-job.js +57 -0
  13. package/lib/Signal/Group/sender-chain-key.js +34 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  15. package/lib/Signal/Group/sender-key-message.js +69 -0
  16. package/lib/Signal/Group/sender-key-name.js +51 -0
  17. package/lib/Signal/Group/sender-key-record.js +53 -0
  18. package/lib/Signal/Group/sender-key-state.js +99 -0
  19. package/lib/Signal/Group/sender-message-key.js +29 -0
  20. package/lib/Signal/libsignal.js +174 -0
  21. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  22. package/lib/Socket/Client/index.js +19 -0
  23. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  24. package/lib/Socket/Client/web-socket-client.js +62 -0
  25. package/lib/Socket/business.js +260 -0
  26. package/lib/Socket/chats.js +987 -0
  27. package/lib/Socket/dugong.js +637 -0
  28. package/lib/Socket/groups.js +317 -0
  29. package/lib/Socket/index.js +11 -0
  30. package/lib/Socket/messages-recv.js +1110 -0
  31. package/lib/Socket/messages-send.js +831 -0
  32. package/lib/Socket/newsletter.js +424 -0
  33. package/lib/Socket/registration.js +166 -0
  34. package/lib/Socket/socket.js +661 -0
  35. package/lib/Socket/usync.js +70 -0
  36. package/lib/Store/index.js +10 -0
  37. package/lib/Store/make-cache-manager-store.js +83 -0
  38. package/lib/Store/make-in-memory-store.js +427 -0
  39. package/lib/Store/make-ordered-dictionary.js +81 -0
  40. package/lib/Store/object-repository.js +27 -0
  41. package/lib/Types/Auth.js +2 -0
  42. package/lib/Types/Call.js +2 -0
  43. package/lib/Types/Chat.js +4 -0
  44. package/lib/Types/Contact.js +2 -0
  45. package/lib/Types/Events.js +2 -0
  46. package/lib/Types/GroupMetadata.js +2 -0
  47. package/lib/Types/Label.js +27 -0
  48. package/lib/Types/LabelAssociation.js +9 -0
  49. package/lib/Types/Message.js +9 -0
  50. package/lib/Types/Newsletter.js +38 -0
  51. package/lib/Types/Product.js +2 -0
  52. package/lib/Types/Signal.js +2 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +2 -0
  55. package/lib/Types/USync.js +2 -0
  56. package/lib/Types/index.js +42 -0
  57. package/lib/Utils/auth-utils.js +206 -0
  58. package/lib/Utils/baileys-event-stream.js +63 -0
  59. package/lib/Utils/business.js +234 -0
  60. package/lib/Utils/chat-utils.js +729 -0
  61. package/lib/Utils/crypto.js +151 -0
  62. package/lib/Utils/decode-wa-message.js +198 -0
  63. package/lib/Utils/event-buffer.js +514 -0
  64. package/lib/Utils/generics.js +498 -0
  65. package/lib/Utils/history.js +96 -0
  66. package/lib/Utils/index.js +33 -0
  67. package/lib/Utils/link-preview.js +93 -0
  68. package/lib/Utils/logger.js +7 -0
  69. package/lib/Utils/lt-hash.js +51 -0
  70. package/lib/Utils/make-mutex.js +43 -0
  71. package/lib/Utils/messages-media.js +819 -0
  72. package/lib/Utils/messages.js +787 -0
  73. package/lib/Utils/noise-handler.js +155 -0
  74. package/lib/Utils/process-message.js +321 -0
  75. package/lib/Utils/signal.js +153 -0
  76. package/lib/Utils/use-multi-file-auth-state.js +122 -0
  77. package/lib/Utils/validate-connection.js +229 -0
  78. package/lib/WABinary/constants.js +40 -0
  79. package/lib/WABinary/decode.js +252 -0
  80. package/lib/WABinary/encode.js +265 -0
  81. package/lib/WABinary/generic-utils.js +198 -0
  82. package/lib/WABinary/index.js +21 -0
  83. package/lib/WABinary/jid-utils.js +62 -0
  84. package/lib/WABinary/types.js +2 -0
  85. package/lib/WAM/BinaryInfo.js +13 -0
  86. package/lib/WAM/constants.js +15350 -0
  87. package/lib/WAM/encode.js +155 -0
  88. package/lib/WAM/index.js +19 -0
  89. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  90. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  91. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  92. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  93. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  94. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  95. package/lib/WAUSync/Protocols/index.js +20 -0
  96. package/lib/WAUSync/USyncQuery.js +89 -0
  97. package/lib/WAUSync/USyncUser.js +26 -0
  98. package/lib/WAUSync/index.js +19 -0
  99. package/lib/index.js +38 -0
  100. package/package.json +100 -5
@@ -0,0 +1,987 @@
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
+ const updateDefaultDisappearingMode = async (duration) => {
175
+ await query({
176
+ tag: 'iq',
177
+ attrs: {
178
+ xmlns: 'disappearing_mode',
179
+ to: WABinary_1.S_WHATSAPP_NET,
180
+ type: 'set'
181
+ },
182
+ content: [{
183
+ tag: 'disappearing_mode',
184
+ attrs: {
185
+ duration: duration.toString()
186
+ }
187
+ }]
188
+ });
189
+ };
190
+ /** helper function to run a generic IQ query */
191
+ const interactiveQuery = async (userNodes, queryNode) => {
192
+ const result = await query({
193
+ tag: 'iq',
194
+ attrs: {
195
+ to: WABinary_1.S_WHATSAPP_NET,
196
+ type: 'get',
197
+ xmlns: 'usync',
198
+ },
199
+ content: [
200
+ {
201
+ tag: 'usync',
202
+ attrs: {
203
+ sid: generateMessageTag(),
204
+ mode: 'query',
205
+ last: 'true',
206
+ index: '0',
207
+ context: 'interactive',
208
+ },
209
+ content: [
210
+ {
211
+ tag: 'query',
212
+ attrs: {},
213
+ content: [queryNode]
214
+ },
215
+ {
216
+ tag: 'list',
217
+ attrs: {},
218
+ content: userNodes
219
+ }
220
+ ]
221
+ }
222
+ ],
223
+ });
224
+ const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
225
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
226
+ const users = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'user');
227
+ return users;
228
+ };
229
+ const getBusinessProfile = async (jid) => {
230
+ var _a, _b, _c, _d, _e, _f, _g;
231
+ const results = await query({
232
+ tag: 'iq',
233
+ attrs: {
234
+ to: 's.whatsapp.net',
235
+ xmlns: 'w:biz',
236
+ type: 'get'
237
+ },
238
+ content: [{
239
+ tag: 'business_profile',
240
+ attrs: { v: '244' },
241
+ content: [{
242
+ tag: 'profile',
243
+ attrs: { jid }
244
+ }]
245
+ }]
246
+ });
247
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
248
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
249
+ if (profiles) {
250
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
251
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
252
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
253
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
254
+ const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
255
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
256
+ const businessHoursConfig = businessHours ?
257
+ (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config') :
258
+ undefined;
259
+ const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
260
+ return {
261
+ wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
262
+ address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
263
+ description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
264
+ website: websiteStr ? [websiteStr] : [],
265
+ email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
266
+ category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
267
+ 'business_hours': {
268
+ timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
269
+ 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
270
+ }
271
+ };
272
+ }
273
+ };
274
+ const onWhatsApp = async (...jids) => {
275
+ const usyncQuery = new WAUSync_1.USyncQuery()
276
+ .withContactProtocol()
277
+ .withLIDProtocol();
278
+
279
+ for (const jid of jids) {
280
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
281
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
282
+ }
283
+
284
+ const results = await sock.executeUSyncQuery(usyncQuery);
285
+ if (results) {
286
+ const verifiedResults = await Promise.all(
287
+ results.list
288
+ .filter((a) => !!a.contact)
289
+ .map(async ({ contact, id, lid }) => {
290
+ try {
291
+ const businessProfile = await getBusinessProfile(id);
292
+ const isBusiness = businessProfile && Object.keys(businessProfile).length > 0;
293
+ if (isBusiness) {
294
+ const { wid, ...businessInfo } = businessProfile;
295
+
296
+ return {
297
+ jid: id,
298
+ exists: true,
299
+ lid: lid,
300
+ status: 'business',
301
+ businessInfo: businessInfo
302
+ };
303
+ } else {
304
+ return {
305
+ jid: id,
306
+ exists: true,
307
+ lid: lid,
308
+ status: 'regular'
309
+ };
310
+ }
311
+ } catch (error) {
312
+ return {
313
+ jid: id,
314
+ exists: true,
315
+ lid: lid,
316
+ status: error
317
+ };
318
+ }
319
+ })
320
+ );
321
+ return verifiedResults;
322
+ }
323
+ };
324
+ const fetchStatus = async (jid) => {
325
+ const [result] = await interactiveQuery([{ tag: 'user', attrs: { jid } }], { tag: 'status', attrs: {} });
326
+ if (result) {
327
+ const status = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
328
+ return {
329
+ status: status === null || status === void 0 ? void 0 : status.content.toString(),
330
+ setAt: new Date(+((status === null || status === void 0 ? void 0 : status.attrs.t) || 0) * 1000)
331
+ };
332
+ }
333
+ };
334
+ /** update the profile picture for yourself or a group */
335
+ const updateProfilePicture = async (jid, content) => {
336
+ let targetJid;
337
+ if (!jid) {
338
+ 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');
339
+ }
340
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
341
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
342
+ }
343
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
344
+ await query({
345
+ tag: 'iq',
346
+ attrs: {
347
+ target: targetJid,
348
+ to: WABinary_1.S_WHATSAPP_NET,
349
+ type: 'set',
350
+ xmlns: 'w:profile:picture'
351
+ },
352
+ content: [
353
+ {
354
+ tag: 'picture',
355
+ attrs: { type: 'image' },
356
+ content: img
357
+ }
358
+ ]
359
+ });
360
+ };
361
+ /** remove the profile picture for yourself or a group */
362
+ const removeProfilePicture = async (jid) => {
363
+ let targetJid;
364
+ if (!jid) {
365
+ 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');
366
+ }
367
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
368
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
369
+ }
370
+ await query({
371
+ tag: 'iq',
372
+ attrs: {
373
+ target: targetJid,
374
+ to: WABinary_1.S_WHATSAPP_NET,
375
+ type: 'set',
376
+ xmlns: 'w:profile:picture'
377
+ }
378
+ });
379
+ };
380
+ /** update the profile status for yourself */
381
+ const updateProfileStatus = async (status) => {
382
+ await query({
383
+ tag: 'iq',
384
+ attrs: {
385
+ to: WABinary_1.S_WHATSAPP_NET,
386
+ type: 'set',
387
+ xmlns: 'status'
388
+ },
389
+ content: [
390
+ {
391
+ tag: 'status',
392
+ attrs: {},
393
+ content: Buffer.from(status, 'utf-8')
394
+ }
395
+ ]
396
+ });
397
+ };
398
+ const updateProfileName = async (name) => {
399
+ await chatModify({ pushNameSetting: name }, '');
400
+ };
401
+ const fetchBlocklist = async () => {
402
+ const result = await query({
403
+ tag: 'iq',
404
+ attrs: {
405
+ xmlns: 'blocklist',
406
+ to: WABinary_1.S_WHATSAPP_NET,
407
+ type: 'get'
408
+ }
409
+ });
410
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
411
+ return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
412
+ .map(n => n.attrs.jid);
413
+ };
414
+ const updateBlockStatus = async (jid, action) => {
415
+ await query({
416
+ tag: 'iq',
417
+ attrs: {
418
+ xmlns: 'blocklist',
419
+ to: WABinary_1.S_WHATSAPP_NET,
420
+ type: 'set'
421
+ },
422
+ content: [
423
+ {
424
+ tag: 'item',
425
+ attrs: {
426
+ action,
427
+ jid
428
+ }
429
+ }
430
+ ]
431
+ });
432
+ };
433
+ const cleanDirtyBits = async (type, fromTimestamp) => {
434
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
435
+ await sendNode({
436
+ tag: 'iq',
437
+ attrs: {
438
+ to: WABinary_1.S_WHATSAPP_NET,
439
+ type: 'set',
440
+ xmlns: 'urn:xmpp:whatsapp:dirty',
441
+ id: generateMessageTag(),
442
+ },
443
+ content: [
444
+ {
445
+ tag: 'clean',
446
+ attrs: {
447
+ type,
448
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
449
+ }
450
+ }
451
+ ]
452
+ });
453
+ };
454
+ const newAppStateChunkHandler = (isInitialSync) => {
455
+ return {
456
+ onMutation(mutation) {
457
+ (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
458
+ }
459
+ };
460
+ };
461
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
462
+ // we use this to determine which events to fire
463
+ // otherwise when we resync from scratch -- all notifications will fire
464
+ const initialVersionMap = {};
465
+ const globalMutationMap = {};
466
+ await authState.keys.transaction(async () => {
467
+ var _a;
468
+ const collectionsToHandle = new Set(collections);
469
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
470
+ const attemptsMap = {};
471
+ // keep executing till all collections are done
472
+ // sometimes a single patch request will not return all the patches (God knows why)
473
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
474
+ while (collectionsToHandle.size) {
475
+ const states = {};
476
+ const nodes = [];
477
+ for (const name of collectionsToHandle) {
478
+ const result = await authState.keys.get('app-state-sync-version', [name]);
479
+ let state = result[name];
480
+ if (state) {
481
+ if (typeof initialVersionMap[name] === 'undefined') {
482
+ initialVersionMap[name] = state.version;
483
+ }
484
+ }
485
+ else {
486
+ state = (0, Utils_1.newLTHashState)();
487
+ }
488
+ states[name] = state;
489
+ logger.info(`resyncing ${name} from v${state.version}`);
490
+ nodes.push({
491
+ tag: 'collection',
492
+ attrs: {
493
+ name,
494
+ version: state.version.toString(),
495
+ // return snapshot if being synced from scratch
496
+ 'return_snapshot': (!state.version).toString()
497
+ }
498
+ });
499
+ }
500
+ const result = await query({
501
+ tag: 'iq',
502
+ attrs: {
503
+ to: WABinary_1.S_WHATSAPP_NET,
504
+ xmlns: 'w:sync:app:state',
505
+ type: 'set'
506
+ },
507
+ content: [
508
+ {
509
+ tag: 'sync',
510
+ attrs: {},
511
+ content: nodes
512
+ }
513
+ ]
514
+ });
515
+ // extract from binary node
516
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
517
+ for (const key in decoded) {
518
+ const name = key;
519
+ const { patches, hasMorePatches, snapshot } = decoded[name];
520
+ try {
521
+ if (snapshot) {
522
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
523
+ states[name] = newState;
524
+ Object.assign(globalMutationMap, mutationMap);
525
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
526
+ await authState.keys.set({ 'app-state-sync-version': {
527
+ [name]: newState
528
+ } });
529
+ }
530
+ // only process if there are syncd patches
531
+ if (patches.length) {
532
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
533
+ await authState.keys.set({ 'app-state-sync-version': {
534
+ [name]: newState
535
+ } });
536
+ logger.info(`synced ${name} to v${newState.version}`);
537
+ initialVersionMap[name] = newState.version;
538
+ Object.assign(globalMutationMap, mutationMap);
539
+ }
540
+ if (hasMorePatches) {
541
+ logger.info(`${name} has more patches...`);
542
+ }
543
+ else { // collection is done with sync
544
+ collectionsToHandle.delete(name);
545
+ }
546
+ }
547
+ catch (error) {
548
+ // if retry attempts overshoot
549
+ // or key not found
550
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
551
+ ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
552
+ error.name === 'TypeError';
553
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
554
+ await authState.keys.set({ 'app-state-sync-version': {
555
+ [name]: null
556
+ } });
557
+ // increment number of retries
558
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
559
+ if (isIrrecoverableError) {
560
+ // stop retrying
561
+ collectionsToHandle.delete(name);
562
+ }
563
+ }
564
+ }
565
+ }
566
+ });
567
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
568
+ for (const key in globalMutationMap) {
569
+ onMutation(globalMutationMap[key]);
570
+ }
571
+ });
572
+ /**
573
+ * fetch the profile picture of a user/group
574
+ * type = "preview" for a low res picture
575
+ * type = "image for the high res picture"
576
+ */
577
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
578
+ var _a;
579
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
580
+ const result = await query({
581
+ tag: 'iq',
582
+ attrs: {
583
+ target: jid,
584
+ to: WABinary_1.S_WHATSAPP_NET,
585
+ type: 'get',
586
+ xmlns: 'w:profile:picture'
587
+ },
588
+ content: [
589
+ { tag: 'picture', attrs: { type, query: 'url' } }
590
+ ]
591
+ }, timeoutMs);
592
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
593
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
594
+ };
595
+ const sendPresenceUpdate = async (type, toJid) => {
596
+ const me = authState.creds.me;
597
+ if (type === 'available' || type === 'unavailable') {
598
+ if (!me.name) {
599
+ logger.warn('no name present, ignoring presence update request...');
600
+ return;
601
+ }
602
+ ev.emit('connection.update', { isOnline: type === 'available' });
603
+ await sendNode({
604
+ tag: 'presence',
605
+ attrs: {
606
+ name: me.name,
607
+ type
608
+ }
609
+ });
610
+ }
611
+ else {
612
+ const { server } = (0, WABinary_1.jidDecode)(toJid);
613
+ const isLid = server === 'lid';
614
+ await sendNode({
615
+ tag: 'chatstate',
616
+ attrs: {
617
+ from: isLid ? me.lid : me.id,
618
+ to: toJid,
619
+ },
620
+ content: [
621
+ {
622
+ tag: type === 'recording' ? 'composing' : type,
623
+ attrs: type === 'recording' ? { media: 'audio' } : {}
624
+ }
625
+ ]
626
+ });
627
+ }
628
+ };
629
+ /**
630
+ * @param toJid the jid to subscribe to
631
+ * @param tcToken token for subscription, use if present
632
+ */
633
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
634
+ tag: 'presence',
635
+ attrs: {
636
+ to: toJid,
637
+ id: generateMessageTag(),
638
+ type: 'subscribe'
639
+ },
640
+ content: tcToken ?
641
+ [
642
+ {
643
+ tag: 'tctoken',
644
+ attrs: {},
645
+ content: tcToken
646
+ }
647
+ ] :
648
+ undefined
649
+ }));
650
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
651
+ var _a;
652
+ let presence;
653
+ const jid = attrs.from;
654
+ const participant = attrs.participant || attrs.from;
655
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
656
+ return;
657
+ }
658
+ if (tag === 'presence') {
659
+ presence = {
660
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
661
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
662
+ };
663
+ }
664
+ else if (Array.isArray(content)) {
665
+ const [firstChild] = content;
666
+ let type = firstChild.tag;
667
+ if (type === 'paused') {
668
+ type = 'available';
669
+ }
670
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
671
+ type = 'recording';
672
+ }
673
+ presence = { lastKnownPresence: type };
674
+ }
675
+ else {
676
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
677
+ }
678
+ if (presence) {
679
+ ev.emit('presence.update', { id: jid, presences: {
680
+ [participant]: presence
681
+ } });
682
+ }
683
+ };
684
+ const appPatch = async (patchCreate) => {
685
+ const name = patchCreate.type;
686
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
687
+ if (!myAppStateKeyId) {
688
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
689
+ }
690
+ let initial;
691
+ let encodeResult;
692
+ await processingMutex.mutex(async () => {
693
+ await authState.keys.transaction(async () => {
694
+ logger.debug({ patch: patchCreate }, 'applying app patch');
695
+ await resyncAppState([name], false);
696
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
697
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
698
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
699
+ const { patch, state } = encodeResult;
700
+ const node = {
701
+ tag: 'iq',
702
+ attrs: {
703
+ to: WABinary_1.S_WHATSAPP_NET,
704
+ type: 'set',
705
+ xmlns: 'w:sync:app:state'
706
+ },
707
+ content: [
708
+ {
709
+ tag: 'sync',
710
+ attrs: {},
711
+ content: [
712
+ {
713
+ tag: 'collection',
714
+ attrs: {
715
+ name,
716
+ version: (state.version - 1).toString(),
717
+ 'return_snapshot': 'false'
718
+ },
719
+ content: [
720
+ {
721
+ tag: 'patch',
722
+ attrs: {},
723
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
724
+ }
725
+ ]
726
+ }
727
+ ]
728
+ }
729
+ ]
730
+ };
731
+ await query(node);
732
+ await authState.keys.set({ 'app-state-sync-version': {
733
+ [name]: state
734
+ } });
735
+ });
736
+ });
737
+ if (config.emitOwnEvents) {
738
+ const { onMutation } = newAppStateChunkHandler(false);
739
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
740
+ for (const key in mutationMap) {
741
+ onMutation(mutationMap[key]);
742
+ }
743
+ }
744
+ };
745
+ /** sending non-abt props may fix QR scan fail if server expects */
746
+ const fetchProps = async () => {
747
+ var _a, _b;
748
+ const resultNode = await query({
749
+ tag: 'iq',
750
+ attrs: {
751
+ to: WABinary_1.S_WHATSAPP_NET,
752
+ xmlns: 'w',
753
+ type: 'get',
754
+ },
755
+ content: [
756
+ {
757
+ tag: 'props',
758
+ attrs: {
759
+ protocol: '2',
760
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
761
+ }
762
+ }
763
+ ]
764
+ });
765
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
766
+ let props = {};
767
+ if (propsNode) {
768
+ authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
769
+ ev.emit('creds.update', authState.creds);
770
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
771
+ }
772
+ logger.debug('fetched props');
773
+ return props;
774
+ };
775
+ /**
776
+ * modify a chat -- mark unread, read etc.
777
+ * lastMessages must be sorted in reverse chronologically
778
+ * requires the last messages till the last message received; required for archive & unread
779
+ */
780
+ const chatModify = (mod, jid) => {
781
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
782
+ return appPatch(patch);
783
+ };
784
+ /**
785
+ * Star or Unstar a message
786
+ */
787
+ const star = (jid, messages, star) => {
788
+ return chatModify({
789
+ star: {
790
+ messages,
791
+ star
792
+ }
793
+ }, jid);
794
+ };
795
+ /**
796
+ * Adds label for the chats
797
+ */
798
+ const addChatLabel = (jid, labelId) => {
799
+ return chatModify({
800
+ addChatLabel: {
801
+ labelId
802
+ }
803
+ }, jid);
804
+ };
805
+ /**
806
+ * Removes label for the chat
807
+ */
808
+ const removeChatLabel = (jid, labelId) => {
809
+ return chatModify({
810
+ removeChatLabel: {
811
+ labelId
812
+ }
813
+ }, jid);
814
+ };
815
+ /**
816
+ * Adds label for the message
817
+ */
818
+ const addMessageLabel = (jid, messageId, labelId) => {
819
+ return chatModify({
820
+ addMessageLabel: {
821
+ messageId,
822
+ labelId
823
+ }
824
+ }, jid);
825
+ };
826
+ /**
827
+ * Removes label for the message
828
+ */
829
+ const removeMessageLabel = (jid, messageId, labelId) => {
830
+ return chatModify({
831
+ removeMessageLabel: {
832
+ messageId,
833
+ labelId
834
+ }
835
+ }, jid);
836
+ };
837
+ /**
838
+ * queries need to be fired on connection open
839
+ * help ensure parity with WA Web
840
+ * */
841
+ const executeInitQueries = async () => {
842
+ await Promise.all([
843
+ fetchProps(),
844
+ fetchBlocklist(),
845
+ fetchPrivacySettings(),
846
+ ]);
847
+ };
848
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
849
+ var _a, _b, _c;
850
+ ev.emit('messages.upsert', { messages: [msg], type });
851
+ if (!!msg.pushName) {
852
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
853
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
854
+ if (!msg.key.fromMe) {
855
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
856
+ }
857
+ // update our pushname too
858
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
859
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
860
+ }
861
+ }
862
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
863
+ const shouldProcessHistoryMsg = historyMsg ?
864
+ (shouldSyncHistoryMessage(historyMsg) &&
865
+ Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
866
+ false;
867
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
868
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
869
+ pendingAppStateSync = true;
870
+ }
871
+ await Promise.all([
872
+ (async () => {
873
+ if (historyMsg &&
874
+ authState.creds.myAppStateKeyId) {
875
+ pendingAppStateSync = false;
876
+ await doAppStateSync();
877
+ }
878
+ })(),
879
+ (0, process_message_1.default)(msg, {
880
+ shouldProcessHistoryMsg,
881
+ ev,
882
+ creds: authState.creds,
883
+ keyStore: authState.keys,
884
+ logger,
885
+ options: config.options,
886
+ getMessage: config.getMessage,
887
+ })
888
+ ]);
889
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
890
+ pendingAppStateSync) {
891
+ await doAppStateSync();
892
+ pendingAppStateSync = false;
893
+ }
894
+ async function doAppStateSync() {
895
+ if (!authState.creds.accountSyncCounter) {
896
+ logger.info('doing initial app state sync');
897
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
898
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
899
+ ev.emit('creds.update', { accountSyncCounter });
900
+ if (needToFlushWithAppStateSync) {
901
+ logger.debug('flushing with app state sync');
902
+ ev.flush();
903
+ }
904
+ }
905
+ }
906
+ });
907
+ ws.on('CB:presence', handlePresenceUpdate);
908
+ ws.on('CB:chatstate', handlePresenceUpdate);
909
+ ws.on('CB:ib,,dirty', async (node) => {
910
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
911
+ const type = attrs.type;
912
+ switch (type) {
913
+ case 'account_sync':
914
+ if (attrs.timestamp) {
915
+ let { lastAccountSyncTimestamp } = authState.creds;
916
+ if (lastAccountSyncTimestamp) {
917
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
918
+ }
919
+ lastAccountSyncTimestamp = +attrs.timestamp;
920
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
921
+ }
922
+ break;
923
+ case 'groups':
924
+ // handled in groups.ts
925
+ break;
926
+ default:
927
+ logger.info({ node }, 'received unknown sync');
928
+ break;
929
+ }
930
+ });
931
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
932
+ var _a;
933
+ if (connection === 'open') {
934
+ if (fireInitQueries) {
935
+ executeInitQueries()
936
+ .catch(error => onUnexpectedError(error, 'init queries'));
937
+ }
938
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
939
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
940
+ }
941
+ if (receivedPendingNotifications) {
942
+ // if we don't have the app state key
943
+ // we keep buffering events until we finally have
944
+ // the key and can sync the messages
945
+ if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
946
+ ev.buffer();
947
+ needToFlushWithAppStateSync = true;
948
+ }
949
+ }
950
+ });
951
+ return {
952
+ ...sock,
953
+ processingMutex,
954
+ fetchPrivacySettings,
955
+ upsertMessage,
956
+ appPatch,
957
+ sendPresenceUpdate,
958
+ presenceSubscribe,
959
+ profilePictureUrl,
960
+ onWhatsApp,
961
+ fetchBlocklist,
962
+ fetchStatus,
963
+ updateProfilePicture,
964
+ removeProfilePicture,
965
+ updateProfileStatus,
966
+ updateProfileName,
967
+ updateBlockStatus,
968
+ updateLastSeenPrivacy,
969
+ updateOnlinePrivacy,
970
+ updateProfilePicturePrivacy,
971
+ updateStatusPrivacy,
972
+ updateReadReceiptsPrivacy,
973
+ updateGroupsAddPrivacy,
974
+ updateDefaultDisappearingMode,
975
+ getBusinessProfile,
976
+ resyncAppState,
977
+ chatModify,
978
+ cleanDirtyBits,
979
+ addChatLabel,
980
+ removeChatLabel,
981
+ addMessageLabel,
982
+ checkWhatsApp,
983
+ removeMessageLabel,
984
+ star
985
+ };
986
+ };
987
+ exports.makeChatsSocket = makeChatsSocket;