xhyphersockets 1.4.3 → 2.4.3

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 (125) hide show
  1. package/LICENSE +1 -1
  2. package/README.MD +1295 -0
  3. package/WAProto/p.html +1 -0
  4. package/lib/Defaults/index.js +47 -35
  5. package/lib/Defaults/wileys-version.json +3 -0
  6. package/lib/Socket/chats.js +132 -125
  7. package/lib/Socket/messages-recv.js +1 -1
  8. package/lib/Socket/messages-send.js +1 -32
  9. package/lib/Socket/newsletter.js +71 -124
  10. package/lib/Socket/socket.js +1 -1
  11. package/lib/Store/make-in-memory-store.js +1 -1
  12. package/lib/Types/Newsletter.js +18 -38
  13. package/lib/Utils/browser-utils.js +35 -0
  14. package/lib/Utils/event-buffer.js +2 -2
  15. package/lib/Utils/generics.js +47 -8
  16. package/lib/Utils/index.js +3 -4
  17. package/lib/Utils/message-retry-manager.js +128 -0
  18. package/lib/Utils/messages-media.js +37 -45
  19. package/lib/Utils/messages.js +19 -0
  20. package/lib/Utils/process-message.js +19 -0
  21. package/lib/Utils/use-multi-file-auth-state.js +1 -1
  22. package/lib/Utils/validate-connection.js +77 -21
  23. package/lib/Utils/{baileys-event-stream.js → wileys-event-stream.js} +1 -1
  24. package/lib/WABinary/jid-utils.js +3 -1
  25. package/lib/index.js +12 -18
  26. package/package.json +28 -22
  27. package/README.md +0 -252
  28. package/WAProto/index.d.ts +0 -55057
  29. package/WAProto/index.ts.ts +0 -53473
  30. package/lib/Defaults/baileys-version.json +0 -3
  31. package/lib/Defaults/index.d.ts +0 -51
  32. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  33. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  34. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  35. package/lib/Signal/Group/index.d.ts +0 -11
  36. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  37. package/lib/Signal/Group/queue-job.d.ts +0 -1
  38. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  39. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  40. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  41. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  42. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  43. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  44. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  45. package/lib/Signal/libsignal.d.ts +0 -3
  46. package/lib/Socket/Client/index.d.ts +0 -2
  47. package/lib/Socket/Client/types.d.ts +0 -16
  48. package/lib/Socket/Client/websocket.d.ts +0 -13
  49. package/lib/Socket/RHandler.d.ts +0 -416
  50. package/lib/Socket/RHandler.js +0 -530
  51. package/lib/Socket/business.d.ts +0 -172
  52. package/lib/Socket/chats.d.ts +0 -94
  53. package/lib/Socket/groups.d.ts +0 -124
  54. package/lib/Socket/index.d.ts +0 -172
  55. package/lib/Socket/messages-recv.d.ts +0 -161
  56. package/lib/Socket/messages-send.d.ts +0 -152
  57. package/lib/Socket/newsletter.d.ts +0 -136
  58. package/lib/Socket/socket.d.ts +0 -43
  59. package/lib/Socket/usync.d.ts +0 -36
  60. package/lib/Store/index.d.ts +0 -2
  61. package/lib/Store/make-in-memory-store.d.ts +0 -118
  62. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  63. package/lib/Store/object-repository.d.ts +0 -10
  64. package/lib/Types/Auth.d.ts +0 -103
  65. package/lib/Types/Call.d.ts +0 -13
  66. package/lib/Types/Chat.d.ts +0 -109
  67. package/lib/Types/Contact.d.ts +0 -23
  68. package/lib/Types/Events.d.ts +0 -199
  69. package/lib/Types/GroupMetadata.d.ts +0 -64
  70. package/lib/Types/Label.d.ts +0 -35
  71. package/lib/Types/LabelAssociation.d.ts +0 -29
  72. package/lib/Types/Message.d.ts +0 -402
  73. package/lib/Types/Newsletter.d.ts +0 -103
  74. package/lib/Types/Product.d.ts +0 -78
  75. package/lib/Types/Signal.d.ts +0 -57
  76. package/lib/Types/Socket.d.ts +0 -119
  77. package/lib/Types/State.d.ts +0 -27
  78. package/lib/Types/USync.d.ts +0 -25
  79. package/lib/Types/index.d.ts +0 -64
  80. package/lib/Utils/audioToBuffer.js +0 -29
  81. package/lib/Utils/auth-utils.d.ts +0 -18
  82. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  83. package/lib/Utils/business.d.ts +0 -22
  84. package/lib/Utils/chat-utils.d.ts +0 -70
  85. package/lib/Utils/crypto.d.ts +0 -40
  86. package/lib/Utils/decode-wa-message.d.ts +0 -35
  87. package/lib/Utils/event-buffer.d.ts +0 -35
  88. package/lib/Utils/generics.d.ts +0 -89
  89. package/lib/Utils/history.d.ts +0 -19
  90. package/lib/Utils/index.d.ts +0 -19
  91. package/lib/Utils/link-preview.d.ts +0 -21
  92. package/lib/Utils/logger.d.ts +0 -11
  93. package/lib/Utils/lt-hash.d.ts +0 -12
  94. package/lib/Utils/make-mutex.d.ts +0 -7
  95. package/lib/Utils/messages-media.d.ts +0 -124
  96. package/lib/Utils/messages.d.ts +0 -75
  97. package/lib/Utils/noise-handler.d.ts +0 -19
  98. package/lib/Utils/process-message.d.ts +0 -42
  99. package/lib/Utils/signal.d.ts +0 -33
  100. package/lib/Utils/streamToBuffer.js +0 -15
  101. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  102. package/lib/Utils/validate-connection.d.ts +0 -10
  103. package/lib/WABinary/constants.d.ts +0 -27
  104. package/lib/WABinary/decode.d.ts +0 -6
  105. package/lib/WABinary/encode.d.ts +0 -2
  106. package/lib/WABinary/generic-utils.d.ts +0 -14
  107. package/lib/WABinary/index.d.ts +0 -5
  108. package/lib/WABinary/jid-utils.d.ts +0 -36
  109. package/lib/WABinary/jid-utils.js.bak +0 -83
  110. package/lib/WABinary/types.d.ts +0 -18
  111. package/lib/WAM/BinaryInfo.d.ts +0 -8
  112. package/lib/WAM/constants.d.ts +0 -38
  113. package/lib/WAM/encode.d.ts +0 -2
  114. package/lib/WAM/index.d.ts +0 -3
  115. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  116. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  117. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  118. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  119. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  120. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  121. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  122. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  123. package/lib/WAUSync/USyncUser.d.ts +0 -12
  124. package/lib/WAUSync/index.d.ts +0 -3
  125. package/lib/index.d.ts +0 -16
package/WAProto/p.html ADDED
@@ -0,0 +1 @@
1
+ xhypher
@@ -3,61 +3,69 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_CACHE_TTLS = exports.INITIAL_PREKEY_COUNT = exports.MIN_PREKEY_COUNT = exports.MEDIA_KEYS = exports.MEDIA_HKDF_KEY_MAPPING = exports.MEDIA_PATH_MAP = exports.DEFAULT_CONNECTION_CONFIG = exports.PROCESSABLE_HISTORY_TYPES = exports.WA_CERT_DETAILS = exports.URL_REGEX = exports.NOISE_WA_HEADER = exports.KEY_BUNDLE_TYPE = exports.DICT_VERSION = exports.NOISE_MODE = exports.WA_DEFAULT_EPHEMERAL = exports.PHONE_CONNECTION_CB = exports.DEF_TAG_PREFIX = exports.DEF_CALLBACK_PREFIX = exports.DEFAULT_ORIGIN = exports.UNAUTHORIZED_CODES = void 0;
6
+ exports.DEFAULT_CACHE_TTLS = exports.MIN_UPLOAD_INTERVAL = exports.UPLOAD_TIMEOUT = exports.INITIAL_PREKEY_COUNT = exports.MIN_PREKEY_COUNT = exports.MEDIA_KEYS = exports.MEDIA_HKDF_KEY_MAPPING = exports.MEDIA_PATH_MAP = exports.DEFAULT_CONNECTION_CONFIG = exports.PROCESSABLE_HISTORY_TYPES = exports.WA_CERT_DETAILS = exports.URL_REGEX = exports.NOISE_WA_HEADER = exports.KEY_BUNDLE_TYPE = exports.DICT_VERSION = exports.NOISE_MODE = exports.WA_DEFAULT_EPHEMERAL = exports.WA_ADV_HOSTED_DEVICE_SIG_PREFIX = exports.WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = exports.WA_ADV_DEVICE_SIG_PREFIX = exports.WA_ADV_ACCOUNT_SIG_PREFIX = exports.UNAUTHORIZED_CODES = exports.version = void 0;
7
7
  const WAProto_1 = require("../../WAProto");
8
8
  const libsignal_1 = require("../Signal/libsignal");
9
- const Utils_1 = require("../Utils");
9
+ const browser_utils_1 = require("../Utils/browser-utils");
10
10
  const logger_1 = __importDefault(require("../Utils/logger"));
11
- const baileys_version_json_1 = require("./baileys-version.json");
11
+ exports.version = [2, 3000, 1027934701];
12
12
  exports.UNAUTHORIZED_CODES = [401, 403, 419];
13
13
  exports.DEFAULT_ORIGIN = 'https://web.whatsapp.com';
14
+ exports.CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/';
15
+ exports.CALL_AUDIO_PREFIX = 'https://call.whatsapp.com/voice/';
14
16
  exports.DEF_CALLBACK_PREFIX = 'CB:';
15
17
  exports.DEF_TAG_PREFIX = 'TAG:';
16
18
  exports.PHONE_CONNECTION_CB = 'CB:Pong';
19
+ exports.WA_ADV_ACCOUNT_SIG_PREFIX = Buffer.from([6, 0]);
20
+ exports.WA_ADV_DEVICE_SIG_PREFIX = Buffer.from([6, 1]);
21
+ exports.WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5]);
22
+ exports.WA_ADV_HOSTED_DEVICE_SIG_PREFIX = Buffer.from([6, 6]);
17
23
  exports.WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60;
18
24
  exports.NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0';
19
25
  exports.DICT_VERSION = 3;
20
26
  exports.KEY_BUNDLE_TYPE = Buffer.from([5]);
21
- exports.NOISE_WA_HEADER = Buffer.from([87, 65, 6, exports.DICT_VERSION]); // last is "DICT_VERSION"
22
- /** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
27
+ exports.NOISE_WA_HEADER = Buffer.from([87, 65, 6, exports.DICT_VERSION]);
23
28
  exports.URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g;
24
29
  exports.WA_CERT_DETAILS = {
25
- SERIAL: 0,
30
+ SERIAL: 0
26
31
  };
27
32
  exports.PROCESSABLE_HISTORY_TYPES = [
28
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.INITIAL_BOOTSTRAP,
29
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.PUSH_NAME,
30
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.RECENT,
31
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.FULL,
32
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND,
33
+ WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,
34
+ WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME,
35
+ WAProto_1.proto.HistorySync.HistorySyncType.RECENT,
36
+ WAProto_1.proto.HistorySync.HistorySyncType.FULL,
37
+ WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND,
38
+ WAProto_1.proto.HistorySync.HistorySyncType.NON_BLOCKING_DATA,
39
+ WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_STATUS_V3,
33
40
  ];
34
41
  exports.DEFAULT_CONNECTION_CONFIG = {
35
- version: baileys_version_json_1.version,
36
- browser: Utils_1.Browsers.ubuntu('Chrome'),
42
+ version: exports.version,
43
+ browser: (0, browser_utils_1.Browsers)('Chrome'),
37
44
  waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
38
- connectTimeoutMs: 20000,
39
- keepAliveIntervalMs: 30000,
45
+ connectTimeoutMs: 20_000,
46
+ keepAliveIntervalMs: 30_000,
40
47
  logger: logger_1.default.child({ class: 'baileys' }),
41
- printQRInTerminal: false,
42
48
  emitOwnEvents: true,
43
- defaultQueryTimeoutMs: 60000,
49
+ defaultQueryTimeoutMs: 60_000,
44
50
  customUploadHosts: [],
45
51
  retryRequestDelayMs: 250,
46
52
  maxMsgRetryCount: 5,
47
53
  fireInitQueries: true,
48
54
  auth: undefined,
49
55
  markOnlineOnConnect: true,
50
- syncFullHistory: false,
56
+ syncFullHistory: true,
51
57
  patchMessageBeforeSending: msg => msg,
52
58
  shouldSyncHistoryMessage: () => true,
53
59
  shouldIgnoreJid: () => false,
54
60
  linkPreviewImageThumbnailWidth: 192,
55
61
  transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
56
62
  generateHighQualityLinkPreview: false,
63
+ enableAutoSessionRecreation: true,
64
+ enableRecentMessageCache: true,
57
65
  options: {},
58
66
  appStateMacVerification: {
59
67
  patch: false,
60
- snapshot: false,
68
+ snapshot: false
61
69
  },
62
70
  countryCode: 'US',
63
71
  getMessage: async () => undefined,
@@ -74,17 +82,18 @@ exports.MEDIA_PATH_MAP = {
74
82
  'product-catalog-image': '/product/image',
75
83
  'md-app-state': '',
76
84
  'md-msg-hist': '/mms/md-app-state',
85
+ 'biz-cover-photo': '/pps/biz-cover-photo'
77
86
  };
78
87
  exports.MEDIA_HKDF_KEY_MAPPING = {
79
- 'audio': 'Audio',
80
- 'document': 'Document',
81
- 'gif': 'Video',
82
- 'image': 'Image',
83
- 'ppic': '',
84
- 'product': 'Image',
85
- 'ptt': 'Audio',
86
- 'sticker': 'Image',
87
- 'video': 'Video',
88
+ audio: 'Audio',
89
+ document: 'Document',
90
+ gif: 'Video',
91
+ image: 'Image',
92
+ ppic: '',
93
+ product: 'Image',
94
+ ptt: 'Audio',
95
+ sticker: 'Image',
96
+ video: 'Video',
88
97
  'thumbnail-document': 'Document Thumbnail',
89
98
  'thumbnail-image': 'Image Thumbnail',
90
99
  'thumbnail-video': 'Video Thumbnail',
@@ -93,14 +102,17 @@ exports.MEDIA_HKDF_KEY_MAPPING = {
93
102
  'md-app-state': 'App State',
94
103
  'product-catalog-image': '',
95
104
  'payment-bg-image': 'Payment Background',
96
- 'ptv': 'Video'
105
+ ptv: 'Video',
106
+ 'biz-cover-photo': 'Image'
97
107
  };
98
108
  exports.MEDIA_KEYS = Object.keys(exports.MEDIA_PATH_MAP);
99
109
  exports.MIN_PREKEY_COUNT = 5;
100
- exports.INITIAL_PREKEY_COUNT = 30;
110
+ exports.INITIAL_PREKEY_COUNT = 812;
111
+ exports.UPLOAD_TIMEOUT = 30000;
112
+ exports.MIN_UPLOAD_INTERVAL = 5000;
101
113
  exports.DEFAULT_CACHE_TTLS = {
102
- SIGNAL_STORE: 5 * 60, // 5 minutes
103
- MSG_RETRY: 60 * 60, // 1 hour
104
- CALL_OFFER: 5 * 60, // 5 minutes
105
- USER_DEVICES: 5 * 60, // 5 minutes
106
- };
114
+ SIGNAL_STORE: 5 * 60,
115
+ MSG_RETRY: 60 * 60,
116
+ CALL_OFFER: 5 * 60,
117
+ USER_DEVICES: 5 * 60
118
+ };
@@ -0,0 +1,3 @@
1
+ {
2
+ "version": [2, 3000, 1027934701]
3
+ }
@@ -15,24 +15,31 @@ const process_message_1 = __importDefault(require("../Utils/process-message"));
15
15
  const WABinary_1 = require("../WABinary");
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
36
  const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
29
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
37
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
30
38
  useClones: false
31
39
  });
32
40
  if (!config.placeholderResendCache) {
33
41
  config.placeholderResendCache = placeholderResendCache;
34
42
  }
35
- /** helper function to fetch the given app state sync key */
36
43
  const getAppStateSyncKey = async (keyId) => {
37
44
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
38
45
  return key;
@@ -54,7 +61,6 @@ const makeChatsSocket = (config) => {
54
61
  }
55
62
  return privacySettings;
56
63
  };
57
- /** helper function to run a privacy IQ query */
58
64
  const privacyQuery = async (name, value) => {
59
65
  await query({
60
66
  tag: 'iq',
@@ -99,6 +105,9 @@ const makeChatsSocket = (config) => {
99
105
  const updateGroupsAddPrivacy = async (value) => {
100
106
  await privacyQuery('groupadd', value);
101
107
  };
108
+ const updateDisableLinkPreviewsPrivacy = async (isPreviewsDisabled) => {
109
+ return chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '');
110
+ };
102
111
  const updateDefaultDisappearingMode = async (duration) => {
103
112
  await query({
104
113
  tag: 'iq',
@@ -168,42 +177,6 @@ const makeChatsSocket = (config) => {
168
177
  return result.list;
169
178
  }
170
179
  };
171
- const checkStatusWA = async (numberOrJid) => {
172
- try {
173
- const jid = numberOrJid.includes('@s.whatsapp.net')
174
- ? numberOrJid
175
- : numberOrJid.replace(/[^0-9]/g, '') + '@s.whatsapp.net'
176
-
177
- const exists = await onWhatsApp(jid)
178
- if (!exists || !exists[0]?.exists) {
179
- return {
180
- jid,
181
- IsBanned: true,
182
- Statusbio: null,
183
- setAt: null
184
- }
185
- }
186
-
187
- const fetched = await fetchStatus(jid).catch(() => [])
188
- const status = fetched?.[0]?.status?.status || null
189
- const setAt = fetched?.[0]?.status?.setAt || null
190
-
191
- return {
192
- jid,
193
- IsBanned: false,
194
- Statusbio: status,
195
- setAt
196
- }
197
- } catch (e) {
198
- return {
199
- jid: numberOrJid,
200
- IsBanned: true,
201
- Statusbio: null,
202
- setAt: null,
203
- error: e.message
204
- }
205
- }
206
- }
207
180
  const fetchDisappearingDuration = async (...jids) => {
208
181
  const usyncQuery = new WAUSync_1.USyncQuery()
209
182
  .withDisappearingModeProtocol();
@@ -215,16 +188,15 @@ const checkStatusWA = async (numberOrJid) => {
215
188
  return result.list;
216
189
  }
217
190
  };
218
- /** update the profile picture for yourself or a group */
219
- const updateProfilePicture = async (jid, content) => {
191
+ const updateProfilePicture = async (jid, content, dimensions) => {
220
192
  let targetJid;
221
193
  if (!jid) {
222
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');
223
195
  }
224
196
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
225
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
197
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
226
198
  }
227
- const { img } = await (0, Utils_1.generateProfilePicture)(content);
199
+ const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions);
228
200
  await query({
229
201
  tag: 'iq',
230
202
  attrs: {
@@ -242,14 +214,13 @@ const checkStatusWA = async (numberOrJid) => {
242
214
  ]
243
215
  });
244
216
  };
245
- /** remove the profile picture for yourself or a group */
246
217
  const removeProfilePicture = async (jid) => {
247
218
  let targetJid;
248
219
  if (!jid) {
249
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');
250
221
  }
251
222
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
252
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
223
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
253
224
  }
254
225
  await query({
255
226
  tag: 'iq',
@@ -261,7 +232,6 @@ const checkStatusWA = async (numberOrJid) => {
261
232
  }
262
233
  });
263
234
  };
264
- /** update the profile status for yourself */
265
235
  const updateProfileStatus = async (status) => {
266
236
  await query({
267
237
  tag: 'iq',
@@ -388,18 +358,12 @@ const checkStatusWA = async (numberOrJid) => {
388
358
  };
389
359
  };
390
360
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
391
- // we use this to determine which events to fire
392
- // otherwise when we resync from scratch -- all notifications will fire
393
361
  const initialVersionMap = {};
394
362
  const globalMutationMap = {};
395
363
  await authState.keys.transaction(async () => {
396
364
  var _a;
397
365
  const collectionsToHandle = new Set(collections);
398
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
399
366
  const attemptsMap = {};
400
- // keep executing till all collections are done
401
- // sometimes a single patch request will not return all the patches (God knows why)
402
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
403
367
  while (collectionsToHandle.size) {
404
368
  const states = {};
405
369
  const nodes = [];
@@ -421,7 +385,6 @@ const checkStatusWA = async (numberOrJid) => {
421
385
  attrs: {
422
386
  name,
423
387
  version: state.version.toString(),
424
- // return snapshot if being synced from scratch
425
388
  'return_snapshot': (!state.version).toString()
426
389
  }
427
390
  });
@@ -441,7 +404,6 @@ const checkStatusWA = async (numberOrJid) => {
441
404
  }
442
405
  ]
443
406
  });
444
- // extract from binary node
445
407
  const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
446
408
  for (const key in decoded) {
447
409
  const name = key;
@@ -454,7 +416,6 @@ const checkStatusWA = async (numberOrJid) => {
454
416
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
455
417
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
456
418
  }
457
- // only process if there are syncd patches
458
419
  if (patches.length) {
459
420
  const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
460
421
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
@@ -465,22 +426,18 @@ const checkStatusWA = async (numberOrJid) => {
465
426
  if (hasMorePatches) {
466
427
  logger.info(`${name} has more patches...`);
467
428
  }
468
- else { // collection is done with sync
429
+ else {
469
430
  collectionsToHandle.delete(name);
470
431
  }
471
432
  }
472
433
  catch (error) {
473
- // if retry attempts overshoot
474
- // or key not found
475
434
  const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
476
435
  || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
477
436
  || error.name === 'TypeError';
478
437
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
479
438
  await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
480
- // increment number of retries
481
439
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
482
440
  if (isIrrecoverableError) {
483
- // stop retrying
484
441
  collectionsToHandle.delete(name);
485
442
  }
486
443
  }
@@ -492,28 +449,56 @@ const checkStatusWA = async (numberOrJid) => {
492
449
  onMutation(globalMutationMap[key]);
493
450
  }
494
451
  });
495
- /**
496
- * fetch the profile picture of a user/group
497
- * type = "preview" for a low res picture
498
- * type = "image for the high res picture"
499
- */
500
452
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
501
453
  var _a;
502
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) => {
503
486
  const result = await query({
504
- tag: 'iq',
487
+ tag: 'call',
505
488
  attrs: {
506
- target: jid,
507
- to: WABinary_1.S_WHATSAPP_NET,
508
- type: 'get',
509
- xmlns: 'w:profile:picture'
489
+ id: generateMessageTag(),
490
+ to: '@call'
510
491
  },
511
492
  content: [
512
- { 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
+ }
513
498
  ]
514
499
  }, timeoutMs);
515
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
516
- 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;
517
502
  };
518
503
  const sendPresenceUpdate = async (type, toJid) => {
519
504
  const me = authState.creds.me;
@@ -549,10 +534,6 @@ const checkStatusWA = async (numberOrJid) => {
549
534
  });
550
535
  }
551
536
  };
552
- /**
553
- * @param toJid the jid to subscribe to
554
- * @param tcToken token for subscription, use if present
555
- */
556
537
  const presenceSubscribe = (toJid, tcToken) => (sendNode({
557
538
  tag: 'presence',
558
539
  attrs: {
@@ -661,7 +642,6 @@ const checkStatusWA = async (numberOrJid) => {
661
642
  }
662
643
  }
663
644
  };
664
- /** sending non-abt props may fix QR scan fail if server expects */
665
645
  const fetchProps = async () => {
666
646
  var _a, _b, _c;
667
647
  const resultNode = await query({
@@ -681,7 +661,7 @@ const checkStatusWA = async (numberOrJid) => {
681
661
  const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
682
662
  let props = {};
683
663
  if (propsNode) {
684
- if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) { // on some clients, the hash is returning as undefined
664
+ if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) {
685
665
  authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
686
666
  ev.emit('creds.update', authState.creds);
687
667
  }
@@ -690,18 +670,10 @@ const checkStatusWA = async (numberOrJid) => {
690
670
  logger.debug('fetched props');
691
671
  return props;
692
672
  };
693
- /**
694
- * modify a chat -- mark unread, read etc.
695
- * lastMessages must be sorted in reverse chronologically
696
- * requires the last messages till the last message received; required for archive & unread
697
- */
698
673
  const chatModify = (mod, jid) => {
699
674
  const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
700
675
  return appPatch(patch);
701
676
  };
702
- /**
703
- * Star or Unstar a message
704
- */
705
677
  const star = (jid, messages, star) => {
706
678
  return chatModify({
707
679
  star: {
@@ -710,9 +682,15 @@ const checkStatusWA = async (numberOrJid) => {
710
682
  }
711
683
  }, jid);
712
684
  };
713
- /**
714
- * Adds label for the chats
715
- */
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
+ };
716
694
  const addChatLabel = (jid, labelId) => {
717
695
  return chatModify({
718
696
  addChatLabel: {
@@ -720,9 +698,6 @@ const checkStatusWA = async (numberOrJid) => {
720
698
  }
721
699
  }, jid);
722
700
  };
723
- /**
724
- * Removes label for the chat
725
- */
726
701
  const removeChatLabel = (jid, labelId) => {
727
702
  return chatModify({
728
703
  removeChatLabel: {
@@ -730,9 +705,6 @@ const checkStatusWA = async (numberOrJid) => {
730
705
  }
731
706
  }, jid);
732
707
  };
733
- /**
734
- * Adds label for the message
735
- */
736
708
  const addMessageLabel = (jid, messageId, labelId) => {
737
709
  return chatModify({
738
710
  addMessageLabel: {
@@ -741,9 +713,6 @@ const checkStatusWA = async (numberOrJid) => {
741
713
  }
742
714
  }, jid);
743
715
  };
744
- /**
745
- * Removes label for the message
746
- */
747
716
  const removeMessageLabel = (jid, messageId, labelId) => {
748
717
  return chatModify({
749
718
  removeMessageLabel: {
@@ -752,10 +721,6 @@ const checkStatusWA = async (numberOrJid) => {
752
721
  }
753
722
  }, jid);
754
723
  };
755
- /**
756
- * queries need to be fired on connection open
757
- * help ensure parity with WA Web
758
- * */
759
724
  const executeInitQueries = async () => {
760
725
  await Promise.all([
761
726
  fetchProps(),
@@ -772,7 +737,6 @@ const checkStatusWA = async (numberOrJid) => {
772
737
  if (!msg.key.fromMe) {
773
738
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
774
739
  }
775
- // update our pushname too
776
740
  if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
777
741
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
778
742
  }
@@ -782,6 +746,31 @@ const checkStatusWA = async (numberOrJid) => {
782
746
  ? (shouldSyncHistoryMessage(historyMsg)
783
747
  && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
784
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
+ };
785
774
  if (historyMsg && !authState.creds.myAppStateKeyId) {
786
775
  logger.warn('skipping app state sync, as myAppStateKeyId is not set');
787
776
  pendingAppStateSync = true;
@@ -795,6 +784,7 @@ const checkStatusWA = async (numberOrJid) => {
795
784
  }
796
785
  })(),
797
786
  (0, process_message_1.default)(msg, {
787
+ signalRepository,
798
788
  shouldProcessHistoryMsg,
799
789
  placeholderResendCache,
800
790
  ev,
@@ -810,18 +800,6 @@ const checkStatusWA = async (numberOrJid) => {
810
800
  await doAppStateSync();
811
801
  pendingAppStateSync = false;
812
802
  }
813
- async function doAppStateSync() {
814
- if (!authState.creds.accountSyncCounter) {
815
- logger.info('doing initial app state sync');
816
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
817
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
818
- ev.emit('creds.update', { accountSyncCounter });
819
- if (needToFlushWithAppStateSync) {
820
- logger.debug('flushing with app state sync');
821
- ev.flush();
822
- }
823
- }
824
- }
825
803
  });
826
804
  ws.on('CB:presence', handlePresenceUpdate);
827
805
  ws.on('CB:chatstate', handlePresenceUpdate);
@@ -840,7 +818,6 @@ const checkStatusWA = async (numberOrJid) => {
840
818
  }
841
819
  break;
842
820
  case 'groups':
843
- // handled in groups.ts
844
821
  break;
845
822
  default:
846
823
  logger.info({ node }, 'received unknown sync');
@@ -857,16 +834,43 @@ const checkStatusWA = async (numberOrJid) => {
857
834
  sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
858
835
  .catch(error => onUnexpectedError(error, 'presence update requests'));
859
836
  }
860
- if (receivedPendingNotifications && // if we don't have the app state key
861
- // we keep buffering events until we finally have
862
- // the key and can sync the messages
837
+ if (receivedPendingNotifications &&
863
838
  !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
864
839
  ev.buffer();
865
840
  needToFlushWithAppStateSync = true;
866
841
  }
842
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
843
+ return;
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);
867
870
  });
868
871
  return {
869
872
  ...sock,
873
+ createCallLink,
870
874
  getBotListV2,
871
875
  processingMutex,
872
876
  fetchPrivacySettings,
@@ -884,6 +888,7 @@ const checkStatusWA = async (numberOrJid) => {
884
888
  updateProfileStatus,
885
889
  updateProfileName,
886
890
  updateBlockStatus,
891
+ updateDisableLinkPreviewsPrivacy,
887
892
  updateCallPrivacy,
888
893
  updateMessagesPrivacy,
889
894
  updateLastSeenPrivacy,
@@ -897,12 +902,14 @@ const checkStatusWA = async (numberOrJid) => {
897
902
  resyncAppState,
898
903
  chatModify,
899
904
  cleanDirtyBits,
905
+ addOrEditContact,
906
+ removeContact,
907
+ addLabel,
900
908
  addChatLabel,
901
909
  removeChatLabel,
902
910
  addMessageLabel,
903
911
  removeMessageLabel,
904
- star,
905
- checkStatusWA
912
+ star
906
913
  };
907
914
  };
908
- exports.makeChatsSocket = makeChatsSocket;
915
+ exports.makeChatsSocket = makeChatsSocket;