violetics 7.0.0-alpha

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