@sanzoffc/baileys 3.0.1 → 3.0.2

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