@nexustechpro/baileys 1.0.1

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