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