-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
generics.ts
415 lines (360 loc) · 10.7 KB
/
generics.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import { Boom } from '@hapi/boom'
import axios, { AxiosRequestConfig } from 'axios'
import { randomBytes } from 'crypto'
import { platform, release } from 'os'
import { Logger } from 'pino'
import { proto } from '../../WAProto'
import { version as baileysVersion } from '../Defaults/baileys-version.json'
import { BaileysEventEmitter, BaileysEventMap, DisconnectReason, WACallUpdateType, WAVersion } from '../Types'
import { BinaryNode, getAllBinaryNodeChildren } from '../WABinary'
const PLATFORM_MAP = {
'aix': 'AIX',
'darwin': 'Mac OS',
'win32': 'Windows',
'android': 'Android'
}
export const Browsers = {
ubuntu: browser => ['Ubuntu', browser, '20.0.04'] as [string, string, string],
macOS: browser => ['Mac OS', browser, '10.15.7'] as [string, string, string],
baileys: browser => ['Baileys', browser, '4.0.0'] as [string, string, string],
windows: browser => ['Windows', browser, '10.0.22621'] as [string, string, string],
/** The appropriate browser based on your OS & release */
appropriate: browser => [ PLATFORM_MAP[platform()] || 'Ubuntu', browser, release() ] as [string, string, string]
}
export const BufferJSON = {
replacer: (k, value: any) => {
if(Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
}
return value
},
reviver: (_, value: any) => {
if(typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
const val = value.data || value.value
return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
}
return value
}
}
export const getKeyAuthor = (
key: proto.IMessageKey | undefined | null,
meId: string = 'me'
) => (
(key?.fromMe ? meId : key?.participant || key?.remoteJid) || ''
)
export const writeRandomPadMax16 = (msg: Uint8Array) => {
const pad = randomBytes(1)
pad[0] &= 0xf
if(!pad[0]) {
pad[0] = 0xf
}
return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])])
}
export const unpadRandomMax16 = (e: Uint8Array | Buffer) => {
const t = new Uint8Array(e)
if(0 === t.length) {
throw new Error('unpadPkcs7 given empty bytes')
}
var r = t[t.length - 1]
if(r > t.length) {
throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
}
return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
}
export const encodeWAMessage = (message: proto.IMessage) => (
writeRandomPadMax16(
proto.Message.encode(message).finish()
)
)
export const generateRegistrationId = (): number => {
return Uint16Array.from(randomBytes(2))[0] & 16383
}
export const encodeBigEndian = (e: number, t = 4) => {
let r = e
const a = new Uint8Array(t)
for(let i = t - 1; i >= 0; i--) {
a[i] = 255 & r
r >>>= 8
}
return a
}
export const toNumber = (t: Long | number | null | undefined): number => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : (t as any).low) : t)
/** unix timestamp of a date in seconds */
export const unixTimestampSeconds = (date: Date = new Date()) => Math.floor(date.getTime() / 1000)
export type DebouncedTimeout = ReturnType<typeof debouncedTimeout>
export const debouncedTimeout = (intervalMs: number = 1000, task?: () => void) => {
let timeout: NodeJS.Timeout | undefined
return {
start: (newIntervalMs?: number, newTask?: () => void) => {
task = newTask || task
intervalMs = newIntervalMs || intervalMs
timeout && clearTimeout(timeout)
timeout = setTimeout(() => task?.(), intervalMs)
},
cancel: () => {
timeout && clearTimeout(timeout)
timeout = undefined
},
setTask: (newTask: () => void) => task = newTask,
setInterval: (newInterval: number) => intervalMs = newInterval
}
}
export const delay = (ms: number) => delayCancellable (ms).delay
export const delayCancellable = (ms: number) => {
const stack = new Error().stack
let timeout: NodeJS.Timeout
let reject: (error) => void
const delay: Promise<void> = new Promise((resolve, _reject) => {
timeout = setTimeout(resolve, ms)
reject = _reject
})
const cancel = () => {
clearTimeout (timeout)
reject(
new Boom('Cancelled', {
statusCode: 500,
data: {
stack
}
})
)
}
return { delay, cancel }
}
export async function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error) => void) => void) {
if(!ms) {
return new Promise(promise)
}
const stack = new Error().stack
// Create a promise that rejects in <ms> milliseconds
const { delay, cancel } = delayCancellable (ms)
const p = new Promise((resolve, reject) => {
delay
.then(() => reject(
new Boom('Timed Out', {
statusCode: DisconnectReason.timedOut,
data: {
stack
}
})
))
.catch (err => reject(err))
promise (resolve, reject)
})
.finally (cancel)
return p as Promise<T>
}
// generate a random ID to attach to a message
export const generateMessageID = () => 'BAE5' + randomBytes(6).toString('hex').toUpperCase()
export function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T) {
return async(check: (u: BaileysEventMap[T]) => boolean | undefined, timeoutMs?: number) => {
let listener: (item: BaileysEventMap[T]) => void
let closeListener: any
await (
promiseTimeout<void>(
timeoutMs,
(resolve, reject) => {
closeListener = ({ connection, lastDisconnect }) => {
if(connection === 'close') {
reject(
lastDisconnect?.error
|| new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
)
}
}
ev.on('connection.update', closeListener)
listener = (update) => {
if(check(update)) {
resolve()
}
}
ev.on(event, listener)
}
)
.finally(() => {
ev.off(event, listener)
ev.off('connection.update', closeListener)
})
)
}
}
export const bindWaitForConnectionUpdate = (ev: BaileysEventEmitter) => bindWaitForEvent(ev, 'connection.update')
export const printQRIfNecessaryListener = (ev: BaileysEventEmitter, logger: Logger) => {
ev.on('connection.update', async({ qr }) => {
if(qr) {
const QR = await import('qrcode-terminal')
.then(m => m.default || m)
.catch(() => {
logger.error('QR code terminal not added as dependency')
})
QR?.generate(qr, { small: true })
}
})
}
/**
* utility that fetches latest baileys version from the master branch.
* Use to ensure your WA connection is always on the latest version
*/
export const fetchLatestBaileysVersion = async(options: AxiosRequestConfig<any> = { }) => {
const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json'
try {
const result = await axios.get<{ version: WAVersion }>(
URL,
{
...options,
responseType: 'json'
}
)
return {
version: result.data.version,
isLatest: true
}
} catch(error) {
return {
version: baileysVersion as WAVersion,
isLatest: false,
error
}
}
}
/**
* A utility that fetches the latest web version of whatsapp.
* Use to ensure your WA connection is always on the latest version
*/
export const fetchLatestWaWebVersion = async(options: AxiosRequestConfig<any>) => {
try {
const result = await axios.get(
'https://web.whatsapp.com/check-update?version=1&platform=web',
{
...options,
responseType: 'json'
}
)
const version = result.data.currentVersion.split('.')
return {
version: [+version[0], +version[1], +version[2]] as WAVersion,
isLatest: true
}
} catch(error) {
return {
version: baileysVersion as WAVersion,
isLatest: false,
error
}
}
}
/** unique message tag prefix for MD clients */
export const generateMdTagPrefix = () => {
const bytes = randomBytes(4)
return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
}
const STATUS_MAP: { [_: string]: proto.WebMessageInfo.Status } = {
'played': proto.WebMessageInfo.Status.PLAYED,
'read': proto.WebMessageInfo.Status.READ,
'read-self': proto.WebMessageInfo.Status.READ
}
/**
* Given a type of receipt, returns what the new status of the message should be
* @param type type from receipt
*/
export const getStatusFromReceiptType = (type: string | undefined) => {
const status = STATUS_MAP[type!]
if(typeof type === 'undefined') {
return proto.WebMessageInfo.Status.DELIVERY_ACK
}
return status
}
const CODE_MAP: { [_: string]: DisconnectReason } = {
conflict: DisconnectReason.connectionReplaced
}
/**
* Stream errors generally provide a reason, map that to a baileys DisconnectReason
* @param reason the string reason given, eg. "conflict"
*/
export const getErrorCodeFromStreamError = (node: BinaryNode) => {
const [reasonNode] = getAllBinaryNodeChildren(node)
let reason = reasonNode?.tag || 'unknown'
const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession)
if(statusCode === DisconnectReason.restartRequired) {
reason = 'restart required'
}
return {
reason,
statusCode
}
}
export const getCallStatusFromNode = ({ tag, attrs }: BinaryNode) => {
let status: WACallUpdateType
switch (tag) {
case 'offer':
case 'offer_notice':
status = 'offer'
break
case 'terminate':
if(attrs.reason === 'timeout') {
status = 'timeout'
} else {
status = 'reject'
}
break
case 'reject':
status = 'reject'
break
case 'accept':
status = 'accept'
break
default:
status = 'ringing'
break
}
return status
}
const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
export const getCodeFromWSError = (error: Error) => {
let statusCode = 500
if(error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length)
if(!Number.isNaN(code) && code >= 400) {
statusCode = code
}
} else if(
(error as any)?.code?.startsWith('E')
|| error?.message?.includes('timed out')
) { // handle ETIMEOUT, ENOTFOUND etc
statusCode = 408
}
return statusCode
}
/**
* Is the given platform WA business
* @param platform AuthenticationCreds.platform
*/
export const isWABusinessPlatform = (platform: string) => {
return platform === 'smbi' || platform === 'smba'
}
export function trimUndefined(obj: any) {
for(const key in obj) {
if(typeof obj[key] === 'undefined') {
delete obj[key]
}
}
return obj
}
const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ'
export function bytesToCrockford(buffer: Buffer): string {
let value = 0
let bitCount = 0
const crockford: string[] = []
for(let i = 0; i < buffer.length; i++) {
value = (value << 8) | (buffer[i] & 0xff)
bitCount += 8
while(bitCount >= 5) {
crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
bitCount -= 5
}
}
if(bitCount > 0) {
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
}
return crockford.join('')
}