@baileys-md/baileys 10.0.7

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