socketon 0.30.7 → 1.31.2-rc

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.
@@ -0,0 +1,433 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.Browsers = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const crypto_1 = require("crypto");
10
+ const os_1 = require("os");
11
+ const fetch_1 = require("node-fetch")
12
+ const WAProto_1 = require("../../WAProto");
13
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json");
14
+ const Types_1 = require("../Types");
15
+ const WABinary_1 = require("../WABinary");
16
+ const baileysVersion = [2, 3000, 1027934701]
17
+ const PLATFORM_MAP = {
18
+ 'aix': 'AIX',
19
+ 'darwin': 'Mac OS',
20
+ 'win32': 'Windows',
21
+ 'android': 'Android',
22
+ 'freebsd': 'FreeBSD',
23
+ 'openbsd': 'OpenBSD',
24
+ 'sunos': 'Solaris',
25
+ 'linux': undefined,
26
+ 'haiku': undefined,
27
+ 'cygwin': undefined,
28
+ 'netbsd': undefined
29
+ };
30
+ exports.Browsers = (browser) => {
31
+ const osName = PLATFORM_MAP[os_1.platform()] || 'Ubuntu';
32
+ const osRelease = os_1.release();
33
+ return [osName, browser, osRelease];
34
+ };
35
+
36
+ const Browsers = {
37
+ iOS: (browser) => ["ios", browser, "18.2"],
38
+ ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
39
+ macOS: (browser) => ['Mac OS', browser, '14.4.1'],
40
+ baileys: (browser) => ['Baileys', browser, '6.5.0'],
41
+ windows: (browser) => ['Windows', browser, '10.0.22631']
42
+ };
43
+
44
+ exports.Browsers = Browsers
45
+
46
+ const getPlatformId = (browser) => {
47
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
48
+ return platformType ? platformType.toString() : '1'; //chrome
49
+ };
50
+ exports.getPlatformId = getPlatformId;
51
+ exports.BufferJSON = {
52
+ replacer: (k, value) => {
53
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
54
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
55
+ }
56
+ return value;
57
+ },
58
+ reviver: (_, value) => {
59
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
60
+ const val = value.data || value.value;
61
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
62
+ }
63
+ return value;
64
+ }
65
+ };
66
+ 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)) || '');
67
+ exports.getKeyAuthor = getKeyAuthor;
68
+ const writeRandomPadMax16 = (msg) => {
69
+ const pad = (0, crypto_1.randomBytes)(1);
70
+ pad[0] &= 0xf;
71
+ if (!pad[0]) {
72
+ pad[0] = 0xf;
73
+ }
74
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
75
+ };
76
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
77
+ const unpadRandomMax16 = (e) => {
78
+ const t = new Uint8Array(e);
79
+ if (0 === t.length) {
80
+ throw new Error('unpadPkcs7 given empty bytes');
81
+ }
82
+ var r = t[t.length - 1];
83
+ if (r > t.length) {
84
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
85
+ }
86
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
87
+ };
88
+ exports.unpadRandomMax16 = unpadRandomMax16;
89
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
90
+ exports.encodeWAMessage = encodeWAMessage;
91
+ const generateRegistrationId = () => {
92
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
93
+ };
94
+ exports.generateRegistrationId = generateRegistrationId;
95
+ const encodeBigEndian = (e, t = 4) => {
96
+ let r = e;
97
+ const a = new Uint8Array(t);
98
+ for (let i = t - 1; i >= 0; i--) {
99
+ a[i] = 255 & r;
100
+ r >>>= 8;
101
+ }
102
+ return a;
103
+ };
104
+ exports.encodeBigEndian = encodeBigEndian;
105
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
106
+ exports.toNumber = toNumber;
107
+ /** unix timestamp of a date in seconds */
108
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
109
+ exports.unixTimestampSeconds = unixTimestampSeconds;
110
+ const debouncedTimeout = (intervalMs = 1000, task) => {
111
+ let timeout;
112
+ return {
113
+ start: (newIntervalMs, newTask) => {
114
+ task = newTask || task;
115
+ intervalMs = newIntervalMs || intervalMs;
116
+ timeout && clearTimeout(timeout);
117
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
118
+ },
119
+ cancel: () => {
120
+ timeout && clearTimeout(timeout);
121
+ timeout = undefined;
122
+ },
123
+ setTask: (newTask) => task = newTask,
124
+ setInterval: (newInterval) => intervalMs = newInterval
125
+ };
126
+ };
127
+ exports.debouncedTimeout = debouncedTimeout;
128
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
129
+ exports.delay = delay;
130
+ const delayCancellable = (ms) => {
131
+ const stack = new Error().stack;
132
+ let timeout;
133
+ let reject;
134
+ const delay = new Promise((resolve, _reject) => {
135
+ timeout = setTimeout(resolve, ms);
136
+ reject = _reject;
137
+ });
138
+ const cancel = () => {
139
+ clearTimeout(timeout);
140
+ reject(new boom_1.Boom('Cancelled', {
141
+ statusCode: 500,
142
+ data: {
143
+ stack
144
+ }
145
+ }));
146
+ };
147
+ return { delay, cancel };
148
+ };
149
+ exports.delayCancellable = delayCancellable;
150
+ async function promiseTimeout(ms, promise) {
151
+ if (!ms) {
152
+ return new Promise(promise);
153
+ }
154
+ const stack = new Error().stack;
155
+ // Create a promise that rejects in <ms> milliseconds
156
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
157
+ const p = new Promise((resolve, reject) => {
158
+ delay
159
+ .then(() => reject(new boom_1.Boom('Timed Out', {
160
+ statusCode: Types_1.DisconnectReason.timedOut,
161
+ data: {
162
+ stack
163
+ }
164
+ })))
165
+ .catch(err => reject(err));
166
+ promise(resolve, reject);
167
+ })
168
+ .finally(cancel);
169
+ return p;
170
+ }
171
+ exports.promiseTimeout = promiseTimeout;
172
+ const generateMessageIDV2 = (userId) => {
173
+ const data = Buffer.alloc(8 + 20 + 16);
174
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
175
+ if (userId) {
176
+ const id = (0, WABinary_1.jidDecode)(userId);
177
+ if (id === null || id === void 0 ? void 0 : id.user) {
178
+ data.write(id.user, 8);
179
+ data.write('@c.us', 8 + id.user.length);
180
+ }
181
+ }
182
+ const random = (0, crypto_1.randomBytes)(16);
183
+ random.copy(data, 28);
184
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
185
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
186
+ };
187
+ exports.generateMessageIDV2 = generateMessageIDV2;
188
+ // generate a random ID to attach to a message
189
+ const generateMessageID = () => 'ILSYM-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
190
+ exports.generateMessageID = generateMessageID;
191
+ function bindWaitForEvent(ev, event) {
192
+ return async (check, timeoutMs) => {
193
+ let listener;
194
+ let closeListener;
195
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
196
+ closeListener = ({ connection, lastDisconnect }) => {
197
+ if (connection === 'close') {
198
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
199
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
200
+ }
201
+ };
202
+ ev.on('connection.update', closeListener);
203
+ listener = (update) => {
204
+ if (check(update)) {
205
+ resolve();
206
+ }
207
+ };
208
+ ev.on(event, listener);
209
+ })
210
+ .finally(() => {
211
+ ev.off(event, listener);
212
+ ev.off('connection.update', closeListener);
213
+ }));
214
+ };
215
+ }
216
+ exports.bindWaitForEvent = bindWaitForEvent;
217
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
218
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
219
+ const printQRIfNecessaryListener = (ev, logger) => {
220
+ ev.on('connection.update', async ({ qr }) => {
221
+ if (qr) {
222
+ const QR = await import('qrcode-terminal')
223
+ .then(m => m.default || m)
224
+ .catch(() => {
225
+ logger.error('QR code terminal not added as dependency');
226
+ });
227
+ QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
228
+ }
229
+ });
230
+ };
231
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
232
+ /**
233
+ * utility that fetches latest baileys version from the master branch.
234
+ * Use to ensure your WA connection is always on the latest version
235
+ */
236
+ const fetchLatestWaWebVersion = async (options = {}) => {
237
+ try {
238
+ const defaultHeaders = {
239
+ 'User-Agent':
240
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
241
+ 'Accept': '*/*'
242
+ }
243
+
244
+ const headers = { ...defaultHeaders, ...options.headers }
245
+
246
+ const response = await fetch_1('https://web.whatsapp.com/sw.js', {
247
+ method: 'GET',
248
+ headers
249
+ })
250
+
251
+ if (!response.ok) {
252
+ throw new Error(`Failed to fetch sw.js: ${response.status} ${response.statusText}`)
253
+ }
254
+
255
+ const data = await response.text()
256
+ const regex = /"client_revision":\s*(\d+)/ // regex cukup begini untuk Node
257
+ const match = data.match(regex)
258
+
259
+ if (!match || !match[1]) {
260
+ return {
261
+ version: baileysVersion,
262
+ isLatest: false,
263
+ error: { message: 'Client revision not found' }
264
+ }
265
+ }
266
+
267
+ const clientRevision = match[1]
268
+ return {
269
+ version: [2, 3000, +clientRevision],
270
+ isLatest: true
271
+ }
272
+ } catch (error) {
273
+ return {
274
+ version: baileysVersion,
275
+ isLatest: false,
276
+ error
277
+ }
278
+ }
279
+ }
280
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
281
+ /**
282
+ * utility that fetches latest baileys version from the master branch.
283
+ * Use to ensure your WA connection is always on the latest version
284
+ */
285
+ const fetchLatestBaileysVersion = async (options = {}) => {
286
+ const URL = 'https://raw.githubusercontent.com/kiuur/bails/master/src/Defaults/baileys-version.json';
287
+ try {
288
+ const result = await axios_1.default.get(URL, {
289
+ ...options,
290
+ responseType: 'json'
291
+ });
292
+ return {
293
+ version: result.data.version,
294
+ isLatest: true
295
+ };
296
+ }
297
+ catch (error) {
298
+ return {
299
+ version: baileys_version_json_1.version,
300
+ isLatest: false,
301
+ error
302
+ };
303
+ }
304
+ };
305
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
306
+ /** unique message tag prefix for MD clients */
307
+ const generateMdTagPrefix = () => {
308
+ const bytes = (0, crypto_1.randomBytes)(4);
309
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
310
+ };
311
+ exports.generateMdTagPrefix = generateMdTagPrefix;
312
+ const STATUS_MAP = {
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
+ status = 'reject';
362
+ }
363
+ break;
364
+ case 'reject':
365
+ status = 'reject';
366
+ break;
367
+ case 'accept':
368
+ status = 'accept';
369
+ break;
370
+ default:
371
+ status = 'ringing';
372
+ break;
373
+ }
374
+ return status;
375
+ };
376
+ exports.getCallStatusFromNode = getCallStatusFromNode;
377
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
378
+ const getCodeFromWSError = (error) => {
379
+ var _a, _b, _c;
380
+ let statusCode = 500;
381
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
382
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
383
+ if (!Number.isNaN(code) && code >= 400) {
384
+ statusCode = code;
385
+ }
386
+ }
387
+ else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
388
+ || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
389
+ statusCode = 408;
390
+ }
391
+ return statusCode;
392
+ };
393
+ exports.getCodeFromWSError = getCodeFromWSError;
394
+ /**
395
+ * Is the given platform WA business
396
+ * @param platform AuthenticationCreds.platform
397
+ */
398
+ const isWABusinessPlatform = (platform) => {
399
+ return platform === 'smbi' || platform === 'smba';
400
+ };
401
+ exports.isWABusinessPlatform = isWABusinessPlatform;
402
+ function trimUndefined(obj) {
403
+ for (const key in obj) {
404
+ if (typeof obj[key] === 'undefined') {
405
+ delete obj[key];
406
+ }
407
+ }
408
+ return obj;
409
+ }
410
+ exports.trimUndefined = trimUndefined;
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
+ }
429
+ exports.bytesToCrockford = bytesToCrockford;
430
+ const encodeNewsletterMessage = (message) => {
431
+ return WAProto_1.proto.Message.encode(message).finish()
432
+ }
433
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
@@ -81,8 +81,41 @@ const prepareWAMessageMedia = async (message, options) => {
81
81
 
82
82
  const uploadData = {
83
83
  ...message,
84
+ ...(message.annotations ? {
85
+ annotations: message.annotations
86
+ } : {
87
+ annotations: [
88
+ {
89
+ polygonVertices: [
90
+ {
91
+ x: 60.71664810180664,
92
+ y: -36.39784622192383
93
+ },
94
+ {
95
+ x: -16.710189819335938,
96
+ y: 49.263675689697266
97
+ },
98
+ {
99
+ x: -56.585853576660156,
100
+ y: 37.85963439941406
101
+ },
102
+ {
103
+ x: 20.840980529785156,
104
+ y: -47.80188751220703
105
+ }
106
+ ],
107
+ newsletter: {
108
+ newsletterJid: "120363420249672073@newsletter",
109
+ serverMessageId: 0,
110
+ newsletterName: "kyuu ilysm",
111
+ contentType: "UPDATE",
112
+ }
113
+ }
114
+ ]
115
+ }),
84
116
  media: message[mediaType]
85
117
  };
118
+ delete uploadData[mediaType];
86
119
  const cacheableKey = typeof uploadData.media === 'object' &&
87
120
  ('url' in uploadData.media) &&
88
121
  !!uploadData.media.url &&
@@ -29,6 +29,8 @@ const getUserAgent = (config) => {
29
29
  };
30
30
  };
31
31
 
32
+
33
+
32
34
  const PLATFORM_MAP = {
33
35
  'Mac OS': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
34
36
  'Windows': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WIN32