torbaileys 8.0.0

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