mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
lint: stricter linting rules
This commit is contained in:
@@ -11,7 +11,7 @@ const MAX_SYNC_ATTEMPTS = 5
|
||||
export const makeChatsSocket = (config: SocketConfig) => {
|
||||
const { logger } = config
|
||||
const sock = makeMessagesSocket(config)
|
||||
const {
|
||||
const {
|
||||
ev,
|
||||
ws,
|
||||
authState,
|
||||
@@ -95,7 +95,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
|
||||
const fetchStatus = async(jid: string) => {
|
||||
const [result] = await interactiveQuery(
|
||||
[{ tag: 'user', attrs: { jid } }],
|
||||
[{ tag: 'user', attrs: { jid } }],
|
||||
{ tag: 'status', attrs: { } }
|
||||
)
|
||||
if(result) {
|
||||
@@ -130,8 +130,8 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
xmlns: 'blocklist',
|
||||
to: S_WHATSAPP_NET,
|
||||
xmlns: 'blocklist',
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'get'
|
||||
}
|
||||
})
|
||||
@@ -223,7 +223,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
attrs: {
|
||||
type: 'account_sync',
|
||||
timestamp: fromTimestamp.toString(),
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
@@ -238,7 +238,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
await authState.keys.transaction(
|
||||
async() => {
|
||||
const collectionsToHandle = new Set<string>(collections)
|
||||
// in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
|
||||
// in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
|
||||
const attemptsMap = { } as { [T in WAPatchName]: number | undefined }
|
||||
// keep executing till all collections are done
|
||||
// sometimes a single patch request will not return all the patches (God knows why)
|
||||
@@ -265,9 +265,9 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
|
||||
nodes.push({
|
||||
tag: 'collection',
|
||||
attrs: {
|
||||
name,
|
||||
version: state.version.toString(),
|
||||
attrs: {
|
||||
name,
|
||||
version: state.version.toString(),
|
||||
// return snapshot if being synced from scratch
|
||||
return_snapshot: (!state.version).toString()
|
||||
}
|
||||
@@ -289,7 +289,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
|
||||
const decoded = await extractSyncdPatches(result) // extract from binary node
|
||||
for(const key in decoded) {
|
||||
const name = key as WAPatchName
|
||||
@@ -298,7 +298,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
if(snapshot) {
|
||||
const { state: newState, mutations } = await decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name])
|
||||
states[name] = newState
|
||||
|
||||
|
||||
logger.info(`restored state of ${name} from snapshot to v${newState.version} with ${mutations.length} mutations`)
|
||||
|
||||
await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
|
||||
@@ -309,14 +309,14 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
// only process if there are syncd patches
|
||||
if(patches.length) {
|
||||
const { newMutations, state: newState } = await decodePatches(name, patches, states[name], getAppStateSyncKey, initialVersionMap[name])
|
||||
|
||||
|
||||
await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
|
||||
|
||||
|
||||
logger.info(`synced ${name} to v${newState.version}`)
|
||||
if(newMutations.length) {
|
||||
logger.trace({ newMutations, name }, 'recv new mutations')
|
||||
}
|
||||
|
||||
|
||||
appStateChunk.totalMutations.push(...newMutations)
|
||||
}
|
||||
|
||||
@@ -431,17 +431,17 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
const resyncMainAppState = async() => {
|
||||
|
||||
|
||||
logger.debug('resyncing main app state')
|
||||
|
||||
|
||||
await (
|
||||
mutationMutex.mutex(
|
||||
() => resyncAppState([
|
||||
'critical_block',
|
||||
'critical_unblock_low',
|
||||
'regular_high',
|
||||
'regular_low',
|
||||
'regular'
|
||||
() => resyncAppState([
|
||||
'critical_block',
|
||||
'critical_unblock_low',
|
||||
'regular_high',
|
||||
'regular_low',
|
||||
'regular'
|
||||
])
|
||||
)
|
||||
.catch(err => (
|
||||
@@ -458,7 +458,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
for(const { syncAction: { value: action }, index: [_, id, msgId, fromMe] } of actions) {
|
||||
const update: Partial<Chat> = { id }
|
||||
if(action?.muteAction) {
|
||||
update.mute = action.muteAction?.muted ?
|
||||
update.mute = action.muteAction?.muted ?
|
||||
toNumber(action.muteAction!.muteEndTimestamp!) :
|
||||
undefined
|
||||
} else if(action?.archiveChatAction) {
|
||||
@@ -546,7 +546,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
tag: 'collection',
|
||||
attrs: {
|
||||
name,
|
||||
version: (state.version-1).toString(),
|
||||
version: (state.version - 1).toString(),
|
||||
return_snapshot: 'false'
|
||||
},
|
||||
content: [
|
||||
@@ -562,9 +562,9 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
]
|
||||
}
|
||||
await query(node)
|
||||
|
||||
|
||||
await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
|
||||
|
||||
|
||||
if(config.emitOwnEvents) {
|
||||
const result = await decodePatches(name, [{ ...patch, version: { version: state.version }, }], initial, getAppStateSyncKey)
|
||||
processSyncActions(result.newMutations)
|
||||
@@ -589,7 +589,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
})
|
||||
|
||||
const propsNode = getBinaryNodeChild(abtNode, 'props')
|
||||
|
||||
|
||||
let props: { [_: string]: string } = { }
|
||||
if(propsNode) {
|
||||
props = reduceBinaryNodeToDictionary(propsNode, 'prop')
|
||||
@@ -616,7 +616,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
})
|
||||
|
||||
const propsNode = getBinaryNodeChild(resultNode, 'props')
|
||||
|
||||
|
||||
let props: { [_: string]: string } = { }
|
||||
if(propsNode) {
|
||||
props = reduceBinaryNodeToDictionary(propsNode, 'prop')
|
||||
@@ -651,7 +651,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
lastAccountSyncTimestamp = +attrs.timestamp
|
||||
ev.emit('creds.update', { lastAccountSyncTimestamp })
|
||||
ev.emit('creds.update', { lastAccountSyncTimestamp })
|
||||
break
|
||||
default:
|
||||
logger.info({ node }, 'received unknown sync')
|
||||
@@ -683,7 +683,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
||||
})
|
||||
|
||||
return {
|
||||
...sock,
|
||||
...sock,
|
||||
appPatch,
|
||||
sendPresenceUpdate,
|
||||
presenceSubscribe,
|
||||
|
||||
@@ -21,15 +21,15 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
|
||||
const groupMetadata = async(jid: string) => {
|
||||
const result = await groupQuery(
|
||||
jid,
|
||||
'get',
|
||||
jid,
|
||||
'get',
|
||||
[ { tag: 'query', attrs: { request: 'interactive' } } ]
|
||||
)
|
||||
return extractGroupMetadata(result)
|
||||
}
|
||||
|
||||
return {
|
||||
...sock,
|
||||
...sock,
|
||||
groupMetadata,
|
||||
groupCreate: async(subject: string, participants: string[]) => {
|
||||
const key = generateMessageID()
|
||||
@@ -86,7 +86,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
action: ParticipantAction
|
||||
) => {
|
||||
const result = await groupQuery(
|
||||
jid,
|
||||
jid,
|
||||
'set',
|
||||
participants.map(
|
||||
jid => ({
|
||||
@@ -135,7 +135,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
return result.attrs.jid
|
||||
},
|
||||
groupToggleEphemeral: async(jid: string, ephemeralExpiration: number) => {
|
||||
const content: BinaryNode = ephemeralExpiration ?
|
||||
const content: BinaryNode = ephemeralExpiration ?
|
||||
{ tag: 'ephemeral', attrs: { ephemeral: ephemeralExpiration.toString() } } :
|
||||
{ tag: 'not_ephemeral', attrs: { } }
|
||||
await groupQuery(jid, 'set', [content])
|
||||
|
||||
@@ -19,14 +19,14 @@ const getStatusFromReceiptType = (type: string | undefined) => {
|
||||
if(typeof type === 'undefined') {
|
||||
return proto.WebMessageInfo.WebMessageInfoStatus.DELIVERY_ACK
|
||||
}
|
||||
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
const { logger } = config
|
||||
const sock = makeChatsSocket(config)
|
||||
const {
|
||||
const {
|
||||
ev,
|
||||
authState,
|
||||
ws,
|
||||
@@ -74,11 +74,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
return
|
||||
}
|
||||
|
||||
msgRetryMap[msgId] = retryCount+1
|
||||
msgRetryMap[msgId] = retryCount + 1
|
||||
|
||||
const isGroup = !!node.attrs.participant
|
||||
const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
|
||||
|
||||
|
||||
const deviceIdentity = proto.ADVSignedDeviceIdentity.encode(account).finish()
|
||||
await assertingPreKeys(1, async preKeys => {
|
||||
const [keyId] = Object.keys(preKeys)
|
||||
@@ -93,14 +93,14 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
to: isGroup ? node.attrs.from : jidEncode(decFrom!.user, 's.whatsapp.net', decFrom!.device, 0)
|
||||
},
|
||||
content: [
|
||||
{
|
||||
tag: 'retry',
|
||||
attrs: {
|
||||
count: retryCount.toString(),
|
||||
{
|
||||
tag: 'retry',
|
||||
attrs: {
|
||||
count: retryCount.toString(),
|
||||
id: node.attrs.id,
|
||||
t: node.attrs.t,
|
||||
v: '1'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'registration',
|
||||
@@ -145,10 +145,10 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
switch (protocolMsg.type) {
|
||||
case proto.ProtocolMessage.ProtocolMessageType.HISTORY_SYNC_NOTIFICATION:
|
||||
const histNotification = protocolMsg!.historySyncNotification
|
||||
|
||||
|
||||
logger.info({ histNotification, id: message.key.id }, 'got history notification')
|
||||
const { chats, contacts, messages, isLatest } = await downloadAndProcessHistorySyncNotification(histNotification, historyCache)
|
||||
|
||||
|
||||
const meJid = authState.creds.me!.id
|
||||
await sendNode({
|
||||
tag: 'receipt',
|
||||
@@ -178,15 +178,15 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
let newAppStateSyncKeyId = ''
|
||||
for(const { keyData, keyId } of keys) {
|
||||
const strKeyId = Buffer.from(keyId.keyId!).toString('base64')
|
||||
|
||||
|
||||
logger.info({ strKeyId }, 'injecting new app state sync key')
|
||||
await authState.keys.set({ 'app-state-sync-key': { [strKeyId]: keyData } })
|
||||
|
||||
|
||||
newAppStateSyncKeyId = strKeyId
|
||||
}
|
||||
|
||||
|
||||
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
|
||||
|
||||
|
||||
resyncMainAppState()
|
||||
} else {
|
||||
[
|
||||
@@ -197,12 +197,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
break
|
||||
case proto.ProtocolMessage.ProtocolMessageType.REVOKE:
|
||||
ev.emit('messages.update', [
|
||||
{
|
||||
{
|
||||
key: {
|
||||
...message.key,
|
||||
id: protocolMsg.key!.id
|
||||
},
|
||||
update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
|
||||
},
|
||||
update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
|
||||
}
|
||||
])
|
||||
break
|
||||
@@ -299,7 +299,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
|
||||
const participants = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid)
|
||||
if(
|
||||
participants.length === 1 &&
|
||||
participants.length === 1 &&
|
||||
// if recv. "remove" message and sender removed themselves
|
||||
// mark as left
|
||||
areJidsSameUser(participants[0], node.attrs.participant) &&
|
||||
@@ -324,7 +324,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
result.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT
|
||||
result.messageStubParameters = [ (child.tag === 'locked') ? 'on' : 'off' ]
|
||||
break
|
||||
|
||||
|
||||
}
|
||||
} else {
|
||||
switch (child.tag) {
|
||||
@@ -354,7 +354,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
// message failed to decrypt
|
||||
if(msg.messageStubType === proto.WebMessageInfo.WebMessageInfoStubType.CIPHERTEXT) {
|
||||
logger.error(
|
||||
{ msgId: msg.key.id, params: msg.messageStubParameters },
|
||||
{ msgId: msg.key.id, params: msg.messageStubParameters },
|
||||
'failure in decrypting message'
|
||||
)
|
||||
retryMutex.mutex(
|
||||
@@ -366,7 +366,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
await sendReceipt(msg.key.remoteJid!, msg.key.participant, [msg.key.id!], undefined)
|
||||
logger.debug({ msg: msg.key }, 'sent delivery receipt')
|
||||
}
|
||||
|
||||
|
||||
msg.key.remoteJid = jidNormalizedUser(msg.key.remoteJid!)
|
||||
ev.emit('messages.upsert', { messages: [msg], type: stanza.attrs.offline ? 'append' : 'notify' })
|
||||
}
|
||||
@@ -470,7 +470,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
)
|
||||
} else {
|
||||
ev.emit(
|
||||
'messages.update',
|
||||
'messages.update',
|
||||
ids.map(id => ({
|
||||
key: { ...key, id },
|
||||
update: { status }
|
||||
@@ -521,7 +521,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
...(msg.key || {})
|
||||
}
|
||||
msg.messageTimestamp = +node.attrs.t
|
||||
|
||||
|
||||
const fullMsg = proto.WebMessageInfo.fromObject(msg)
|
||||
ev.emit('messages.upsert', { messages: [fullMsg], type: 'append' })
|
||||
}
|
||||
@@ -549,7 +549,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
||||
'p-' + chat.id!,
|
||||
() => processMessage(msg, chat)
|
||||
)
|
||||
|
||||
|
||||
if(!!msg.message && !msg.message!.protocolMessage) {
|
||||
chat.conversationTimestamp = toNumber(msg.messageTimestamp)
|
||||
if(!msg.key.fromMe) {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { makeGroupsSocket } from './groups'
|
||||
export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
const { logger } = config
|
||||
const sock = makeGroupsSocket(config)
|
||||
const {
|
||||
const {
|
||||
ev,
|
||||
authState,
|
||||
query,
|
||||
@@ -31,8 +31,8 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
const { content } = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
xmlns: 'privacy',
|
||||
to: S_WHATSAPP_NET,
|
||||
xmlns: 'privacy',
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'get'
|
||||
},
|
||||
content: [
|
||||
@@ -48,7 +48,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
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 result = await query({
|
||||
tag: 'iq',
|
||||
@@ -77,7 +77,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
/**
|
||||
* generic send receipt function
|
||||
* generic send receipt function
|
||||
* used for receipts of phone call, read, delivery etc.
|
||||
* */
|
||||
const sendReceipt = async(jid: string, participant: string | undefined, messageIds: string[], type: 'read' | 'read-self' | undefined) => {
|
||||
@@ -124,7 +124,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
|
||||
const getUSyncDevices = async(jids: string[], ignoreZeroDevices: boolean) => {
|
||||
const deviceResults: JidWithDevice[] = []
|
||||
|
||||
|
||||
const users: BinaryNode[] = []
|
||||
jids = Array.from(new Set(jids))
|
||||
for(let jid of jids) {
|
||||
@@ -162,8 +162,8 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
tag: 'query',
|
||||
attrs: { },
|
||||
content: [
|
||||
{
|
||||
tag: 'devices',
|
||||
{
|
||||
tag: 'devices',
|
||||
attrs: { version: '2' }
|
||||
}
|
||||
]
|
||||
@@ -194,7 +194,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
const assertSessions = async(jids: string[], force: boolean) => {
|
||||
let jidsRequiringFetch: string[] = []
|
||||
if(force) {
|
||||
jidsRequiringFetch = jids
|
||||
jidsRequiringFetch = jids
|
||||
} else {
|
||||
const addrs = jids.map(jid => jidToSignalProtocolAddress(jid).toString())
|
||||
const sessions = await authState.keys.get('session', addrs)
|
||||
@@ -240,11 +240,11 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
|
||||
if(authState.keys.isInTransaction()) {
|
||||
await authState.keys.prefetch(
|
||||
'session',
|
||||
'session',
|
||||
jids.map(jid => jidToSignalProtocolAddress(jid).toString())
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
const nodes = await Promise.all(
|
||||
jids.map(
|
||||
async jid => {
|
||||
@@ -266,8 +266,8 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
const relayMessage = async(
|
||||
jid: string,
|
||||
message: proto.IMessage,
|
||||
jid: string,
|
||||
message: proto.IMessage,
|
||||
{ messageId: msgId, participant, additionalAttributes, cachedGroupMetadata }: MessageRelayOptions
|
||||
) => {
|
||||
const meId = authState.creds.me!.id
|
||||
@@ -293,10 +293,10 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
async() => {
|
||||
if(isGroup) {
|
||||
const { ciphertext, senderKeyDistributionMessageKey } = await encryptSenderKeyMsgSignalProto(destinationJid, encodedMsg, meId, authState)
|
||||
|
||||
|
||||
const [groupData, senderKeyMap] = await Promise.all([
|
||||
(async() => {
|
||||
let groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
|
||||
let groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
|
||||
if(!groupData) {
|
||||
groupData = await groupMetadata(jid)
|
||||
}
|
||||
@@ -308,13 +308,13 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
return result[jid] || { }
|
||||
})()
|
||||
])
|
||||
|
||||
|
||||
if(!participant) {
|
||||
const participantsList = groupData.participants.map(p => p.id)
|
||||
const additionalDevices = await getUSyncDevices(participantsList, false)
|
||||
devices.push(...additionalDevices)
|
||||
}
|
||||
|
||||
|
||||
const senderKeyJids: string[] = []
|
||||
// ensure a connection is established with every device
|
||||
for(const { user, device } of devices) {
|
||||
@@ -330,44 +330,44 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
// if there are, we re-send the senderkey
|
||||
if(senderKeyJids.length) {
|
||||
logger.debug({ senderKeyJids }, 'sending new sender key')
|
||||
|
||||
|
||||
const encSenderKeyMsg = encodeWAMessage({
|
||||
senderKeyDistributionMessage: {
|
||||
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessageKey,
|
||||
groupId: destinationJid
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
participants.push(
|
||||
...(await createParticipantNodes(senderKeyJids, encSenderKeyMsg))
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
binaryNodeContent.push({
|
||||
tag: 'enc',
|
||||
attrs: { v: '2', type: 'skmsg' },
|
||||
content: ciphertext
|
||||
})
|
||||
|
||||
|
||||
await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
|
||||
} else {
|
||||
const { user: meUser } = jidDecode(meId)
|
||||
|
||||
|
||||
const encodedMeMsg = encodeWAMessage({
|
||||
deviceSentMessage: {
|
||||
destinationJid,
|
||||
message
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
if(!participant) {
|
||||
devices.push({ user })
|
||||
devices.push({ user: meUser })
|
||||
|
||||
|
||||
const additionalDevices = await getUSyncDevices([ meId, jid ], true)
|
||||
devices.push(...additionalDevices)
|
||||
}
|
||||
|
||||
|
||||
const meJids: string[] = []
|
||||
const otherJids: string[] = []
|
||||
for(const { user, device } of devices) {
|
||||
@@ -379,7 +379,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
otherJids.push(jid)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const [meNodes, otherNodes] = await Promise.all([
|
||||
createParticipantNodes(meJids, encodedMeMsg),
|
||||
createParticipantNodes(otherJids, encodedMsg)
|
||||
@@ -387,7 +387,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
participants.push(...meNodes)
|
||||
participants.push(...otherNodes)
|
||||
}
|
||||
|
||||
|
||||
if(participants.length) {
|
||||
binaryNodeContent.push({
|
||||
tag: 'participants',
|
||||
@@ -395,7 +395,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
content: participants
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
const stanza: BinaryNode = {
|
||||
tag: 'message',
|
||||
attrs: {
|
||||
@@ -406,32 +406,32 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
},
|
||||
content: binaryNodeContent
|
||||
}
|
||||
|
||||
|
||||
const shouldHaveIdentity = !!participants.find(
|
||||
participant => (participant.content! as BinaryNode[]).find(n => n.attrs.type === 'pkmsg')
|
||||
)
|
||||
|
||||
|
||||
if(shouldHaveIdentity) {
|
||||
(stanza.content as BinaryNode[]).push({
|
||||
tag: 'device-identity',
|
||||
attrs: { },
|
||||
content: proto.ADVSignedDeviceIdentity.encode(authState.creds.account).finish()
|
||||
})
|
||||
|
||||
|
||||
logger.debug({ jid }, 'adding device identity')
|
||||
}
|
||||
|
||||
|
||||
logger.debug({ msgId }, `sending message to ${participants.length} devices`)
|
||||
|
||||
|
||||
await sendNode(stanza)
|
||||
}
|
||||
)
|
||||
|
||||
return msgId
|
||||
}
|
||||
}
|
||||
|
||||
const waUploadToServer = getWAUploadToServer(config, refreshMediaConn)
|
||||
|
||||
|
||||
return {
|
||||
...sock,
|
||||
assertSessions,
|
||||
@@ -454,7 +454,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
isJidGroup(jid)
|
||||
) {
|
||||
const { disappearingMessagesInChat } = content
|
||||
const value = typeof disappearingMessagesInChat === 'boolean' ?
|
||||
const value = typeof disappearingMessagesInChat === 'boolean' ?
|
||||
(disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) :
|
||||
disappearingMessagesInChat
|
||||
await groupToggleEphemeral(jid, value)
|
||||
|
||||
@@ -16,10 +16,10 @@ import { assertNodeErrorFree, BinaryNode, encodeBinaryNode, getBinaryNodeChild,
|
||||
* - query phone connection
|
||||
*/
|
||||
export const makeSocket = ({
|
||||
waWebSocketUrl,
|
||||
connectTimeoutMs,
|
||||
logger,
|
||||
agent,
|
||||
waWebSocketUrl,
|
||||
connectTimeoutMs,
|
||||
logger,
|
||||
agent,
|
||||
keepAliveIntervalMs,
|
||||
version,
|
||||
browser,
|
||||
@@ -58,7 +58,7 @@ export const makeSocket = ({
|
||||
}
|
||||
|
||||
const { creds } = authState
|
||||
|
||||
|
||||
let lastDateRecv: Date
|
||||
let epoch = 0
|
||||
let keepAliveReq: NodeJS.Timeout
|
||||
@@ -129,7 +129,7 @@ export const makeSocket = ({
|
||||
onErr = err => {
|
||||
reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
|
||||
}
|
||||
|
||||
|
||||
ws.on(`TAG:${msgId}`, onRecv)
|
||||
ws.on('close', onErr) // if the socket closes, you'll never receive the message
|
||||
ws.off('error', onErr)
|
||||
@@ -203,10 +203,10 @@ export const makeSocket = ({
|
||||
/** get some pre-keys and do something with them */
|
||||
const assertingPreKeys = async(range: number, execute: (keys: { [_: number]: any }) => Promise<void>) => {
|
||||
const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(authState.creds, range)
|
||||
|
||||
|
||||
const update: Partial<AuthenticationCreds> = {
|
||||
nextPreKeyId: Math.max(lastPreKeyId+1, creds.nextPreKeyId),
|
||||
firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId+1)
|
||||
nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
|
||||
firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
|
||||
}
|
||||
if(!creds.serverHasPreKeys) {
|
||||
update.serverHasPreKeys = true
|
||||
@@ -255,7 +255,7 @@ export const makeSocket = ({
|
||||
if(logger.level === 'trace') {
|
||||
logger.trace({ msgId, fromMe: false, frame }, 'communication')
|
||||
}
|
||||
|
||||
|
||||
let anyTriggered = false
|
||||
/* Check if this is a response to a message we sent */
|
||||
anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame)
|
||||
@@ -263,7 +263,7 @@ export const makeSocket = ({
|
||||
const l0 = frame.tag
|
||||
const l1 = frame.attrs || { }
|
||||
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
|
||||
|
||||
|
||||
Object.keys(l1).forEach(key => {
|
||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
|
||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
|
||||
@@ -272,7 +272,7 @@ export const makeSocket = ({
|
||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
|
||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
|
||||
anyTriggered = ws.emit('frame', frame) || anyTriggered
|
||||
|
||||
|
||||
if(!anyTriggered && logger.level === 'debug') {
|
||||
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
||||
}
|
||||
@@ -293,16 +293,16 @@ export const makeSocket = ({
|
||||
|
||||
if(ws.readyState !== ws.CLOSED && ws.readyState !== ws.CLOSING) {
|
||||
try {
|
||||
ws.close()
|
||||
ws.close()
|
||||
} catch{ }
|
||||
}
|
||||
|
||||
ev.emit('connection.update', {
|
||||
connection: 'close',
|
||||
ev.emit('connection.update', {
|
||||
connection: 'close',
|
||||
lastDisconnect: {
|
||||
error,
|
||||
date: new Date()
|
||||
}
|
||||
}
|
||||
})
|
||||
ev.removeAllListeners('connection.update')
|
||||
}
|
||||
@@ -343,7 +343,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) {
|
||||
// if its all good, send a keep alive request
|
||||
@@ -422,8 +422,8 @@ export const makeSocket = ({
|
||||
})
|
||||
// QR gen
|
||||
ws.on('CB:iq,type:set,pair-device', async(stanza: BinaryNode) => {
|
||||
const iq: BinaryNode = {
|
||||
tag: 'iq',
|
||||
const iq: BinaryNode = {
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'result',
|
||||
@@ -446,7 +446,7 @@ export const makeSocket = ({
|
||||
}
|
||||
|
||||
const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',')
|
||||
|
||||
|
||||
ev.emit('connection.update', { qr })
|
||||
|
||||
qrTimer = setTimeout(genPairQR, qrMs)
|
||||
@@ -498,10 +498,10 @@ export const makeSocket = ({
|
||||
|
||||
ev.emit('connection.update', { connection: 'open' })
|
||||
})
|
||||
|
||||
|
||||
ws.on('CB:ib,,offline', (node: BinaryNode) => {
|
||||
const child = getBinaryNodeChild(node, 'offline')
|
||||
const offlineCount = +child.attrs.count
|
||||
const offlineCount = +child.attrs.count
|
||||
|
||||
logger.info(`got ${offlineCount} offline messages/notifications`)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user