@ms-nicky/baileys 2.0.3

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