@gara31/void-baileys 7.0.0-rc.10

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