@sanz-0fx/baileys-mod 1.0.3-beta

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