chore: make APIs similar for legacy + MD

This commit is contained in:
Adhiraj Singh
2021-12-18 16:44:31 +05:30
parent c803e22e8a
commit e393f0f9a8
7 changed files with 33 additions and 30 deletions

View File

@@ -22,7 +22,7 @@ const startSock = () => {
await sock.sendPresenceUpdate('paused', jid) await sock.sendPresenceUpdate('paused', jid)
await sock.sendWAMessage(jid, msg) await sock.sendMessage(jid, msg)
} }
sock.ev.on('messages.upsert', async m => { sock.ev.on('messages.upsert', async m => {

View File

@@ -64,7 +64,7 @@ const makeAuthSocket = (config: LegacySocketConfig) => {
*/ */
const logout = async() => { const logout = async() => {
if(state.connection === 'open') { if(state.connection === 'open') {
await socket.sendMessage({ await socket.sendNode({
json: ['admin', 'Conn', 'disconnect'], json: ['admin', 'Conn', 'disconnect'],
tag: 'goodbye' tag: 'goodbye'
}) })
@@ -178,7 +178,7 @@ const makeAuthSocket = (config: LegacySocketConfig) => {
return return
} }
logger.info('sending login request') logger.info('sending login request')
socket.sendMessage({ socket.sendNode({
json, json,
tag: loginTag tag: loginTag
}) })

View File

@@ -12,14 +12,14 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
currentEpoch, currentEpoch,
setQuery, setQuery,
query, query,
sendMessage, sendNode,
getState getState
} = sock } = sock
const chatsDebounceTimeout = debouncedTimeout(10_000, () => sendChatsQuery(1)) const chatsDebounceTimeout = debouncedTimeout(10_000, () => sendChatsQuery(1))
const sendChatsQuery = (epoch: number) => ( const sendChatsQuery = (epoch: number) => (
sendMessage({ sendNode({
json: { json: {
tag: 'query', tag: 'query',
attrs: {type: 'chat', epoch: epoch.toString()} attrs: {type: 'chat', epoch: epoch.toString()}
@@ -108,27 +108,27 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
if(connection !== 'open') return if(connection !== 'open') return
try { try {
await Promise.all([ await Promise.all([
sendMessage({ sendNode({
json: { tag: 'query', attrs: {type: 'contacts', epoch: '1'} }, json: { tag: 'query', attrs: {type: 'contacts', epoch: '1'} },
binaryTag: [ WAMetric.queryContact, WAFlag.ignore ] binaryTag: [ WAMetric.queryContact, WAFlag.ignore ]
}), }),
sendMessage({ sendNode({
json: { tag: 'query', attrs: {type: 'status', epoch: '1'} }, json: { tag: 'query', attrs: {type: 'status', epoch: '1'} },
binaryTag: [ WAMetric.queryStatus, WAFlag.ignore ] binaryTag: [ WAMetric.queryStatus, WAFlag.ignore ]
}), }),
sendMessage({ sendNode({
json: { tag: 'query', attrs: {type: 'quick_reply', epoch: '1'} }, json: { tag: 'query', attrs: {type: 'quick_reply', epoch: '1'} },
binaryTag: [ WAMetric.queryQuickReply, WAFlag.ignore ] binaryTag: [ WAMetric.queryQuickReply, WAFlag.ignore ]
}), }),
sendMessage({ sendNode({
json: { tag: 'query', attrs: {type: 'label', epoch: '1'} }, json: { tag: 'query', attrs: {type: 'label', epoch: '1'} },
binaryTag: [ WAMetric.queryLabel, WAFlag.ignore ] binaryTag: [ WAMetric.queryLabel, WAFlag.ignore ]
}), }),
sendMessage({ sendNode({
json: { tag: 'query', attrs: {type: 'emoji', epoch: '1'} }, json: { tag: 'query', attrs: {type: 'emoji', epoch: '1'} },
binaryTag: [ WAMetric.queryEmoji, WAFlag.ignore ] binaryTag: [ WAMetric.queryEmoji, WAFlag.ignore ]
}), }),
sendMessage({ sendNode({
json: { json: {
tag: 'action', tag: 'action',
attrs: { type: 'set', epoch: '1' }, attrs: { type: 'set', epoch: '1' },
@@ -206,7 +206,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
const update: Partial<Chat> = { const update: Partial<Chat> = {
id: jidNormalizedUser(attrs.jid) id: jidNormalizedUser(attrs.jid)
} }
if (attrs.type === 'false') update.unreadCount = -1 if(attrs.type === 'false') update.unreadCount = -1
else update.unreadCount = 0 else update.unreadCount = 0
ev.emit('chats.update', [update]) ev.emit('chats.update', [update])
@@ -277,7 +277,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
* Modify a given chat (archive, pin etc.) * Modify a given chat (archive, pin etc.)
* @param jid the ID of the person/group you are modifiying * @param jid the ID of the person/group you are modifiying
*/ */
modifyChat: async(jid: string, modification: ChatModification, chatInfo: Pick<Chat, 'mute' | 'pin'>, index?: WAMessageKey) => { chatModify: async( modification: ChatModification, jid: string, chatInfo: Pick<Chat, 'mute' | 'pin'>, index?: WAMessageKey) => {
let chatAttrs: BinaryNode['attrs'] = { jid: jid } let chatAttrs: BinaryNode['attrs'] = { jid: jid }
let data: BinaryNode[] | undefined = undefined let data: BinaryNode[] | undefined = undefined
const stamp = unixTimestampSeconds() const stamp = unixTimestampSeconds()
@@ -335,12 +335,12 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
* @param str phone number/jid you want to check for * @param str phone number/jid you want to check for
* @returns undefined if the number doesn't exists, otherwise the correctly formatted jid * @returns undefined if the number doesn't exists, otherwise the correctly formatted jid
*/ */
isOnWhatsApp: async (str: string) => { onWhatsApp: async(str: string) => {
const { status, jid, biz } = await query({ const { status, jid, biz } = await query({
json: ['query', 'exist', str], json: ['query', 'exist', str],
requiresPhoneConnection: false requiresPhoneConnection: false
}) })
if (status === 200) { if(status === 200) {
return { return {
exists: true, exists: true,
jid: jidNormalizedUser(jid), jid: jidNormalizedUser(jid),
@@ -354,7 +354,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
* @param type your presence * @param type your presence
*/ */
sendPresenceUpdate: ( type: WAPresence, jid: string | undefined) => ( sendPresenceUpdate: ( type: WAPresence, jid: string | undefined) => (
sendMessage({ sendNode({
binaryTag: [WAMetric.presence, WAFlag[type]], // weird stuff WA does binaryTag: [WAMetric.presence, WAFlag[type]], // weird stuff WA does
json: { json: {
tag: 'action', tag: 'action',
@@ -373,7 +373,7 @@ const makeChatsSocket = (config: LegacySocketConfig) => {
* this returns nothing, you'll receive updates in chats.update event * this returns nothing, you'll receive updates in chats.update event
* */ * */
presenceSubscribe: async (jid: string) => ( presenceSubscribe: async (jid: string) => (
sendMessage({ json: ['action', 'presence', 'subscribe', jid] }) sendNode({ json: ['action', 'presence', 'subscribe', jid] })
), ),
/** Query the status of the person (see groupMetadata() for groups) */ /** Query the status of the person (see groupMetadata() for groups) */
getStatus: async(jid: string) => { getStatus: async(jid: string) => {

View File

@@ -224,7 +224,7 @@ const makeGroupsSocket = (config: LegacySocketConfig) => {
} }
return metadata return metadata
}, },
inviteCode: async(jid: string) => { groupInviteCode: async(jid: string) => {
const response = await sock.query({ const response = await sock.query({
json: ['query', 'inviteCode', jid], json: ['query', 'inviteCode', jid],
expect200: true, expect200: true,

View File

@@ -249,7 +249,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
} }
/** Relay (send) a WAMessage; more advanced functionality to send a built WA Message, you may want to stick with sendMessage() */ /** Relay (send) a WAMessage; more advanced functionality to send a built WA Message, you may want to stick with sendMessage() */
const relayWAMessage = async(message: WAMessage, { waitForAck } = { waitForAck: true }) => { const relayMessage = async(message: WAMessage, { waitForAck } = { waitForAck: true }) => {
const json: BinaryNode = { const json: BinaryNode = {
tag: 'action', tag: 'action',
attrs: { epoch: currentEpoch().toString(), type: 'relay' }, attrs: { epoch: currentEpoch().toString(), type: 'relay' },
@@ -388,13 +388,18 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
return { return {
...sock, ...sock,
relayWAMessage, relayMessage,
generateUrlInfo, generateUrlInfo,
messageInfo: async(jid: string, messageID: string) => { messageInfo: async(jid: string, messageID: string) => {
const { content }: BinaryNode = await query({ const { content }: BinaryNode = await query({
json: { json: {
tag: 'query', tag: 'query',
attrs: {type: 'message_info', index: messageID, jid: jid, epoch: currentEpoch().toString()} attrs: {
type: 'message_info',
index: messageID,
jid: jid,
epoch: currentEpoch().toString()
}
}, },
binaryTag: [WAMetric.queryRead, WAFlag.ignore], binaryTag: [WAMetric.queryRead, WAFlag.ignore],
expect200: true, expect200: true,
@@ -419,7 +424,6 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
return info return info
}, },
downloadMediaMessage: async(message: WAMessage, type: 'buffer' | 'stream' = 'buffer') => { downloadMediaMessage: async(message: WAMessage, type: 'buffer' | 'stream' = 'buffer') => {
const downloadMediaMessage = async () => { const downloadMediaMessage = async () => {
let mContent = extractMessageContent(message.message) let mContent = extractMessageContent(message.message)
if (!mContent) throw new Boom('No message present', { statusCode: 400, data: message }) if (!mContent) throw new Boom('No message present', { statusCode: 400, data: message })
@@ -486,7 +490,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
messages: getBinaryNodeMessages(node) messages: getBinaryNodeMessages(node)
} }
}, },
sendWAMessage: async( sendMessage: async(
jid: string, jid: string,
content: AnyMessageContent, content: AnyMessageContent,
options: MiscMessageGenerationOptions & { waitForAck?: boolean } = { waitForAck: true } options: MiscMessageGenerationOptions & { waitForAck?: boolean } = { waitForAck: true }
@@ -526,7 +530,7 @@ const makeMessagesSocket = (config: LegacySocketConfig) => {
} }
) )
await relayWAMessage(msg, { waitForAck: options.waitForAck }) await relayMessage(msg, { waitForAck: options.waitForAck })
return msg return msg
} }
} }

View File

@@ -62,7 +62,7 @@ export const makeSocket = ({
* Send a message to the WA servers * Send a message to the WA servers
* @returns the tag attached in the message * @returns the tag attached in the message
* */ * */
const sendMessage = async( const sendNode = async(
{ json, binaryTag, tag, longTag }: SocketSendMessageOptions { json, binaryTag, tag, longTag }: SocketSendMessageOptions
) => { ) => {
tag = tag || generateMessageTag(longTag) tag = tag || generateMessageTag(longTag)
@@ -204,7 +204,7 @@ export const makeSocket = ({
} }
} }
/** checks for phone connection */ /** checks for phone connection */
const sendAdminTest = () => sendMessage({ json: ['admin', 'test'] }) const sendAdminTest = () => sendNode({ json: ['admin', 'test'] })
/** /**
* Wait for a message with a certain tag to be received * Wait for a message with a certain tag to be received
* @param tag the message tag to await * @param tag the message tag to await
@@ -266,7 +266,7 @@ export const makeSocket = ({
tag = tag || generateMessageTag(longTag) tag = tag || generateMessageTag(longTag)
const { promise, cancelToken } = waitForMessage(tag, requiresPhoneConnection, timeoutMs) const { promise, cancelToken } = waitForMessage(tag, requiresPhoneConnection, timeoutMs)
try { try {
await sendMessage({ json, tag, binaryTag }) await sendNode({ json, tag, binaryTag })
} catch(error) { } catch(error) {
cancelToken() cancelToken()
// swallow error // swallow error
@@ -366,8 +366,7 @@ export const makeSocket = ({
ws, ws,
updateKeys: (info: { encKey: Buffer, macKey: Buffer }) => authInfo = info, updateKeys: (info: { encKey: Buffer, macKey: Buffer }) => authInfo = info,
waitForSocketOpen, waitForSocketOpen,
sendRawMessage, sendNode,
sendMessage,
generateMessageTag, generateMessageTag,
waitForMessage, waitForMessage,
query, query,

View File

@@ -124,7 +124,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
const inviteNode = getBinaryNodeChild(result, 'invite') const inviteNode = getBinaryNodeChild(result, 'invite')
return inviteNode.attrs.code return inviteNode.attrs.code
}, },
groupRevokeInvite: async (jid: string) => { groupRevokeInvite: async (jid: string) => {
const result = await groupQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]) const result = await groupQuery(jid, 'set', [{ tag: 'invite', attrs: {} }])
const inviteNode = getBinaryNodeChild(result, 'invite') const inviteNode = getBinaryNodeChild(result, 'invite')
return inviteNode.attrs.code return inviteNode.attrs.code