dibosockets 1.0.2 → 1.0.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 (40) hide show
  1. package/WAProto/WAProto.proto +4775 -5619
  2. package/lib/Defaults/baileys-version.json +3 -3
  3. package/lib/Defaults/index.js +106 -122
  4. package/lib/Socket/RHandler.js +530 -448
  5. package/lib/Socket/business.js +260 -266
  6. package/lib/Socket/chats.js +908 -1137
  7. package/lib/Socket/index.js +10 -43
  8. package/lib/Socket/messages-recv.js +1054 -1065
  9. package/lib/Socket/messages-send.js +903 -881
  10. package/lib/Socket/newsletter.js +303 -286
  11. package/lib/Socket/socket.js +654 -666
  12. package/lib/Store/make-in-memory-store.js +439 -439
  13. package/lib/Types/Newsletter.js +38 -18
  14. package/lib/Utils/baileys-event-stream.js +63 -63
  15. package/lib/Utils/event-buffer.js +518 -518
  16. package/lib/Utils/generics.js +428 -432
  17. package/lib/Utils/index.js +36 -36
  18. package/lib/Utils/messages-media.js +887 -926
  19. package/lib/Utils/messages.js +1030 -1105
  20. package/lib/Utils/process-message.js +385 -404
  21. package/lib/Utils/use-multi-file-auth-state.js +125 -122
  22. package/lib/Utils/validate-connection.js +173 -229
  23. package/lib/WABinary/jid-utils.js +83 -85
  24. package/lib/index.js +86 -74
  25. package/package.json +2 -2
  26. package/lib/Api/Internet/growagarden.js +0 -28
  27. package/lib/Api/creator.json +0 -13
  28. package/lib/Api/downloader/tiktokdownload.js +0 -132
  29. package/lib/Api/index.js +0 -38
  30. package/lib/Api/nsfw/loli.js +0 -79
  31. package/lib/Api/stalker/githubstalk.js +0 -46
  32. package/lib/Api/stalker/stalkroblox.js +0 -94
  33. package/lib/Api/stalker/tiktokstalk.js +0 -68
  34. package/lib/Api/tools/ssweb.js +0 -38
  35. package/lib/Defaults/phonenumber_mcc.json +0 -223
  36. package/lib/Socket/communities.js +0 -441
  37. package/lib/Utils/async-iterable.js +0 -41
  38. package/lib/Utils/browser-utils.js +0 -35
  39. package/lib/Utils/message-retry-manager.js +0 -128
  40. package/lib/Utils/resolveJid.js +0 -52
@@ -1,432 +1,428 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
40
- exports.promiseTimeout = promiseTimeout;
41
- exports.bindWaitForEvent = bindWaitForEvent;
42
- exports.trimUndefined = trimUndefined;
43
- exports.bytesToCrockford = bytesToCrockford;
44
- const boom_1 = require("@hapi/boom");
45
- const axios_1 = __importDefault(require("axios"));
46
- const crypto_1 = require("crypto");
47
- const os_1 = require("os");
48
- const WAProto_1 = require("../../WAProto");
49
- const baileys_version_json_1 = require("../Defaults/baileys-version.json");
50
- const Types_1 = require("../Types");
51
- const WABinary_1 = require("../WABinary");
52
- const COMPANION_PLATFORM_MAP = {
53
- 'Chrome': '49',
54
- 'Edge': '50',
55
- 'Firefox': '51',
56
- 'Opera': '53',
57
- 'Safari': '54'
58
- };
59
- const PLATFORM_MAP = {
60
- 'aix': 'AIX',
61
- 'darwin': 'Mac OS',
62
- 'win32': 'Windows',
63
- 'android': 'Android',
64
- 'freebsd': 'FreeBSD',
65
- 'openbsd': 'OpenBSD',
66
- 'sunos': 'Solaris'
67
- };
68
- exports.Browsers = {
69
- ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
70
- macOS: (browser) => ['Mac OS', browser, '14.4.1'],
71
- baileys: (browser) => ['Baileys', browser, '6.5.0'],
72
- windows: (browser) => ['Windows', browser, '10.0.22631'],
73
- /** The appropriate browser based on your OS & release */
74
- appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
75
- };
76
- const getPlatformId = (browser) => {
77
- const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
78
- return platformType ? platformType.toString() : '49'; //chrome
79
- };
80
- exports.getPlatformId = getPlatformId;
81
- exports.BufferJSON = {
82
- replacer: (k, value) => {
83
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
84
- return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
85
- }
86
- return value;
87
- },
88
- reviver: (_, value) => {
89
- if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
90
- const val = value.data || value.value;
91
- return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
92
- }
93
- return value;
94
- }
95
- };
96
- const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
97
- exports.getKeyAuthor = getKeyAuthor;
98
- const writeRandomPadMax16 = (msg) => {
99
- const pad = (0, crypto_1.randomBytes)(1);
100
- pad[0] &= 0xf;
101
- if (!pad[0]) {
102
- pad[0] = 0xf;
103
- }
104
- return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
105
- };
106
- exports.writeRandomPadMax16 = writeRandomPadMax16;
107
- const unpadRandomMax16 = (e) => {
108
- const t = new Uint8Array(e);
109
- if (0 === t.length) {
110
- throw new Error('unpadPkcs7 given empty bytes');
111
- }
112
- var r = t[t.length - 1];
113
- if (r > t.length) {
114
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
115
- }
116
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
117
- };
118
- exports.unpadRandomMax16 = unpadRandomMax16;
119
- const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
120
- exports.encodeWAMessage = encodeWAMessage;
121
- const encodeNewsletterMessage = (message) => (WAProto_1.proto.Message.encode(message).finish());
122
- exports.encodeNewsletterMessage = encodeNewsletterMessage;
123
- const generateRegistrationId = () => {
124
- return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
125
- };
126
- exports.generateRegistrationId = generateRegistrationId;
127
- const encodeBigEndian = (e, t = 4) => {
128
- let r = e;
129
- const a = new Uint8Array(t);
130
- for (let i = t - 1; i >= 0; i--) {
131
- a[i] = 255 & r;
132
- r >>>= 8;
133
- }
134
- return a;
135
- };
136
- exports.encodeBigEndian = encodeBigEndian;
137
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
138
- exports.toNumber = toNumber;
139
- /** unix timestamp of a date in seconds */
140
- const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
141
- exports.unixTimestampSeconds = unixTimestampSeconds;
142
- const debouncedTimeout = (intervalMs = 1000, task) => {
143
- let timeout;
144
- return {
145
- start: (newIntervalMs, newTask) => {
146
- task = newTask || task;
147
- intervalMs = newIntervalMs || intervalMs;
148
- timeout && clearTimeout(timeout);
149
- timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
150
- },
151
- cancel: () => {
152
- timeout && clearTimeout(timeout);
153
- timeout = undefined;
154
- },
155
- setTask: (newTask) => task = newTask,
156
- setInterval: (newInterval) => intervalMs = newInterval
157
- };
158
- };
159
- exports.debouncedTimeout = debouncedTimeout;
160
- const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
161
- exports.delay = delay;
162
- const delayCancellable = (ms) => {
163
- const stack = new Error().stack;
164
- let timeout;
165
- let reject;
166
- const delay = new Promise((resolve, _reject) => {
167
- timeout = setTimeout(resolve, ms);
168
- reject = _reject;
169
- });
170
- const cancel = () => {
171
- clearTimeout(timeout);
172
- reject(new boom_1.Boom('Cancelled', {
173
- statusCode: 500,
174
- data: {
175
- stack
176
- }
177
- }));
178
- };
179
- return { delay, cancel };
180
- };
181
- exports.delayCancellable = delayCancellable;
182
- async function promiseTimeout(ms, promise) {
183
- if (!ms) {
184
- return new Promise(promise);
185
- }
186
- const stack = new Error().stack;
187
- // Create a promise that rejects in <ms> milliseconds
188
- const { delay, cancel } = (0, exports.delayCancellable)(ms);
189
- const p = new Promise((resolve, reject) => {
190
- delay
191
- .then(() => reject(new boom_1.Boom('Timed Out', {
192
- statusCode: Types_1.DisconnectReason.timedOut,
193
- data: {
194
- stack
195
- }
196
- })))
197
- .catch(err => reject(err));
198
- promise(resolve, reject);
199
- })
200
- .finally(cancel);
201
- return p;
202
- }
203
- const generateMessageIDV2 = (userId) => {
204
- const data = Buffer.alloc(8 + 20 + 16);
205
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
206
- if (userId) {
207
- const id = (0, WABinary_1.jidDecode)(userId);
208
- if (id === null || id === void 0 ? void 0 : id.user) {
209
- data.write(id.user, 8);
210
- data.write('@c.us', 8 + id.user.length);
211
- }
212
- }
213
- const random = (0, crypto_1.randomBytes)(16);
214
- random.copy(data, 28);
215
- const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
216
- return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
217
- };
218
- exports.generateMessageIDV2 = generateMessageIDV2;
219
- // generate a random ID to attach to a message
220
- const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
221
- exports.generateMessageID = generateMessageID;
222
- function bindWaitForEvent(ev, event) {
223
- return async (check, timeoutMs) => {
224
- let listener;
225
- let closeListener;
226
- await (promiseTimeout(timeoutMs, (resolve, reject) => {
227
- closeListener = ({ connection, lastDisconnect }) => {
228
- if (connection === 'close') {
229
- reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
230
- || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
231
- }
232
- };
233
- ev.on('connection.update', closeListener);
234
- listener = async (update) => {
235
- if (await check(update)) {
236
- resolve();
237
- }
238
- };
239
- ev.on(event, listener);
240
- })
241
- .finally(() => {
242
- ev.off(event, listener);
243
- ev.off('connection.update', closeListener);
244
- }));
245
- };
246
- }
247
- const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
248
- exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
249
- const printQRIfNecessaryListener = (ev, logger) => {
250
- ev.on('connection.update', async ({ qr }) => {
251
- if (qr) {
252
- const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
253
- .catch(() => {
254
- logger.error('QR code terminal not added as dependency');
255
- });
256
- QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
257
- }
258
- });
259
- };
260
- exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
261
-
262
-
263
- const fetchLatestBaileysVersion = async (options = {}) => {
264
- return {
265
- version: baileys_version_json_1.version,
266
- isLatest: true
267
- };
268
- };
269
- exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
270
-
271
- /**
272
- * A utility that fetches the latest web version of whatsapp.
273
- * Use to ensure your WA connection is always on the latest version
274
- */
275
- const fetchLatestWaWebVersion = async (options) => {
276
- try {
277
- const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
278
- ...options,
279
- responseType: 'json'
280
- });
281
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
282
- const match = data.match(regex);
283
- if (!(match === null || match === void 0 ? void 0 : match[1])) {
284
- return {
285
- version: baileys_version_json_1.version,
286
- isLatest: false,
287
- error: {
288
- message: 'Could not find client revision in the fetched content'
289
- }
290
- };
291
- }
292
- const clientRevision = match[1];
293
- return {
294
- version: [2, 3000, +clientRevision],
295
- isLatest: true
296
- };
297
- }
298
- catch (error) {
299
- return {
300
- version: baileys_version_json_1.version,
301
- isLatest: false,
302
- error
303
- };
304
- }
305
- };
306
- exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
307
- /** unique message tag prefix for MD clients */
308
- const generateMdTagPrefix = () => {
309
- const bytes = (0, crypto_1.randomBytes)(4);
310
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
311
- };
312
- exports.generateMdTagPrefix = generateMdTagPrefix;
313
- const STATUS_MAP = {
314
- 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
315
- 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
316
- 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
317
- 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
318
- };
319
- /**
320
- * Given a type of receipt, returns what the new status of the message should be
321
- * @param type type from receipt
322
- */
323
- const getStatusFromReceiptType = (type) => {
324
- const status = STATUS_MAP[type];
325
- if (typeof type === 'undefined') {
326
- return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
327
- }
328
- return status;
329
- };
330
- exports.getStatusFromReceiptType = getStatusFromReceiptType;
331
- const CODE_MAP = {
332
- conflict: Types_1.DisconnectReason.connectionReplaced
333
- };
334
- /**
335
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
336
- * @param reason the string reason given, eg. "conflict"
337
- */
338
- const getErrorCodeFromStreamError = (node) => {
339
- const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
340
- let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
341
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
342
- if (statusCode === Types_1.DisconnectReason.restartRequired) {
343
- reason = 'restart required';
344
- }
345
- return {
346
- reason,
347
- statusCode
348
- };
349
- };
350
- exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
351
- const getCallStatusFromNode = ({ tag, attrs }) => {
352
- let status;
353
- switch (tag) {
354
- case 'offer':
355
- case 'offer_notice':
356
- status = 'offer';
357
- break;
358
- case 'terminate':
359
- if (attrs.reason === 'timeout') {
360
- status = 'timeout';
361
- }
362
- else {
363
- // fired when accepted/rejected/timeout/caller hangs up
364
- status = 'terminate';
365
- }
366
- break;
367
- case 'reject':
368
- status = 'reject';
369
- break;
370
- case 'accept':
371
- status = 'accept';
372
- break;
373
- default:
374
- status = 'ringing';
375
- break;
376
- }
377
- return status;
378
- };
379
- exports.getCallStatusFromNode = getCallStatusFromNode;
380
- const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
381
- const getCodeFromWSError = (error) => {
382
- var _a, _b, _c;
383
- let statusCode = 500;
384
- if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
385
- const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
386
- if (!Number.isNaN(code) && code >= 400) {
387
- statusCode = code;
388
- }
389
- }
390
- else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
391
- || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
392
- statusCode = 408;
393
- }
394
- return statusCode;
395
- };
396
- exports.getCodeFromWSError = getCodeFromWSError;
397
- /**
398
- * Is the given platform WA business
399
- * @param platform AuthenticationCreds.platform
400
- */
401
- const isWABusinessPlatform = (platform) => {
402
- return platform === 'smbi' || platform === 'smba';
403
- };
404
- exports.isWABusinessPlatform = isWABusinessPlatform;
405
- function trimUndefined(obj) {
406
- for (const key in obj) {
407
- if (typeof obj[key] === 'undefined') {
408
- delete obj[key];
409
- }
410
- }
411
- return obj;
412
- }
413
- const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
414
- function bytesToCrockford(buffer) {
415
- let value = 0;
416
- let bitCount = 0;
417
- const crockford = [];
418
- for (let i = 0; i < buffer.length; i++) {
419
- value = (value << 8) | (buffer[i] & 0xff);
420
- bitCount += 8;
421
- while (bitCount >= 5) {
422
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
423
- bitCount -= 5;
424
- }
425
- }
426
- if (bitCount > 0) {
427
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
428
- }
429
- return crockford.join('');
430
- }
431
- exports.trimUndefined = trimUndefined;
432
- exports.bytesToCrockford = bytesToCrockford;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
40
+ exports.promiseTimeout = promiseTimeout;
41
+ exports.bindWaitForEvent = bindWaitForEvent;
42
+ exports.trimUndefined = trimUndefined;
43
+ exports.bytesToCrockford = bytesToCrockford;
44
+ const boom_1 = require("@hapi/boom");
45
+ const axios_1 = __importDefault(require("axios"));
46
+ const crypto_1 = require("crypto");
47
+ const os_1 = require("os");
48
+ const WAProto_1 = require("../../WAProto");
49
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json");
50
+ const Types_1 = require("../Types");
51
+ const WABinary_1 = require("../WABinary");
52
+ const COMPANION_PLATFORM_MAP = {
53
+ 'Chrome': '49',
54
+ 'Edge': '50',
55
+ 'Firefox': '51',
56
+ 'Opera': '53',
57
+ 'Safari': '54'
58
+ };
59
+ const PLATFORM_MAP = {
60
+ 'aix': 'AIX',
61
+ 'darwin': 'Mac OS',
62
+ 'win32': 'Windows',
63
+ 'android': 'Android',
64
+ 'freebsd': 'FreeBSD',
65
+ 'openbsd': 'OpenBSD',
66
+ 'sunos': 'Solaris'
67
+ };
68
+ exports.Browsers = {
69
+ ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
70
+ macOS: (browser) => ['Mac OS', browser, '14.4.1'],
71
+ baileys: (browser) => ['Baileys', browser, '6.5.0'],
72
+ windows: (browser) => ['Windows', browser, '10.0.22631'],
73
+ /** The appropriate browser based on your OS & release */
74
+ appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
75
+ };
76
+ const getPlatformId = (browser) => {
77
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
78
+ return platformType ? platformType.toString() : '49'; //chrome
79
+ };
80
+ exports.getPlatformId = getPlatformId;
81
+ exports.BufferJSON = {
82
+ replacer: (k, value) => {
83
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
84
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
85
+ }
86
+ return value;
87
+ },
88
+ reviver: (_, value) => {
89
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
90
+ const val = value.data || value.value;
91
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
92
+ }
93
+ return value;
94
+ }
95
+ };
96
+ const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
97
+ exports.getKeyAuthor = getKeyAuthor;
98
+ const writeRandomPadMax16 = (msg) => {
99
+ const pad = (0, crypto_1.randomBytes)(1);
100
+ pad[0] &= 0xf;
101
+ if (!pad[0]) {
102
+ pad[0] = 0xf;
103
+ }
104
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
105
+ };
106
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
107
+ const unpadRandomMax16 = (e) => {
108
+ const t = new Uint8Array(e);
109
+ if (0 === t.length) {
110
+ throw new Error('unpadPkcs7 given empty bytes');
111
+ }
112
+ var r = t[t.length - 1];
113
+ if (r > t.length) {
114
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
115
+ }
116
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
117
+ };
118
+ exports.unpadRandomMax16 = unpadRandomMax16;
119
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
120
+ exports.encodeWAMessage = encodeWAMessage;
121
+ const encodeNewsletterMessage = (message) => (WAProto_1.proto.Message.encode(message).finish());
122
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
123
+ const generateRegistrationId = () => {
124
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
125
+ };
126
+ exports.generateRegistrationId = generateRegistrationId;
127
+ const encodeBigEndian = (e, t = 4) => {
128
+ let r = e;
129
+ const a = new Uint8Array(t);
130
+ for (let i = t - 1; i >= 0; i--) {
131
+ a[i] = 255 & r;
132
+ r >>>= 8;
133
+ }
134
+ return a;
135
+ };
136
+ exports.encodeBigEndian = encodeBigEndian;
137
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
138
+ exports.toNumber = toNumber;
139
+ /** unix timestamp of a date in seconds */
140
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
141
+ exports.unixTimestampSeconds = unixTimestampSeconds;
142
+ const debouncedTimeout = (intervalMs = 1000, task) => {
143
+ let timeout;
144
+ return {
145
+ start: (newIntervalMs, newTask) => {
146
+ task = newTask || task;
147
+ intervalMs = newIntervalMs || intervalMs;
148
+ timeout && clearTimeout(timeout);
149
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
150
+ },
151
+ cancel: () => {
152
+ timeout && clearTimeout(timeout);
153
+ timeout = undefined;
154
+ },
155
+ setTask: (newTask) => task = newTask,
156
+ setInterval: (newInterval) => intervalMs = newInterval
157
+ };
158
+ };
159
+ exports.debouncedTimeout = debouncedTimeout;
160
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
161
+ exports.delay = delay;
162
+ const delayCancellable = (ms) => {
163
+ const stack = new Error().stack;
164
+ let timeout;
165
+ let reject;
166
+ const delay = new Promise((resolve, _reject) => {
167
+ timeout = setTimeout(resolve, ms);
168
+ reject = _reject;
169
+ });
170
+ const cancel = () => {
171
+ clearTimeout(timeout);
172
+ reject(new boom_1.Boom('Cancelled', {
173
+ statusCode: 500,
174
+ data: {
175
+ stack
176
+ }
177
+ }));
178
+ };
179
+ return { delay, cancel };
180
+ };
181
+ exports.delayCancellable = delayCancellable;
182
+ async function promiseTimeout(ms, promise) {
183
+ if (!ms) {
184
+ return new Promise(promise);
185
+ }
186
+ const stack = new Error().stack;
187
+ // Create a promise that rejects in <ms> milliseconds
188
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
189
+ const p = new Promise((resolve, reject) => {
190
+ delay
191
+ .then(() => reject(new boom_1.Boom('Timed Out', {
192
+ statusCode: Types_1.DisconnectReason.timedOut,
193
+ data: {
194
+ stack
195
+ }
196
+ })))
197
+ .catch(err => reject(err));
198
+ promise(resolve, reject);
199
+ })
200
+ .finally(cancel);
201
+ return p;
202
+ }
203
+ const generateMessageIDV2 = (userId) => {
204
+ const data = Buffer.alloc(8 + 20 + 16);
205
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
206
+ if (userId) {
207
+ const id = (0, WABinary_1.jidDecode)(userId);
208
+ if (id === null || id === void 0 ? void 0 : id.user) {
209
+ data.write(id.user, 8);
210
+ data.write('@c.us', 8 + id.user.length);
211
+ }
212
+ }
213
+ const random = (0, crypto_1.randomBytes)(16);
214
+ random.copy(data, 28);
215
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
216
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
217
+ };
218
+ exports.generateMessageIDV2 = generateMessageIDV2;
219
+ // generate a random ID to attach to a message
220
+ const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
221
+ exports.generateMessageID = generateMessageID;
222
+ function bindWaitForEvent(ev, event) {
223
+ return async (check, timeoutMs) => {
224
+ let listener;
225
+ let closeListener;
226
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
227
+ closeListener = ({ connection, lastDisconnect }) => {
228
+ if (connection === 'close') {
229
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
230
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
231
+ }
232
+ };
233
+ ev.on('connection.update', closeListener);
234
+ listener = async (update) => {
235
+ if (await check(update)) {
236
+ resolve();
237
+ }
238
+ };
239
+ ev.on(event, listener);
240
+ })
241
+ .finally(() => {
242
+ ev.off(event, listener);
243
+ ev.off('connection.update', closeListener);
244
+ }));
245
+ };
246
+ }
247
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
248
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
249
+ const printQRIfNecessaryListener = (ev, logger) => {
250
+ ev.on('connection.update', async ({ qr }) => {
251
+ if (qr) {
252
+ const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
253
+ .catch(() => {
254
+ logger.error('QR code terminal not added as dependency');
255
+ });
256
+ QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
257
+ }
258
+ });
259
+ };
260
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
261
+ const fetchLatestBaileysVersion = async (options = {}) => {
262
+ return {
263
+ version: baileys_version_json_1.version,
264
+ isLatest: true
265
+ };
266
+ };
267
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
268
+
269
+ /**
270
+ * A utility that fetches the latest web version of whatsapp.
271
+ * Use to ensure your WA connection is always on the latest version
272
+ */
273
+ const fetchLatestWaWebVersion = async (options) => {
274
+ try {
275
+ const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
276
+ ...options,
277
+ responseType: 'json'
278
+ });
279
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
280
+ const match = data.match(regex);
281
+ if (!(match === null || match === void 0 ? void 0 : match[1])) {
282
+ return {
283
+ version: baileys_version_json_1.version,
284
+ isLatest: false,
285
+ error: {
286
+ message: 'Could not find client revision in the fetched content'
287
+ }
288
+ };
289
+ }
290
+ const clientRevision = match[1];
291
+ return {
292
+ version: [2, 3000, +clientRevision],
293
+ isLatest: true
294
+ };
295
+ }
296
+ catch (error) {
297
+ return {
298
+ version: baileys_version_json_1.version,
299
+ isLatest: false,
300
+ error
301
+ };
302
+ }
303
+ };
304
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
305
+ /** unique message tag prefix for MD clients */
306
+ const generateMdTagPrefix = () => {
307
+ const bytes = (0, crypto_1.randomBytes)(4);
308
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
309
+ };
310
+ exports.generateMdTagPrefix = generateMdTagPrefix;
311
+ const STATUS_MAP = {
312
+ 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
313
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
314
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
315
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
316
+ };
317
+ /**
318
+ * Given a type of receipt, returns what the new status of the message should be
319
+ * @param type type from receipt
320
+ */
321
+ const getStatusFromReceiptType = (type) => {
322
+ const status = STATUS_MAP[type];
323
+ if (typeof type === 'undefined') {
324
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
325
+ }
326
+ return status;
327
+ };
328
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
329
+ const CODE_MAP = {
330
+ conflict: Types_1.DisconnectReason.connectionReplaced
331
+ };
332
+ /**
333
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
334
+ * @param reason the string reason given, eg. "conflict"
335
+ */
336
+ const getErrorCodeFromStreamError = (node) => {
337
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
338
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
339
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
340
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
341
+ reason = 'restart required';
342
+ }
343
+ return {
344
+ reason,
345
+ statusCode
346
+ };
347
+ };
348
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
349
+ const getCallStatusFromNode = ({ tag, attrs }) => {
350
+ let status;
351
+ switch (tag) {
352
+ case 'offer':
353
+ case 'offer_notice':
354
+ status = 'offer';
355
+ break;
356
+ case 'terminate':
357
+ if (attrs.reason === 'timeout') {
358
+ status = 'timeout';
359
+ }
360
+ else {
361
+ // fired when accepted/rejected/timeout/caller hangs up
362
+ status = 'terminate';
363
+ }
364
+ break;
365
+ case 'reject':
366
+ status = 'reject';
367
+ break;
368
+ case 'accept':
369
+ status = 'accept';
370
+ break;
371
+ default:
372
+ status = 'ringing';
373
+ break;
374
+ }
375
+ return status;
376
+ };
377
+ exports.getCallStatusFromNode = getCallStatusFromNode;
378
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
379
+ const getCodeFromWSError = (error) => {
380
+ var _a, _b, _c;
381
+ let statusCode = 500;
382
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
383
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
384
+ if (!Number.isNaN(code) && code >= 400) {
385
+ statusCode = code;
386
+ }
387
+ }
388
+ else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
389
+ || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
390
+ statusCode = 408;
391
+ }
392
+ return statusCode;
393
+ };
394
+ exports.getCodeFromWSError = getCodeFromWSError;
395
+ /**
396
+ * Is the given platform WA business
397
+ * @param platform AuthenticationCreds.platform
398
+ */
399
+ const isWABusinessPlatform = (platform) => {
400
+ return platform === 'smbi' || platform === 'smba';
401
+ };
402
+ exports.isWABusinessPlatform = isWABusinessPlatform;
403
+ function trimUndefined(obj) {
404
+ for (const key in obj) {
405
+ if (typeof obj[key] === 'undefined') {
406
+ delete obj[key];
407
+ }
408
+ }
409
+ return obj;
410
+ }
411
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
412
+ function bytesToCrockford(buffer) {
413
+ let value = 0;
414
+ let bitCount = 0;
415
+ const crockford = [];
416
+ for (let i = 0; i < buffer.length; i++) {
417
+ value = (value << 8) | (buffer[i] & 0xff);
418
+ bitCount += 8;
419
+ while (bitCount >= 5) {
420
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
421
+ bitCount -= 5;
422
+ }
423
+ }
424
+ if (bitCount > 0) {
425
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
426
+ }
427
+ return crockford.join('');
428
+ }