lint: stricter linting rules

This commit is contained in:
Adhiraj Singh
2022-03-01 16:32:14 +05:30
parent c00c3da313
commit de7d1002a9
39 changed files with 534 additions and 526 deletions

View File

@@ -49,7 +49,7 @@ const makeBusinessSocket = (config: LegacySocketConfig) => {
mapProductCreate(product)
]
})
return mapProduct(result.data.product)
}
@@ -80,7 +80,7 @@ const makeBusinessSocket = (config: LegacySocketConfig) => {
{
product_id: productId,
...mapProductCreate(
{ ...update, originCountryCode: undefined },
{ ...update, originCountryCode: undefined },
false
)
}
@@ -89,7 +89,7 @@ const makeBusinessSocket = (config: LegacySocketConfig) => {
return mapProduct(result.data.product)
}
// maps product create to send to WA
const mapProductCreate = (product: ProductCreate, mapCompliance = true) => {
const result: any = {
@@ -107,10 +107,10 @@ const makeBusinessSocket = (config: LegacySocketConfig) => {
}
if(mapCompliance) {
Object.assign(result, {
compliance_category: product.originCountryCode
? undefined :
compliance_category: product.originCountryCode
? undefined :
'COUNTRY_ORIGIN_EXEMPT',
compliance_info: product.originCountryCode
compliance_info: product.originCountryCode
? { country_code_origin: product.originCountryCode }
: undefined
})

View File

@@ -6,12 +6,12 @@ import makeAuthSocket from './auth'
const makeChatsSocket = (config: LegacySocketConfig) => {
const { logger } = config
const sock = makeAuthSocket(config)
const {
ev,
const {
ev,
ws: socketEvents,
currentEpoch,
setQuery,
query,
query,
sendNode,
state
} = sock
@@ -29,9 +29,9 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
)
const profilePictureUrl = async(jid: string, timeoutMs?: number) => {
const response = await query({
json: ['query', 'ProfilePicThumb', jid],
expect200: false,
const response = await query({
json: ['query', 'ProfilePicThumb', jid],
expect200: false,
requiresPhoneConnection: false,
timeoutMs
})
@@ -71,11 +71,11 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
case 'unstar':
const starred = updateType === 'star'
const updates: WAMessageUpdate[] = (node.content as BinaryNode[]).map(
({ attrs }) => ({
({ attrs }) => ({
key: {
remoteJid: jid,
id: attrs.index,
fromMe: attrs.owner === 'true'
remoteJid: jid,
id: attrs.index,
fromMe: attrs.owner === 'true'
},
update: { starred }
})
@@ -93,13 +93,13 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
default:
logger.warn({ node }, 'received unrecognized chat update')
break
}
}
}
const applyingPresenceUpdate = (update: BinaryNode['attrs']): BaileysEventMap<any>['presence.update'] => {
const id = jidNormalizedUser(update.id)
const participant = jidNormalizedUser(update.participant || update.id)
const presence: PresenceData = {
lastSeen: update.t ? +update.t : undefined,
lastKnownPresence: update.type as WAPresence
@@ -110,21 +110,21 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
const chatRead = async(fromMessage: WAMessageKey, count: number) => {
await setQuery (
[
{
{
tag: 'read',
attrs: {
jid: fromMessage.remoteJid,
count: count.toString(),
index: fromMessage.id,
attrs: {
jid: fromMessage.remoteJid,
count: count.toString(),
index: fromMessage.id,
owner: fromMessage.fromMe ? 'true' : 'false'
}
}
],
],
[ WAMetric.read, WAFlag.ignore ]
)
if(config.emitOwnEvents) {
ev.emit('chats.update', [{ id: fromMessage.remoteJid, unreadCount: count < 0 ? -1 : 0 }])
}
}
}
ev.on('connection.update', async({ connection }) => {
@@ -143,7 +143,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
binaryTag: [ WAMetric.queryStatus, WAFlag.ignore ]
}),
sendNode({
json: { tag: 'query', attrs: { type: 'quick_reply', epoch: '1' } },
json: { tag: 'query', attrs: { type: 'quick_reply', epoch: '1' } },
binaryTag: [ WAMetric.queryQuickReply, WAFlag.ignore ]
}),
sendNode({
@@ -152,21 +152,21 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
}),
sendNode({
json: { tag: 'query', attrs: { type: 'emoji', epoch: '1' } },
binaryTag: [ WAMetric.queryEmoji, WAFlag.ignore ]
binaryTag: [ WAMetric.queryEmoji, WAFlag.ignore ]
}),
sendNode({
json: {
tag: 'action',
json: {
tag: 'action',
attrs: { type: 'set', epoch: '1' },
content: [
{ tag: 'presence', attrs: { type: 'available' } }
]
},
},
binaryTag: [ WAMetric.presence, WAFlag.available ]
})
])
chatsDebounceTimeout.start()
logger.debug('sent init queries')
} catch(error) {
logger.error(`error in sending init queries: ${error}`)
@@ -246,16 +246,16 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
ev.emit('chats.update', [update])
}
})
})
socketEvents.on('CB:Cmd,type:picture', async json => {
json = json[1]
const id = jidNormalizedUser(json.jid)
const imgUrl = await profilePictureUrl(id).catch(() => '')
ev.emit('contacts.update', [ { id, imgUrl } ])
})
// chat archive, pin etc.
socketEvents.on('CB:action,,chat', ({ content }: BinaryNode) => {
if(Array.isArray(content)) {
@@ -269,7 +269,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
const user = json.content[0].attrs
if(user.id) {
user.id = jidNormalizedUser(user.id)
//ev.emit('contacts.upsert', [user])
} else {
logger.warn({ json }, 'recv unknown action')
@@ -303,7 +303,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
* Modify a given chat (archive, pin etc.)
* @param jid the ID of the person/group you are modifiying
*/
chatModify: async(modification: ChatModification, jid: string, chatInfo: Pick<Chat, 'mute' | 'pin'>, timestampNow?: number) => {
chatModify: async(modification: ChatModification, jid: string, chatInfo: Pick<Chat, 'mute' | 'pin'>, timestampNow?: number) => {
const chatAttrs: BinaryNode['attrs'] = { jid: jid }
let data: BinaryNode[] | undefined = undefined
@@ -327,10 +327,10 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
}
} else if('clear' in modification) {
chatAttrs.type = 'clear'
chatAttrs.modify_tag = Math.round(Math.random()*1000000).toString()
chatAttrs.modify_tag = Math.round(Math.random() * 1000000).toString()
if(modification.clear !== 'all') {
data = modification.clear.messages.map(({ id, fromMe }) => (
{
{
tag: 'item',
attrs: { owner: (!!fromMe).toString(), index: id }
}
@@ -339,20 +339,20 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
} else if('star' in modification) {
chatAttrs.type = modification.star.star ? 'star' : 'unstar'
data = modification.star.messages.map(({ id, fromMe }) => (
{
{
tag: 'item',
attrs: { owner: (!!fromMe).toString(), index: id }
}
))
} else if('markRead' in modification) {
const indexKey = modification.lastMessages[modification.lastMessages.length-1].key
const indexKey = modification.lastMessages[modification.lastMessages.length - 1].key
return chatRead(indexKey, modification.markRead ? 0 : -1)
} else if('delete' in modification) {
chatAttrs.type = 'delete'
}
if('lastMessages' in modification) {
const indexKey = modification.lastMessages[modification.lastMessages.length-1].key
const indexKey = modification.lastMessages[modification.lastMessages.length - 1].key
if(indexKey) {
chatAttrs.index = indexKey.id
chatAttrs.owner = indexKey.fromMe ? 'true' : 'false'
@@ -368,20 +368,20 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
return response
},
/**
/**
* Query whether a given number is registered on WhatsApp
* @param str phone number/jid you want to check for
* @returns undefined if the number doesn't exists, otherwise the correctly formatted jid
*/
onWhatsApp: async(str: string) => {
const { status, jid, biz } = await query({
json: ['query', 'exist', str],
json: ['query', 'exist', str],
requiresPhoneConnection: false
})
if(status === 200) {
return {
exists: true,
jid: jidNormalizedUser(jid),
return {
exists: true,
jid: jidNormalizedUser(jid),
isBusiness: biz as boolean
}
}
@@ -394,20 +394,20 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
sendPresenceUpdate: (type: WAPresence, jid: string | undefined) => (
sendNode({
binaryTag: [WAMetric.presence, WAFlag[type]], // weird stuff WA does
json: {
json: {
tag: 'action',
attrs: { epoch: currentEpoch().toString(), type: 'set' },
content: [
{
tag: 'presence',
{
tag: 'presence',
attrs: { type: type, to: jid }
}
]
}
})
),
/**
* Request updates on the presence of a user
/**
* Request updates on the presence of a user
* this returns nothing, you'll receive updates in chats.update event
* */
presenceSubscribe: async(jid: string) => (
@@ -421,7 +421,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
setStatus: async(status: string) => {
const response = await setQuery(
[
{
{
tag: 'status',
attrs: {},
content: Buffer.from (status, 'utf-8')
@@ -444,7 +444,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
updateProfileName: async(name: string) => {
const response = (await setQuery(
[
{
{
tag: 'profile',
attrs: { name }
}
@@ -463,14 +463,14 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
},
/**
* Update the profile picture
* @param jid
* @param img
* @param jid
* @param img
*/
async updateProfilePicture(jid: string, img: Buffer) {
jid = jidNormalizedUser (jid)
const data = { img: Buffer.from([]), preview: Buffer.from([]) } //await generateProfilePicture(img) TODO
const tag = this.generateMessageTag ()
const query: BinaryNode = {
const query: BinaryNode = {
tag: 'picture',
attrs: { jid: jid, id: tag, type: 'set' },
content: [
@@ -481,7 +481,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
const user = state.legacy?.user
const { eurl } = await this.setQuery ([query], [WAMetric.picture, 136], tag) as { eurl: string, status: number }
if(config.emitOwnEvents) {
if(jid === user.id) {
user.imgUrl = eurl
@@ -502,7 +502,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
* @param type type of operation
*/
blockUser: async(jid: string, type: 'add' | 'remove' = 'add') => {
const json = {
const json = {
tag: 'block',
attrs: { type },
content: [ { tag: 'user', attrs: { jid } } ]
@@ -522,12 +522,12 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
const {
profiles: [{
profile,
wid
wid
}]
} = await query({
json: [
'query', 'businessProfile',
[ { 'wid': jid.replace('@s.whatsapp.net', '@c.us') } ],
'query', 'businessProfile',
[ { 'wid': jid.replace('@s.whatsapp.net', '@c.us') } ],
84
],
expect200: true,

View File

@@ -6,8 +6,8 @@ import makeMessagesSocket from './messages'
const makeGroupsSocket = (config: LegacySocketConfig) => {
const { logger } = config
const sock = makeMessagesSocket(config)
const {
ev,
const {
ev,
ws: socketEvents,
query,
generateMessageTag,
@@ -29,10 +29,10 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
jid: jid,
subject: subject,
},
content: participants ?
content: participants ?
participants.map(jid => (
{ tag: 'participant', attrs: { jid } }
)) :
)) :
additionalNodes
}
], [WAMetric.group, 136], tag)
@@ -42,9 +42,9 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
/** Get the metadata of the group from WA */
const groupMetadataFull = async(jid: string) => {
const metadata = await query({
json: ['query', 'GroupMetadata', jid],
json: ['query', 'GroupMetadata', jid],
expect200: true
})
})
const meta: GroupMetadata = {
id: metadata.id,
@@ -69,10 +69,10 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
const groupMetadataMinimal = async(jid: string) => {
const { attrs, content }:BinaryNode = await query({
json: {
tag: 'query',
tag: 'query',
attrs: { type: 'group', jid: jid, epoch: currentEpoch().toString() }
},
binaryTag: [WAMetric.group, WAFlag.ignore],
binaryTag: [WAMetric.group, WAFlag.ignore],
expect200: true
})
const participants: GroupParticipant[] = []
@@ -102,7 +102,7 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
}
return meta
}
socketEvents.on('CB:Chat,cmd:action', (json: BinaryNode) => {
/*const data = json[1].data
if (data) {
@@ -138,7 +138,7 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
result = await groupMetadataFull(jid)
}
return result
return result
},
/**
* Create a group
@@ -219,16 +219,16 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
return jids
},
/** Query broadcast list info */
getBroadcastListInfo: async(jid: string) => {
getBroadcastListInfo: async(jid: string) => {
interface WABroadcastListInfo {
status: number
name: string
recipients?: {id: string}[]
}
const result = await query({
json: ['query', 'contact', jid],
expect200: true,
const result = await query({
json: ['query', 'contact', jid],
expect200: true,
requiresPhoneConnection: true
}) as WABroadcastListInfo
@@ -245,8 +245,8 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
},
groupInviteCode: async(jid: string) => {
const response = await sock.query({
json: ['query', 'inviteCode', jid],
expect200: true,
json: ['query', 'inviteCode', jid],
expect200: true,
requiresPhoneConnection: false
})
return response.code as string

View File

@@ -15,8 +15,8 @@ const STATUS_MAP = {
const makeMessagesSocket = (config: LegacySocketConfig) => {
const { logger } = config
const sock = makeChatsSocket(config)
const {
ev,
const {
ev,
ws: socketEvents,
query,
generateMessageTag,
@@ -28,10 +28,10 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
let mediaConn: Promise<MediaConnInfo>
const refreshMediaConn = async(forceGet = false) => {
const media = await mediaConn
if(!media || forceGet || (new Date().getTime()-media.fetchDate.getTime()) > media.ttl*1000) {
if(!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
mediaConn = (async() => {
const { media_conn } = await query({
json: ['query', 'mediaConn'],
json: ['query', 'mediaConn'],
requiresPhoneConnection: false,
expect200: true
})
@@ -40,12 +40,12 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
})()
}
return mediaConn
return mediaConn
}
const fetchMessagesFromWA = async(
jid: string,
count: number,
jid: string,
count: number,
cursor?: WAMessageCursor
) => {
let key: WAMessageKey
@@ -66,8 +66,8 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
owner: key?.fromMe === false ? 'false' : 'true',
}
},
binaryTag: [WAMetric.queryMessages, WAFlag.ignore],
expect200: false,
binaryTag: [WAMetric.queryMessages, WAFlag.ignore],
expect200: false,
requiresPhoneConnection: true
})
if(Array.isArray(content)) {
@@ -78,27 +78,27 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
}
const updateMediaMessage = async(message: WAMessage) => {
const content = message.message?.audioMessage || message.message?.videoMessage || message.message?.imageMessage || message.message?.stickerMessage || message.message?.documentMessage
const content = message.message?.audioMessage || message.message?.videoMessage || message.message?.imageMessage || message.message?.stickerMessage || message.message?.documentMessage
if(!content) {
throw new Boom(
`given message ${message.key.id} is not a media message`,
`given message ${message.key.id} is not a media message`,
{ statusCode: 400, data: message }
)
}
const response: BinaryNode = await query ({
json: {
tag: 'query',
attrs: {
type: 'media',
index: message.key.id,
owner: message.key.fromMe ? 'true' : 'false',
jid: message.key.remoteJid,
type: 'media',
index: message.key.id,
owner: message.key.fromMe ? 'true' : 'false',
jid: message.key.remoteJid,
epoch: currentEpoch().toString()
}
},
binaryTag: [WAMetric.queryMedia, WAFlag.ignore],
expect200: true,
},
binaryTag: [WAMetric.queryMedia, WAFlag.ignore],
expect200: true,
requiresPhoneConnection: true
})
const attrs = response.attrs
@@ -112,14 +112,14 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
const onMessage = (message: WAMessage, type: MessageUpdateType) => {
const jid = message.key.remoteJid!
// store chat updates in this
const chatUpdate: Partial<Chat> = {
const chatUpdate: Partial<Chat> = {
id: jid,
}
const emitGroupUpdate = (update: Partial<GroupMetadata>) => {
ev.emit('groups.update', [ { id: jid, ...update } ])
}
if(message.message) {
chatUpdate.conversationTimestamp = +toNumber(message.messageTimestamp)
// add to count if the message isn't from me & there exists a message
@@ -128,7 +128,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
const participant = jidNormalizedUser(message.participant || jid)
ev.emit(
'presence.update',
'presence.update',
{
id: jid,
presences: { [participant]: { lastKnownPresence: 'available' } }
@@ -144,11 +144,11 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
case proto.ProtocolMessage.ProtocolMessageType.REVOKE:
const key = protocolMessage.key
const messageStubType = WAMessageStubType.REVOKE
ev.emit('messages.update', [
{
ev.emit('messages.update', [
{
// the key of the deleted message is updated
update: { message: null, key: message.key, messageStubType },
key
update: { message: null, key: message.key, messageStubType },
key
}
])
return
@@ -166,7 +166,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
}
}
// check if the message is an action
// check if the message is an action
if(message.messageStubType) {
const { user } = state.legacy!
//let actor = jidNormalizedUser (message.participant)
@@ -234,14 +234,14 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
const response: BinaryNode = await query({
json: {
tag: 'query',
attrs: {
type: 'url',
url: text,
epoch: currentEpoch().toString()
attrs: {
type: 'url',
url: text,
epoch: currentEpoch().toString()
}
},
binaryTag: [26, WAFlag.ignore],
expect200: true,
},
binaryTag: [26, WAFlag.ignore],
expect200: true,
requiresPhoneConnection: false
})
const urlInfo = { ...response.attrs } as any as WAUrlInfo
@@ -258,9 +258,9 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
tag: 'action',
attrs: { epoch: currentEpoch().toString(), type: 'relay' },
content: [
{
tag: 'message',
attrs: {},
{
tag: 'message',
attrs: {},
content: proto.WebMessageInfo.encode(message).finish()
}
]
@@ -272,9 +272,9 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
message.status = WAMessageStatus.PENDING
const promise = query({
json,
binaryTag: [WAMetric.message, flag],
tag: mID,
json,
binaryTag: [WAMetric.message, flag],
tag: mID,
expect200: true,
requiresPhoneConnection: true
})
@@ -308,7 +308,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
socketEvents.on('CB:action,add:last', json => messagesUpdate(json, true))
socketEvents.on('CB:action,add:unread', json => messagesUpdate(json, false))
socketEvents.on('CB:action,add:before', json => messagesUpdate(json, false))
// new messages
socketEvents.on('CB:action,add:relay,message', (node: BinaryNode) => {
const msgs = getBinaryNodeMessages(node)
@@ -316,7 +316,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
onMessage(msg, 'notify')
}
})
// If a message has been updated
// If a message has been updated
// usually called when a video message gets its upload url, or live locations or ciphertext message gets fixed
socketEvents.on ('CB:action,add:update,message', (node: BinaryNode) => {
const msgs = getBinaryNodeMessages(node)
@@ -369,7 +369,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
return
}
const keyPartial = {
const keyPartial = {
remoteJid: jidNormalizedUser(attributes.to),
fromMe: areJidsSameUser(attributes.from, state.legacy?.user?.id || ''),
}
@@ -413,13 +413,13 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
json: {
tag: 'query',
attrs: {
type: 'message_info',
index: messageID,
jid: jid,
type: 'message_info',
index: messageID,
jid: jid,
epoch: currentEpoch().toString()
}
},
binaryTag: [WAMetric.queryRead, WAFlag.ignore],
},
binaryTag: [WAMetric.queryRead, WAFlag.ignore],
expect200: true,
requiresPhoneConnection: true
})
@@ -427,7 +427,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
if(Array.isArray(content)) {
for(const { tag, content: innerData } of content) {
const [{ attrs }] = (innerData as BinaryNode[])
const jid = jidNormalizedUser(attrs.jid)
const recp = info[jid] || { userJid: jid }
const date = +attrs.t
@@ -465,14 +465,14 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
return stream
}
try {
const result = await downloadMediaMessage()
return result
} catch(error) {
if(error.message.includes('404')) { // media needs to be updated
logger.info (`updating media of message: ${message.key.id}`)
await updateMediaMessage(message)
const result = await downloadMediaMessage()
@@ -508,13 +508,13 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
page: page.toString(),
jid: inJid
}
},
binaryTag: [24, WAFlag.ignore],
},
binaryTag: [24, WAFlag.ignore],
expect200: true
}) // encrypt and send off
return {
last: node.attrs?.last === 'true',
return {
last: node.attrs?.last === 'true',
messages: getBinaryNodeMessages(node)
}
},
@@ -531,7 +531,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
isJidGroup(jid)
) {
const { disappearingMessagesInChat } = content
const value = typeof disappearingMessagesInChat === 'boolean' ?
const value = typeof disappearingMessagesInChat === 'boolean' ?
(disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) :
disappearingMessagesInChat
const tag = generateMessageTag(true)
@@ -539,8 +539,8 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
{
tag: 'group',
attrs: { id: tag, jid, type: 'prop', author: userJid },
content: [
{ tag: 'ephemeral', attrs: { value: value.toString() } }
content: [
{ tag: 'ephemeral', attrs: { value: value.toString() } }
]
}
])
@@ -557,7 +557,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
...options,
}
)
await relayMessage(msg, { waitForAck: options.waitForAck })
return msg
}

View File

@@ -14,13 +14,13 @@ import { BinaryNode, encodeBinaryNodeLegacy } from '../WABinary'
* - query phone connection
*/
export const makeSocket = ({
waWebSocketUrl,
connectTimeoutMs,
phoneResponseTimeMs,
logger,
agent,
waWebSocketUrl,
connectTimeoutMs,
phoneResponseTimeMs,
logger,
agent,
keepAliveIntervalMs,
expectResponseTimeout,
expectResponseTimeout,
}: LegacySocketConfig) => {
// for generating tags
const referenceDateSeconds = unixTimestampSeconds(new Date())
@@ -53,7 +53,7 @@ export const makeSocket = ({
const sendPromise = promisify(ws.send)
/** generate message tag and increment epoch */
const generateMessageTag = (longTag: boolean = false) => {
const tag = `${longTag ? referenceDateSeconds : (referenceDateSeconds%1000)}.--${epoch}`
const tag = `${longTag ? referenceDateSeconds : (referenceDateSeconds % 1000)}.--${epoch}`
epoch += 1 // increment message count, it makes the 'epoch' field when sending binary messages
return tag
}
@@ -66,7 +66,7 @@ export const makeSocket = ({
return sendPromise.call(ws, data) as Promise<void>
}
/**
/**
* Send a message to the WA servers
* @returns the tag attached in the message
* */
@@ -121,7 +121,7 @@ export const makeSocket = ({
if(ws.readyState !== ws.CLOSED && ws.readyState !== ws.CLOSING) {
try {
ws.close()
ws.close()
} catch{ }
}
@@ -150,7 +150,7 @@ export const makeSocket = ({
return
}
//if (this.shouldLogMessages) this.messageLog.push ({ tag: messageTag, json: JSON.stringify(json), fromMe: false })
if(logger.level === 'trace') {
logger.trace({ tag: messageTag, fromMe: false, json }, 'communication')
}
@@ -213,7 +213,7 @@ export const makeSocket = ({
phoneConnectionChanged(false)
}, phoneResponseTimeMs)
}
}
}
const clearPhoneCheckInterval = () => {
@@ -254,12 +254,12 @@ export const makeSocket = ({
}
cancelToken = () => onErr(new Boom('Cancelled', { statusCode: 500 }))
if(requiresPhoneConnection) {
startPhoneCheckInterval()
cancelPhoneChecker = exitQueryIfResponseNotExpected(tag, onErr)
}
ws.on(`TAG:${tag}`, onRecv)
ws.on('ws-close', onErr) // if the socket closes, you'll never receive the message
},
@@ -268,13 +268,13 @@ export const makeSocket = ({
} finally {
requiresPhoneConnection && clearPhoneCheckInterval()
cancelPhoneChecker && cancelPhoneChecker()
ws.off(`TAG:${tag}`, onRecv)
ws.off('ws-close', onErr) // if the socket closes, you'll never receive the message
}
})(),
cancelToken: () => {
cancelToken()
cancelToken()
}
}
}
@@ -300,7 +300,7 @@ export const makeSocket = ({
// throw back the error
throw error
}
const response = await promise
const responseStatusCode = +(response.status ? response.status : 200) // default status
// read here: http://getstatuscode.com/599
@@ -308,10 +308,10 @@ export const makeSocket = ({
end(new Boom('WA server overloaded', { statusCode: 599, data: { query: json, response } }))
}
if(expect200 && Math.floor(responseStatusCode/100) !== 2) {
if(expect200 && Math.floor(responseStatusCode / 100) !== 2) {
const message = STATUS_CODES[responseStatusCode] || 'unknown'
throw new Boom(
`Unexpected status in '${Array.isArray(json) ? json[0] : (json?.tag || 'query')}': ${message}(${responseStatusCode})`,
`Unexpected status in '${Array.isArray(json) ? json[0] : (json?.tag || 'query')}': ${message}(${responseStatusCode})`,
{ data: { query: json, response }, statusCode: response.status }
)
}
@@ -330,7 +330,7 @@ export const makeSocket = ({
check if it's been a suspicious amount of time since the server responded with our last seen
it could be that the network is down
*/
if(diff > keepAliveIntervalMs+5000) {
if(diff > keepAliveIntervalMs + 5000) {
end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
} else if(ws.readyState === ws.OPEN) {
sendRawMessage('?,,') // if its all good, send a keep alive request
@@ -394,7 +394,7 @@ export const makeSocket = ({
}
end(new Boom(
`Connection terminated by server: "${kind || 'unknown'}"`,
`Connection terminated by server: "${kind || 'unknown'}"`,
{ statusCode: reason }
))
})
@@ -417,12 +417,12 @@ export const makeSocket = ({
content: nodes
}
return query({
json,
binaryTag,
tag,
expect200: true,
requiresPhoneConnection: true
return query({
json,
binaryTag,
tag,
expect200: true,
requiresPhoneConnection: true
}) as Promise<{ status: number }>
},
currentEpoch: () => epoch,