chore: format everything

This commit is contained in:
canove
2025-05-06 12:10:19 -03:00
parent 04afa20244
commit fa706d0b50
76 changed files with 8241 additions and 7142 deletions
+207 -234
View File
@@ -1,6 +1,17 @@
import { AxiosRequestConfig } from 'axios'
import { proto } from '../../WAProto'
import { AuthenticationCreds, BaileysEventEmitter, CacheStore, Chat, GroupMetadata, ParticipantAction, RequestJoinAction, RequestJoinMethod, SignalKeyStoreWithTransaction, WAMessageStubType } from '../Types'
import {
AuthenticationCreds,
BaileysEventEmitter,
CacheStore,
Chat,
GroupMetadata,
ParticipantAction,
RequestJoinAction,
RequestJoinMethod,
SignalKeyStoreWithTransaction,
WAMessageStubType
} from '../Types'
import { getContentType, normalizeMessageContent } from '../Utils/messages'
import { areJidsSameUser, isJidBroadcast, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
import { aesDecryptGCM, hmacSign } from './crypto'
@@ -25,9 +36,7 @@ const REAL_MSG_STUB_TYPES = new Set([
WAMessageStubType.CALL_MISSED_VOICE
])
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
WAMessageStubType.GROUP_PARTICIPANT_ADD
])
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
/** Cleans a received message to further processing */
export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
@@ -36,25 +45,25 @@ export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
message.key.participant = message.key.participant ? jidNormalizedUser(message.key.participant) : undefined
const content = normalizeMessageContent(message.message)
// if the message has a reaction, ensure fromMe & remoteJid are from our perspective
if(content?.reactionMessage) {
if (content?.reactionMessage) {
normaliseKey(content.reactionMessage.key!)
}
if(content?.pollUpdateMessage) {
if (content?.pollUpdateMessage) {
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey!)
}
function normaliseKey(msgKey: proto.IMessageKey) {
// if the reaction is from another user
// we've to correctly map the key to this user's perspective
if(!message.key.fromMe) {
if (!message.key.fromMe) {
// if the sender believed the message being reacted to is not from them
// we've to correct the key to be from them, or some other participant
msgKey.fromMe = !msgKey.fromMe
? areJidsSameUser(msgKey.participant || msgKey.remoteJid!, meId)
// if the message being reacted to, was from them
// fromMe automatically becomes false
: false
: // if the message being reacted to, was from them
// fromMe automatically becomes false
false
// set the remoteJid to being the same as the chat the message came from
msgKey.remoteJid = message.key.remoteJid
// set participant of the message
@@ -67,33 +76,26 @@ export const isRealMessage = (message: proto.IWebMessageInfo, meId: string) => {
const normalizedContent = normalizeMessageContent(message.message)
const hasSomeContent = !!getContentType(normalizedContent)
return (
!!normalizedContent
|| REAL_MSG_STUB_TYPES.has(message.messageStubType!)
|| (
REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType!)
&& message.messageStubParameters?.some(p => areJidsSameUser(meId, p))
)
(!!normalizedContent ||
REAL_MSG_STUB_TYPES.has(message.messageStubType!) ||
(REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType!) &&
message.messageStubParameters?.some(p => areJidsSameUser(meId, p)))) &&
hasSomeContent &&
!normalizedContent?.protocolMessage &&
!normalizedContent?.reactionMessage &&
!normalizedContent?.pollUpdateMessage
)
&& hasSomeContent
&& !normalizedContent?.protocolMessage
&& !normalizedContent?.reactionMessage
&& !normalizedContent?.pollUpdateMessage
}
export const shouldIncrementChatUnread = (message: proto.IWebMessageInfo) => (
export const shouldIncrementChatUnread = (message: proto.IWebMessageInfo) =>
!message.key.fromMe && !message.messageStubType
)
/**
* Get the ID of the chat from the given key.
* Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
*/
export const getChatId = ({ remoteJid, participant, fromMe }: proto.IMessageKey) => {
if(
isJidBroadcast(remoteJid!)
&& !isJidStatusBroadcast(remoteJid!)
&& !fromMe
) {
if (isJidBroadcast(remoteJid!) && !isJidStatusBroadcast(remoteJid!) && !fromMe) {
return participant!
}
@@ -119,22 +121,15 @@ type PollContext = {
*/
export function decryptPollVote(
{ encPayload, encIv }: proto.Message.IPollEncValue,
{
pollCreatorJid,
pollMsgId,
pollEncKey,
voterJid,
}: PollContext
{ pollCreatorJid, pollMsgId, pollEncKey, voterJid }: PollContext
) {
const sign = Buffer.concat(
[
toBinary(pollMsgId),
toBinary(pollCreatorJid),
toBinary(voterJid),
toBinary('Poll Vote'),
new Uint8Array([1])
]
)
const sign = Buffer.concat([
toBinary(pollMsgId),
toBinary(pollCreatorJid),
toBinary(voterJid),
toBinary('Poll Vote'),
new Uint8Array([1])
])
const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
const decKey = hmacSign(sign, key0, 'sha256')
@@ -148,17 +143,9 @@ export function decryptPollVote(
}
}
const processMessage = async(
const processMessage = async (
message: proto.IWebMessageInfo,
{
shouldProcessHistoryMsg,
placeholderResendCache,
ev,
creds,
keyStore,
logger,
options
}: ProcessMessageContext
{ shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options }: ProcessMessageContext
) => {
const meId = creds.me!.id
const { accountSettings } = creds
@@ -166,11 +153,11 @@ const processMessage = async(
const chat: Partial<Chat> = { id: jidNormalizedUser(getChatId(message.key)) }
const isRealMsg = isRealMessage(message, meId)
if(isRealMsg) {
if (isRealMsg) {
chat.messages = [{ message }]
chat.conversationTimestamp = toNumber(message.messageTimestamp)
// only increment unread count if not CIPHERTEXT and from another person
if(shouldIncrementChatUnread(message)) {
if (shouldIncrementChatUnread(message)) {
chat.unreadCount = (chat.unreadCount || 0) + 1
}
}
@@ -179,63 +166,56 @@ const processMessage = async(
// unarchive chat if it's a real message, or someone reacted to our message
// and we've the unarchive chats setting on
if(
(isRealMsg || content?.reactionMessage?.key?.fromMe)
&& accountSettings?.unarchiveChats
) {
if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
chat.archived = false
chat.readOnly = false
}
const protocolMsg = content?.protocolMessage
if(protocolMsg) {
if (protocolMsg) {
switch (protocolMsg.type) {
case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
const histNotification = protocolMsg.historySyncNotification!
const process = shouldProcessHistoryMsg
const isLatest = !creds.processedHistoryMessages?.length
case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
const histNotification = protocolMsg.historySyncNotification!
const process = shouldProcessHistoryMsg
const isLatest = !creds.processedHistoryMessages?.length
logger?.info({
histNotification,
process,
id: message.key.id,
isLatest,
}, 'got history notification')
logger?.info(
{
histNotification,
process,
id: message.key.id,
isLatest
},
'got history notification'
)
if(process) {
if(histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
ev.emit('creds.update', {
processedHistoryMessages: [
...(creds.processedHistoryMessages || []),
{ key: message.key, messageTimestamp: message.messageTimestamp }
]
if (process) {
if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
ev.emit('creds.update', {
processedHistoryMessages: [
...(creds.processedHistoryMessages || []),
{ key: message.key, messageTimestamp: message.messageTimestamp }
]
})
}
const data = await downloadAndProcessHistorySyncNotification(histNotification, options)
ev.emit('messaging-history.set', {
...data,
isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
})
}
const data = await downloadAndProcessHistorySyncNotification(
histNotification,
options
)
ev.emit('messaging-history.set', {
...data,
isLatest:
histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND
? isLatest
: undefined,
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
})
}
break
case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
const keys = protocolMsg.appStateSyncKeyShare!.keys
if(keys?.length) {
let newAppStateSyncKeyId = ''
await keyStore.transaction(
async() => {
break
case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
const keys = protocolMsg.appStateSyncKeyShare!.keys
if (keys?.length) {
let newAppStateSyncKeyId = ''
await keyStore.transaction(async () => {
const newKeys: string[] = []
for(const { keyData, keyId } of keys) {
for (const { keyData, keyId } of keys) {
const strKeyId = Buffer.from(keyId!.keyId!).toString('base64')
newKeys.push(strKeyId)
@@ -244,65 +224,59 @@ const processMessage = async(
newAppStateSyncKeyId = strKeyId
}
logger?.info(
{ newAppStateSyncKeyId, newKeys },
'injecting new app state sync keys'
)
}
)
logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
})
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
} else {
logger?.info({ protocolMsg }, 'recv app state sync with 0 keys')
}
break
case proto.Message.ProtocolMessage.Type.REVOKE:
ev.emit('messages.update', [
{
key: {
...message.key,
id: protocolMsg.key!.id
},
update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
} else {
logger?.info({ protocolMsg }, 'recv app state sync with 0 keys')
}
])
break
case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
Object.assign(chat, {
ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
ephemeralExpiration: protocolMsg.ephemeralExpiration || null
})
break
case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
const response = protocolMsg.peerDataOperationRequestResponseMessage!
if(response) {
placeholderResendCache?.del(response.stanzaId!)
// TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
const { peerDataOperationResult } = response
for(const result of peerDataOperationResult!) {
const { placeholderMessageResendResponse: retryResponse } = result
//eslint-disable-next-line max-depth
if(retryResponse) {
const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes!)
// wait till another upsert event is available, don't want it to be part of the PDO response message
setTimeout(() => {
ev.emit('messages.upsert', {
messages: [webMessageInfo],
type: 'notify',
requestId: response.stanzaId!
})
}, 500)
}
}
}
case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
ev.emit(
'messages.update',
[
break
case proto.Message.ProtocolMessage.Type.REVOKE:
ev.emit('messages.update', [
{
// flip the sender / fromMe properties because they're in the perspective of the sender
key: {
...message.key,
id: protocolMsg.key!.id
},
update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
}
])
break
case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
Object.assign(chat, {
ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
ephemeralExpiration: protocolMsg.ephemeralExpiration || null
})
break
case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
const response = protocolMsg.peerDataOperationRequestResponseMessage!
if (response) {
placeholderResendCache?.del(response.stanzaId!)
// TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
const { peerDataOperationResult } = response
for (const result of peerDataOperationResult!) {
const { placeholderMessageResendResponse: retryResponse } = result
//eslint-disable-next-line max-depth
if (retryResponse) {
const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes!)
// wait till another upsert event is available, don't want it to be part of the PDO response message
setTimeout(() => {
ev.emit('messages.upsert', {
messages: [webMessageInfo],
type: 'notify',
requestId: response.stanzaId!
})
}, 500)
}
}
}
case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
ev.emit('messages.update', [
{
// flip the sender / fromMe properties because they're in the perspective of the sender
key: { ...message.key, id: protocolMsg.key?.id },
update: {
message: {
@@ -315,26 +289,26 @@ const processMessage = async(
: message.messageTimestamp
}
}
]
)
break
])
break
}
} else if(content?.reactionMessage) {
} else if (content?.reactionMessage) {
const reaction: proto.IReaction = {
...content.reactionMessage,
key: message.key,
key: message.key
}
ev.emit('messages.reaction', [{
reaction,
key: content.reactionMessage?.key!,
}])
} else if(message.messageStubType) {
ev.emit('messages.reaction', [
{
reaction,
key: content.reactionMessage?.key!
}
])
} else if (message.messageStubType) {
const jid = message.key?.remoteJid!
//let actor = whatsappID (message.participant)
let participants: string[]
const emitParticipantsUpdate = (action: ParticipantAction) => (
const emitParticipantsUpdate = (action: ParticipantAction) =>
ev.emit('group-participants.update', { id: jid, author: message.participant!, participants, action })
)
const emitGroupUpdate = (update: Partial<GroupMetadata>) => {
ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ?? undefined }])
}
@@ -346,76 +320,75 @@ const processMessage = async(
const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid))
switch (message.messageStubType) {
case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
participants = message.messageStubParameters || []
emitParticipantsUpdate('modify')
break
case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
participants = message.messageStubParameters || []
emitParticipantsUpdate('remove')
// mark the chat read only if you left the group
if(participantsIncludesMe()) {
chat.readOnly = true
}
case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
participants = message.messageStubParameters || []
emitParticipantsUpdate('modify')
break
case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
participants = message.messageStubParameters || []
emitParticipantsUpdate('remove')
// mark the chat read only if you left the group
if (participantsIncludesMe()) {
chat.readOnly = true
}
break
case WAMessageStubType.GROUP_PARTICIPANT_ADD:
case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
participants = message.messageStubParameters || []
if(participantsIncludesMe()) {
chat.readOnly = false
}
break
case WAMessageStubType.GROUP_PARTICIPANT_ADD:
case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
participants = message.messageStubParameters || []
if (participantsIncludesMe()) {
chat.readOnly = false
}
emitParticipantsUpdate('add')
break
case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
participants = message.messageStubParameters || []
emitParticipantsUpdate('demote')
break
case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
participants = message.messageStubParameters || []
emitParticipantsUpdate('promote')
break
case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
const announceValue = message.messageStubParameters?.[0]
emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
break
case WAMessageStubType.GROUP_CHANGE_RESTRICT:
const restrictValue = message.messageStubParameters?.[0]
emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
break
case WAMessageStubType.GROUP_CHANGE_SUBJECT:
const name = message.messageStubParameters?.[0]
chat.name = name
emitGroupUpdate({ subject: name })
break
case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
const description = message.messageStubParameters?.[0]
chat.description = description
emitGroupUpdate({ desc: description })
break
case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
const code = message.messageStubParameters?.[0]
emitGroupUpdate({ inviteCode: code })
break
case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
const memberAddValue = message.messageStubParameters?.[0]
emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
break
case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
const approvalMode = message.messageStubParameters?.[0]
emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
break
case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
const participant = message.messageStubParameters?.[0] as string
const action = message.messageStubParameters?.[1] as RequestJoinAction
const method = message.messageStubParameters?.[2] as RequestJoinMethod
emitGroupRequestJoin(participant, action, method)
break
emitParticipantsUpdate('add')
break
case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
participants = message.messageStubParameters || []
emitParticipantsUpdate('demote')
break
case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
participants = message.messageStubParameters || []
emitParticipantsUpdate('promote')
break
case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
const announceValue = message.messageStubParameters?.[0]
emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
break
case WAMessageStubType.GROUP_CHANGE_RESTRICT:
const restrictValue = message.messageStubParameters?.[0]
emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
break
case WAMessageStubType.GROUP_CHANGE_SUBJECT:
const name = message.messageStubParameters?.[0]
chat.name = name
emitGroupUpdate({ subject: name })
break
case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
const description = message.messageStubParameters?.[0]
chat.description = description
emitGroupUpdate({ desc: description })
break
case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
const code = message.messageStubParameters?.[0]
emitGroupUpdate({ inviteCode: code })
break
case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
const memberAddValue = message.messageStubParameters?.[0]
emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
break
case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
const approvalMode = message.messageStubParameters?.[0]
emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
break
case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
const participant = message.messageStubParameters?.[0] as string
const action = message.messageStubParameters?.[1] as RequestJoinAction
const method = message.messageStubParameters?.[2] as RequestJoinMethod
emitGroupRequestJoin(participant, action, method)
break
}
} /* else if(content?.pollUpdateMessage) {
const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
// we need to fetch the poll creation message to get the poll enc key
@@ -466,7 +439,7 @@ const processMessage = async(
}
} */
if(Object.keys(chat).length > 1) {
if (Object.keys(chat).length > 1) {
ev.emit('chats.update', [chat])
}
}