cuki-bailx 1.2.4 → 1.2.6

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 (157) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +4775 -0
  4. package/WAProto/index.js +56886 -17506
  5. package/engine-requirements.js +1 -1
  6. package/lib/Defaults/index.js +98 -108
  7. package/lib/Defaults/vyzen-baileysx-version.json +3 -0
  8. package/lib/Signal/libsignal.js +2 -0
  9. package/lib/Socket/Client/index.js +2 -3
  10. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +54 -5
  11. package/lib/Socket/chats.js +224 -173
  12. package/lib/Socket/groups.js +20 -5
  13. package/lib/Socket/index.js +2 -2
  14. package/lib/Socket/messages-recv.js +10 -66
  15. package/lib/Socket/messages-send.js +379 -312
  16. package/lib/Socket/newsletter.js +54 -40
  17. package/lib/Socket/socket.js +58 -32
  18. package/lib/Store/index.js +1 -3
  19. package/lib/Store/make-in-memory-store.js +27 -15
  20. package/lib/Store/make-ordered-dictionary.js +2 -2
  21. package/lib/Types/Label.js +1 -1
  22. package/lib/Types/LabelAssociation.js +1 -1
  23. package/lib/Types/Message.js +0 -2
  24. package/lib/Types/Newsletter.js +3 -17
  25. package/lib/Types/index.js +2 -2
  26. package/lib/Utils/auth-utils.js +6 -13
  27. package/lib/Utils/baileys-event-stream.js +1 -1
  28. package/lib/Utils/browser-utils.js +35 -0
  29. package/lib/Utils/business.js +2 -2
  30. package/lib/Utils/chat-utils.js +36 -35
  31. package/lib/Utils/crypto.js +71 -29
  32. package/lib/Utils/decode-wa-message.js +65 -56
  33. package/lib/Utils/event-buffer.js +13 -9
  34. package/lib/Utils/generics.js +107 -29
  35. package/lib/Utils/history.js +4 -6
  36. package/lib/Utils/index.js +2 -0
  37. package/lib/Utils/link-preview.js +34 -1
  38. package/lib/Utils/lt-hash.js +6 -6
  39. package/lib/Utils/message-retry-manager.js +128 -0
  40. package/lib/Utils/messages-media.js +263 -115
  41. package/lib/Utils/messages.js +500 -93
  42. package/lib/Utils/noise-handler.js +18 -23
  43. package/lib/Utils/process-message.js +108 -25
  44. package/lib/Utils/signal.js +37 -35
  45. package/lib/Utils/use-multi-file-auth-state.js +51 -6
  46. package/lib/Utils/validate-connection.js +90 -66
  47. package/lib/WABinary/constants.js +1276 -13
  48. package/lib/WABinary/decode.js +26 -13
  49. package/lib/WABinary/encode.js +39 -17
  50. package/lib/WABinary/generic-utils.js +2 -85
  51. package/lib/WABinary/jid-utils.js +28 -5
  52. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  53. package/lib/index.js +18 -5
  54. package/package.json +109 -104
  55. package/lib/Defaults/baileys-version.json +0 -3
  56. package/lib/Defaults/index.d.ts +0 -53
  57. package/lib/Defaults/phonenumber-mcc.json +0 -223
  58. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  59. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  60. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  61. package/lib/Signal/Group/index.d.ts +0 -11
  62. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  63. package/lib/Signal/Group/queue-job.d.ts +0 -1
  64. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  65. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  66. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  67. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  68. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  69. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  70. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  71. package/lib/Signal/libsignal.d.ts +0 -3
  72. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  73. package/lib/Socket/Client/index.d.ts +0 -3
  74. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  75. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  76. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  77. package/lib/Socket/business.d.ts +0 -171
  78. package/lib/Socket/chats.d.ts +0 -80
  79. package/lib/Socket/dugong.d.ts +0 -219
  80. package/lib/Socket/dugong.js +0 -441
  81. package/lib/Socket/groups.d.ts +0 -115
  82. package/lib/Socket/index.d.ts +0 -173
  83. package/lib/Socket/messages-recv.d.ts +0 -161
  84. package/lib/Socket/messages-send.d.ts +0 -149
  85. package/lib/Socket/newsletter.d.ts +0 -134
  86. package/lib/Socket/registration.d.ts +0 -267
  87. package/lib/Socket/registration.js +0 -166
  88. package/lib/Socket/socket.d.ts +0 -43
  89. package/lib/Socket/socket.js.bak +0 -630
  90. package/lib/Socket/usync.d.ts +0 -36
  91. package/lib/Store/index.d.ts +0 -3
  92. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  93. package/lib/Store/make-cache-manager-store.js +0 -83
  94. package/lib/Store/make-in-memory-store.d.ts +0 -118
  95. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  96. package/lib/Store/object-repository.d.ts +0 -10
  97. package/lib/Types/Auth.d.ts +0 -110
  98. package/lib/Types/Call.d.ts +0 -13
  99. package/lib/Types/Chat.d.ts +0 -102
  100. package/lib/Types/Contact.d.ts +0 -19
  101. package/lib/Types/Events.d.ts +0 -157
  102. package/lib/Types/GroupMetadata.d.ts +0 -55
  103. package/lib/Types/Label.d.ts +0 -35
  104. package/lib/Types/LabelAssociation.d.ts +0 -29
  105. package/lib/Types/Message.d.ts +0 -273
  106. package/lib/Types/Newsletter.d.ts +0 -92
  107. package/lib/Types/Product.d.ts +0 -78
  108. package/lib/Types/Signal.d.ts +0 -57
  109. package/lib/Types/Socket.d.ts +0 -111
  110. package/lib/Types/State.d.ts +0 -27
  111. package/lib/Types/USync.d.ts +0 -25
  112. package/lib/Types/index.d.ts +0 -57
  113. package/lib/Utils/auth-utils.d.ts +0 -18
  114. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  115. package/lib/Utils/business.d.ts +0 -22
  116. package/lib/Utils/chat-utils.d.ts +0 -71
  117. package/lib/Utils/crypto.d.ts +0 -41
  118. package/lib/Utils/decode-wa-message.d.ts +0 -19
  119. package/lib/Utils/event-buffer.d.ts +0 -35
  120. package/lib/Utils/generics.d.ts +0 -92
  121. package/lib/Utils/history.d.ts +0 -15
  122. package/lib/Utils/index.d.ts +0 -17
  123. package/lib/Utils/link-preview.d.ts +0 -21
  124. package/lib/Utils/logger.d.ts +0 -4
  125. package/lib/Utils/lt-hash.d.ts +0 -12
  126. package/lib/Utils/make-mutex.d.ts +0 -7
  127. package/lib/Utils/messages-media.d.ts +0 -116
  128. package/lib/Utils/messages.d.ts +0 -77
  129. package/lib/Utils/noise-handler.d.ts +0 -21
  130. package/lib/Utils/process-message.d.ts +0 -41
  131. package/lib/Utils/signal.d.ts +0 -32
  132. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  133. package/lib/Utils/validate-connection.d.ts +0 -11
  134. package/lib/WABinary/constants.d.ts +0 -27
  135. package/lib/WABinary/decode.d.ts +0 -7
  136. package/lib/WABinary/encode.d.ts +0 -3
  137. package/lib/WABinary/generic-utils.d.ts +0 -16
  138. package/lib/WABinary/index.d.ts +0 -5
  139. package/lib/WABinary/jid-utils.d.ts +0 -31
  140. package/lib/WABinary/types.d.ts +0 -18
  141. package/lib/WAM/BinaryInfo.d.ts +0 -17
  142. package/lib/WAM/constants.d.ts +0 -38
  143. package/lib/WAM/encode.d.ts +0 -3
  144. package/lib/WAM/index.d.ts +0 -3
  145. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  146. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  147. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  148. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  149. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  150. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  151. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  152. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  153. package/lib/WAUSync/USyncUser.d.ts +0 -12
  154. package/lib/WAUSync/index.d.ts +0 -3
  155. package/lib/index.d.ts +0 -12
  156. package/lib/index.js.bak +0 -48
  157. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.makeChatsSocket = void 0;
7
7
  const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
8
9
  const WAProto_1 = require("../../WAProto");
9
10
  const Defaults_1 = require("../Defaults");
10
11
  const Types_1 = require("../Types");
@@ -12,20 +13,33 @@ const Utils_1 = require("../Utils");
12
13
  const make_mutex_1 = require("../Utils/make-mutex");
13
14
  const process_message_1 = __importDefault(require("../Utils/process-message"));
14
15
  const WABinary_1 = require("../WABinary");
15
- const socket_1 = require("./socket");
16
16
  const WAUSync_1 = require("../WAUSync");
17
17
  const usync_1 = require("./usync");
18
+ const chalk = require('chalk');
18
19
  const MAX_SYNC_ATTEMPTS = 2;
20
+ const SyncState = {
21
+ Connecting: 'connecting',
22
+ AwaitingInitialSync: 'awaiting_initial_sync',
23
+ Syncing: 'syncing',
24
+ Online: 'online'
25
+ };
19
26
  const makeChatsSocket = (config) => {
20
27
  const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
28
  const sock = (0, usync_1.makeUSyncSocket)(config);
22
- const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
29
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, } = sock;
23
30
  let privacySettings;
31
+ let syncState = SyncState.Connecting;
24
32
  let needToFlushWithAppStateSync = false;
25
33
  let pendingAppStateSync = false;
26
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
34
+ let awaitingSyncTimeout;
27
35
  const processingMutex = (0, make_mutex_1.makeMutex)();
28
- /** helper function to fetch the given app state sync key */
36
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
37
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
38
+ useClones: false
39
+ });
40
+ if (!config.placeholderResendCache) {
41
+ config.placeholderResendCache = placeholderResendCache;
42
+ }
29
43
  const getAppStateSyncKey = async (keyId) => {
30
44
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
31
45
  return key;
@@ -47,7 +61,6 @@ const makeChatsSocket = (config) => {
47
61
  }
48
62
  return privacySettings;
49
63
  };
50
- /** helper function to run a privacy IQ query */
51
64
  const privacyQuery = async (name, value) => {
52
65
  await query({
53
66
  tag: 'iq',
@@ -68,6 +81,12 @@ const makeChatsSocket = (config) => {
68
81
  }]
69
82
  });
70
83
  };
84
+ const updateMessagesPrivacy = async (value) => {
85
+ await privacyQuery('messages', value);
86
+ };
87
+ const updateCallPrivacy = async (value) => {
88
+ await privacyQuery('calladd', value);
89
+ };
71
90
  const updateLastSeenPrivacy = async (value) => {
72
91
  await privacyQuery('last', value);
73
92
  };
@@ -86,6 +105,9 @@ const makeChatsSocket = (config) => {
86
105
  const updateGroupsAddPrivacy = async (value) => {
87
106
  await privacyQuery('groupadd', value);
88
107
  };
108
+ const updateDisableLinkPreviewsPrivacy = async (isPreviewsDisabled) => {
109
+ return chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '');
110
+ };
89
111
  const updateDefaultDisappearingMode = async (duration) => {
90
112
  await query({
91
113
  tag: 'iq',
@@ -102,44 +124,34 @@ const makeChatsSocket = (config) => {
102
124
  }]
103
125
  });
104
126
  };
105
- /** helper function to run a generic IQ query */
106
- const interactiveQuery = async (userNodes, queryNode) => {
107
- const result = await query({
127
+ const getBotListV2 = async () => {
128
+ const resp = await query({
108
129
  tag: 'iq',
109
130
  attrs: {
131
+ xmlns: 'bot',
110
132
  to: WABinary_1.S_WHATSAPP_NET,
111
- type: 'get',
112
- xmlns: 'usync',
133
+ type: 'get'
113
134
  },
114
- content: [
115
- {
116
- tag: 'usync',
135
+ content: [{
136
+ tag: 'bot',
117
137
  attrs: {
118
- sid: generateMessageTag(),
119
- mode: 'query',
120
- last: 'true',
121
- index: '0',
122
- context: 'interactive',
123
- },
124
- content: [
125
- {
126
- tag: 'query',
127
- attrs: {},
128
- content: [queryNode]
129
- },
130
- {
131
- tag: 'list',
132
- attrs: {},
133
- content: userNodes
134
- }
135
- ]
136
- }
137
- ],
138
+ v: '2'
139
+ }
140
+ }]
138
141
  });
139
- const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
140
- const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
141
- const users = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'user');
142
- return users;
142
+ const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
143
+ const botList = [];
144
+ for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
145
+ if (section.attrs.type === 'all') {
146
+ for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
147
+ botList.push({
148
+ jid: bot.attrs.jid,
149
+ personaId: bot.attrs['persona_id']
150
+ });
151
+ }
152
+ }
153
+ }
154
+ return botList;
143
155
  };
144
156
  const onWhatsApp = async (...jids) => {
145
157
  const usyncQuery = new WAUSync_1.USyncQuery()
@@ -154,26 +166,37 @@ const makeChatsSocket = (config) => {
154
166
  return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
155
167
  }
156
168
  };
157
- const fetchStatus = async (jid) => {
158
- const [result] = await interactiveQuery([{ tag: 'user', attrs: { jid } }], { tag: 'status', attrs: {} });
169
+ const fetchStatus = async (...jids) => {
170
+ const usyncQuery = new WAUSync_1.USyncQuery()
171
+ .withStatusProtocol();
172
+ for (const jid of jids) {
173
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
174
+ }
175
+ const result = await sock.executeUSyncQuery(usyncQuery);
159
176
  if (result) {
160
- const status = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
161
- return {
162
- status: status === null || status === void 0 ? void 0 : status.content.toString(),
163
- setAt: new Date(+((status === null || status === void 0 ? void 0 : status.attrs.t) || 0) * 1000)
164
- };
177
+ return result.list;
165
178
  }
166
179
  };
167
- /** update the profile picture for yourself or a group */
168
- const updateProfilePicture = async (jid, content) => {
180
+ const fetchDisappearingDuration = async (...jids) => {
181
+ const usyncQuery = new WAUSync_1.USyncQuery()
182
+ .withDisappearingModeProtocol();
183
+ for (const jid of jids) {
184
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
185
+ }
186
+ const result = await sock.executeUSyncQuery(usyncQuery);
187
+ if (result) {
188
+ return result.list;
189
+ }
190
+ };
191
+ const updateProfilePicture = async (jid, content, dimensions) => {
169
192
  let targetJid;
170
193
  if (!jid) {
171
194
  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');
172
195
  }
173
196
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
174
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
197
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
175
198
  }
176
- const { img } = await (0, Utils_1.generateProfilePicture)(content);
199
+ const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions);
177
200
  await query({
178
201
  tag: 'iq',
179
202
  attrs: {
@@ -191,14 +214,13 @@ const makeChatsSocket = (config) => {
191
214
  ]
192
215
  });
193
216
  };
194
- /** remove the profile picture for yourself or a group */
195
217
  const removeProfilePicture = async (jid) => {
196
218
  let targetJid;
197
219
  if (!jid) {
198
220
  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
221
  }
200
222
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
201
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
223
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
202
224
  }
203
225
  await query({
204
226
  tag: 'iq',
@@ -210,7 +232,6 @@ const makeChatsSocket = (config) => {
210
232
  }
211
233
  });
212
234
  };
213
- /** update the profile status for yourself */
214
235
  const updateProfileStatus = async (status) => {
215
236
  await query({
216
237
  tag: 'iq',
@@ -290,9 +311,9 @@ const makeChatsSocket = (config) => {
290
311
  const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
291
312
  const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
292
313
  const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
293
- const businessHoursConfig = businessHours ?
294
- (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config') :
295
- undefined;
314
+ const businessHoursConfig = businessHours
315
+ ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
316
+ : undefined;
296
317
  const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
297
318
  return {
298
319
  wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
@@ -337,18 +358,12 @@ const makeChatsSocket = (config) => {
337
358
  };
338
359
  };
339
360
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
340
- // we use this to determine which events to fire
341
- // otherwise when we resync from scratch -- all notifications will fire
342
361
  const initialVersionMap = {};
343
362
  const globalMutationMap = {};
344
363
  await authState.keys.transaction(async () => {
345
364
  var _a;
346
365
  const collectionsToHandle = new Set(collections);
347
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
348
366
  const attemptsMap = {};
349
- // keep executing till all collections are done
350
- // sometimes a single patch request will not return all the patches (God knows why)
351
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
352
367
  while (collectionsToHandle.size) {
353
368
  const states = {};
354
369
  const nodes = [];
@@ -370,7 +385,6 @@ const makeChatsSocket = (config) => {
370
385
  attrs: {
371
386
  name,
372
387
  version: state.version.toString(),
373
- // return snapshot if being synced from scratch
374
388
  'return_snapshot': (!state.version).toString()
375
389
  }
376
390
  });
@@ -390,7 +404,6 @@ const makeChatsSocket = (config) => {
390
404
  }
391
405
  ]
392
406
  });
393
- // extract from binary node
394
407
  const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
395
408
  for (const key in decoded) {
396
409
  const name = key;
@@ -401,16 +414,11 @@ const makeChatsSocket = (config) => {
401
414
  states[name] = newState;
402
415
  Object.assign(globalMutationMap, mutationMap);
403
416
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
404
- await authState.keys.set({ 'app-state-sync-version': {
405
- [name]: newState
406
- } });
417
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
407
418
  }
408
- // only process if there are syncd patches
409
419
  if (patches.length) {
410
420
  const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
411
- await authState.keys.set({ 'app-state-sync-version': {
412
- [name]: newState
413
- } });
421
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
414
422
  logger.info(`synced ${name} to v${newState.version}`);
415
423
  initialVersionMap[name] = newState.version;
416
424
  Object.assign(globalMutationMap, mutationMap);
@@ -418,24 +426,18 @@ const makeChatsSocket = (config) => {
418
426
  if (hasMorePatches) {
419
427
  logger.info(`${name} has more patches...`);
420
428
  }
421
- else { // collection is done with sync
429
+ else {
422
430
  collectionsToHandle.delete(name);
423
431
  }
424
432
  }
425
433
  catch (error) {
426
- // if retry attempts overshoot
427
- // or key not found
428
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
429
- ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
430
- error.name === 'TypeError';
434
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
435
+ || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
436
+ || error.name === 'TypeError';
431
437
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
432
- await authState.keys.set({ 'app-state-sync-version': {
433
- [name]: null
434
- } });
435
- // increment number of retries
438
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
436
439
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
437
440
  if (isIrrecoverableError) {
438
- // stop retrying
439
441
  collectionsToHandle.delete(name);
440
442
  }
441
443
  }
@@ -447,28 +449,56 @@ const makeChatsSocket = (config) => {
447
449
  onMutation(globalMutationMap[key]);
448
450
  }
449
451
  });
450
- /**
451
- * fetch the profile picture of a user/group
452
- * type = "preview" for a low res picture
453
- * type = "image for the high res picture"
454
- */
455
452
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
456
453
  var _a;
457
454
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
455
+ try {
456
+ const result = await query({
457
+ tag: 'iq',
458
+ attrs: {
459
+ target: jid,
460
+ to: WABinary_1.S_WHATSAPP_NET,
461
+ type: 'get',
462
+ xmlns: 'w:profile:picture'
463
+ },
464
+ content: [
465
+ { tag: 'picture', attrs: { type, query: 'url' } }
466
+ ]
467
+ }, timeoutMs);
468
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
469
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
470
+ } catch (error) {
471
+ if (error.message?.includes('item-not-found') ||
472
+ error.output?.payload?.statusCode === 404 ||
473
+ error.statusCode === 404) {
474
+ logger.info(chalk.gray(`[INFO] Profile pic not found for ${jid}, using fallback`));
475
+ return {
476
+ eurl: undefined,
477
+ id: jid.split('@')[0],
478
+ status: null,
479
+ img: null
480
+ };
481
+ }
482
+ throw error;
483
+ }
484
+ };
485
+ const createCallLink = async (type, event, timeoutMs) => {
458
486
  const result = await query({
459
- tag: 'iq',
487
+ tag: 'call',
460
488
  attrs: {
461
- target: jid,
462
- to: WABinary_1.S_WHATSAPP_NET,
463
- type: 'get',
464
- xmlns: 'w:profile:picture'
489
+ id: generateMessageTag(),
490
+ to: '@call'
465
491
  },
466
492
  content: [
467
- { tag: 'picture', attrs: { type, query: 'url' } }
493
+ {
494
+ tag: 'link_create',
495
+ attrs: { media: type },
496
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
497
+ }
468
498
  ]
469
499
  }, timeoutMs);
470
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
471
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
500
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'link_create');
501
+ return child?.attrs?.token;
472
502
  };
473
503
  const sendPresenceUpdate = async (type, toJid) => {
474
504
  const me = authState.creds.me;
@@ -481,7 +511,7 @@ const makeChatsSocket = (config) => {
481
511
  await sendNode({
482
512
  tag: 'presence',
483
513
  attrs: {
484
- name: me.name,
514
+ name: me.name.replace(/@/g, ''),
485
515
  type
486
516
  }
487
517
  });
@@ -504,10 +534,6 @@ const makeChatsSocket = (config) => {
504
534
  });
505
535
  }
506
536
  };
507
- /**
508
- * @param toJid the jid to subscribe to
509
- * @param tcToken token for subscription, use if present
510
- */
511
537
  const presenceSubscribe = (toJid, tcToken) => (sendNode({
512
538
  tag: 'presence',
513
539
  attrs: {
@@ -515,22 +541,22 @@ const makeChatsSocket = (config) => {
515
541
  id: generateMessageTag(),
516
542
  type: 'subscribe'
517
543
  },
518
- content: tcToken ?
519
- [
544
+ content: tcToken
545
+ ? [
520
546
  {
521
547
  tag: 'tctoken',
522
548
  attrs: {},
523
549
  content: tcToken
524
550
  }
525
- ] :
526
- undefined
551
+ ]
552
+ : undefined
527
553
  }));
528
554
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
529
555
  var _a;
530
556
  let presence;
531
557
  const jid = attrs.from;
532
558
  const participant = attrs.participant || attrs.from;
533
- if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
559
+ if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
534
560
  return;
535
561
  }
536
562
  if (tag === 'presence') {
@@ -554,9 +580,7 @@ const makeChatsSocket = (config) => {
554
580
  logger.error({ tag, attrs, content }, 'recv invalid presence node');
555
581
  }
556
582
  if (presence) {
557
- ev.emit('presence.update', { id: jid, presences: {
558
- [participant]: presence
559
- } });
583
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
560
584
  }
561
585
  };
562
586
  const appPatch = async (patchCreate) => {
@@ -607,9 +631,7 @@ const makeChatsSocket = (config) => {
607
631
  ]
608
632
  };
609
633
  await query(node);
610
- await authState.keys.set({ 'app-state-sync-version': {
611
- [name]: state
612
- } });
634
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
613
635
  });
614
636
  });
615
637
  if (config.emitOwnEvents) {
@@ -620,9 +642,8 @@ const makeChatsSocket = (config) => {
620
642
  }
621
643
  }
622
644
  };
623
- /** sending non-abt props may fix QR scan fail if server expects */
624
645
  const fetchProps = async () => {
625
- var _a, _b;
646
+ var _a, _b, _c;
626
647
  const resultNode = await query({
627
648
  tag: 'iq',
628
649
  attrs: {
@@ -631,37 +652,28 @@ const makeChatsSocket = (config) => {
631
652
  type: 'get',
632
653
  },
633
654
  content: [
634
- {
635
- tag: 'props',
636
- attrs: {
655
+ { tag: 'props', attrs: {
637
656
  protocol: '2',
638
657
  hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
639
- }
640
- }
658
+ } }
641
659
  ]
642
660
  });
643
661
  const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
644
662
  let props = {};
645
663
  if (propsNode) {
646
- authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
647
- ev.emit('creds.update', authState.creds);
664
+ if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) {
665
+ authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
666
+ ev.emit('creds.update', authState.creds);
667
+ }
648
668
  props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
649
669
  }
650
670
  logger.debug('fetched props');
651
671
  return props;
652
672
  };
653
- /**
654
- * modify a chat -- mark unread, read etc.
655
- * lastMessages must be sorted in reverse chronologically
656
- * requires the last messages till the last message received; required for archive & unread
657
- */
658
673
  const chatModify = (mod, jid) => {
659
674
  const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
660
675
  return appPatch(patch);
661
676
  };
662
- /**
663
- * Star or Unstar a message
664
- */
665
677
  const star = (jid, messages, star) => {
666
678
  return chatModify({
667
679
  star: {
@@ -670,9 +682,15 @@ const makeChatsSocket = (config) => {
670
682
  }
671
683
  }, jid);
672
684
  };
673
- /**
674
- * Adds label for the chats
675
- */
685
+ const addOrEditContact = (jid, contact) => {
686
+ return chatModify({ contact }, jid);
687
+ };
688
+ const removeContact = (jid) => {
689
+ return chatModify({ contact: null }, jid);
690
+ };
691
+ const addLabel = (jid, labels) => {
692
+ return chatModify({ addLabel: { ...labels } }, jid);
693
+ };
676
694
  const addChatLabel = (jid, labelId) => {
677
695
  return chatModify({
678
696
  addChatLabel: {
@@ -680,9 +698,6 @@ const makeChatsSocket = (config) => {
680
698
  }
681
699
  }, jid);
682
700
  };
683
- /**
684
- * Removes label for the chat
685
- */
686
701
  const removeChatLabel = (jid, labelId) => {
687
702
  return chatModify({
688
703
  removeChatLabel: {
@@ -690,9 +705,6 @@ const makeChatsSocket = (config) => {
690
705
  }
691
706
  }, jid);
692
707
  };
693
- /**
694
- * Adds label for the message
695
- */
696
708
  const addMessageLabel = (jid, messageId, labelId) => {
697
709
  return chatModify({
698
710
  addMessageLabel: {
@@ -701,9 +713,6 @@ const makeChatsSocket = (config) => {
701
713
  }
702
714
  }, jid);
703
715
  };
704
- /**
705
- * Removes label for the message
706
- */
707
716
  const removeMessageLabel = (jid, messageId, labelId) => {
708
717
  return chatModify({
709
718
  removeMessageLabel: {
@@ -712,10 +721,6 @@ const makeChatsSocket = (config) => {
712
721
  }
713
722
  }, jid);
714
723
  };
715
- /**
716
- * queries need to be fired on connection open
717
- * help ensure parity with WA Web
718
- * */
719
724
  const executeInitQueries = async () => {
720
725
  await Promise.all([
721
726
  fetchProps(),
@@ -732,30 +737,56 @@ const makeChatsSocket = (config) => {
732
737
  if (!msg.key.fromMe) {
733
738
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
734
739
  }
735
- // update our pushname too
736
740
  if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
737
741
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
738
742
  }
739
743
  }
740
744
  const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
741
- const shouldProcessHistoryMsg = historyMsg ?
742
- (shouldSyncHistoryMessage(historyMsg) &&
743
- Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
744
- false;
745
+ const shouldProcessHistoryMsg = historyMsg
746
+ ? (shouldSyncHistoryMessage(historyMsg)
747
+ && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
748
+ : false;
749
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
750
+ if (awaitingSyncTimeout) {
751
+ clearTimeout(awaitingSyncTimeout);
752
+ awaitingSyncTimeout = undefined;
753
+ }
754
+ if (shouldProcessHistoryMsg) {
755
+ syncState = SyncState.Syncing;
756
+ logger.info('Transitioned to Syncing state');
757
+ } else {
758
+ syncState = SyncState.Online;
759
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
760
+ ev.flush();
761
+ }
762
+ }
763
+ const doAppStateSync = async () => {
764
+ if (syncState === SyncState.Syncing) {
765
+ logger.info('Doing app state sync');
766
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
767
+ syncState = SyncState.Online;
768
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
769
+ ev.flush();
770
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
771
+ ev.emit('creds.update', { accountSyncCounter });
772
+ }
773
+ };
745
774
  if (historyMsg && !authState.creds.myAppStateKeyId) {
746
775
  logger.warn('skipping app state sync, as myAppStateKeyId is not set');
747
776
  pendingAppStateSync = true;
748
777
  }
749
778
  await Promise.all([
750
779
  (async () => {
751
- if (historyMsg &&
752
- authState.creds.myAppStateKeyId) {
780
+ if (historyMsg
781
+ && authState.creds.myAppStateKeyId) {
753
782
  pendingAppStateSync = false;
754
783
  await doAppStateSync();
755
784
  }
756
785
  })(),
757
786
  (0, process_message_1.default)(msg, {
787
+ signalRepository,
758
788
  shouldProcessHistoryMsg,
789
+ placeholderResendCache,
759
790
  ev,
760
791
  creds: authState.creds,
761
792
  keyStore: authState.keys,
@@ -764,23 +795,11 @@ const makeChatsSocket = (config) => {
764
795
  getMessage: config.getMessage,
765
796
  })
766
797
  ]);
767
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
768
- pendingAppStateSync) {
798
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
799
+ && pendingAppStateSync) {
769
800
  await doAppStateSync();
770
801
  pendingAppStateSync = false;
771
802
  }
772
- async function doAppStateSync() {
773
- if (!authState.creds.accountSyncCounter) {
774
- logger.info('doing initial app state sync');
775
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
776
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
777
- ev.emit('creds.update', { accountSyncCounter });
778
- if (needToFlushWithAppStateSync) {
779
- logger.debug('flushing with app state sync');
780
- ev.flush();
781
- }
782
- }
783
- }
784
803
  });
785
804
  ws.on('CB:presence', handlePresenceUpdate);
786
805
  ws.on('CB:chatstate', handlePresenceUpdate);
@@ -799,7 +818,6 @@ const makeChatsSocket = (config) => {
799
818
  }
800
819
  break;
801
820
  case 'groups':
802
- // handled in groups.ts
803
821
  break;
804
822
  default:
805
823
  logger.info({ node }, 'received unknown sync');
@@ -816,18 +834,44 @@ const makeChatsSocket = (config) => {
816
834
  sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
817
835
  .catch(error => onUnexpectedError(error, 'presence update requests'));
818
836
  }
819
- if (receivedPendingNotifications) {
820
- // if we don't have the app state key
821
- // we keep buffering events until we finally have
822
- // the key and can sync the messages
823
- if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
824
- ev.buffer();
825
- needToFlushWithAppStateSync = true;
826
- }
837
+ if (receivedPendingNotifications &&
838
+ !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
839
+ ev.buffer();
840
+ needToFlushWithAppStateSync = true;
841
+ }
842
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
843
+ return;
827
844
  }
845
+ syncState = SyncState.AwaitingInitialSync;
846
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
847
+ ev.buffer();
848
+ const willSyncHistory = shouldSyncHistoryMessage(
849
+ WAProto_1.proto.Message.HistorySyncNotification.create({
850
+ syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
851
+ })
852
+ );
853
+ if (!willSyncHistory) {
854
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
855
+ syncState = SyncState.Online;
856
+ setTimeout(() => ev.flush(), 0);
857
+ return;
858
+ }
859
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
860
+ if (awaitingSyncTimeout) {
861
+ clearTimeout(awaitingSyncTimeout);
862
+ }
863
+ awaitingSyncTimeout = setTimeout(() => {
864
+ if (syncState === SyncState.AwaitingInitialSync) {
865
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
866
+ syncState = SyncState.Online;
867
+ ev.flush();
868
+ }
869
+ }, 20000);
828
870
  });
829
871
  return {
830
872
  ...sock,
873
+ createCallLink,
874
+ getBotListV2,
831
875
  processingMutex,
832
876
  fetchPrivacySettings,
833
877
  upsertMessage,
@@ -837,12 +881,16 @@ const makeChatsSocket = (config) => {
837
881
  profilePictureUrl,
838
882
  onWhatsApp,
839
883
  fetchBlocklist,
884
+ fetchDisappearingDuration,
840
885
  fetchStatus,
841
886
  updateProfilePicture,
842
887
  removeProfilePicture,
843
888
  updateProfileStatus,
844
889
  updateProfileName,
845
890
  updateBlockStatus,
891
+ updateDisableLinkPreviewsPrivacy,
892
+ updateCallPrivacy,
893
+ updateMessagesPrivacy,
846
894
  updateLastSeenPrivacy,
847
895
  updateOnlinePrivacy,
848
896
  updateProfilePicturePrivacy,
@@ -854,6 +902,9 @@ const makeChatsSocket = (config) => {
854
902
  resyncAppState,
855
903
  chatModify,
856
904
  cleanDirtyBits,
905
+ addOrEditContact,
906
+ removeContact,
907
+ addLabel,
857
908
  addChatLabel,
858
909
  removeChatLabel,
859
910
  addMessageLabel,
@@ -861,4 +912,4 @@ const makeChatsSocket = (config) => {
861
912
  star
862
913
  };
863
914
  };
864
- exports.makeChatsSocket = makeChatsSocket;
915
+ exports.makeChatsSocket = makeChatsSocket;