Cleanup + add remaining utils

This commit is contained in:
Adhiraj Singh
2021-07-12 23:50:08 +05:30
parent 89cf8004e9
commit 71e34fc5f8
15 changed files with 234 additions and 74 deletions

View File

@@ -3,8 +3,7 @@ import EventEmitter from "events"
import * as Curve from 'curve25519-js'
import { BaileysEventEmitter, BaileysEventMap, SocketConfig, CurveKeyPair, WAInitResponse, ConnectionState, DisconnectReason } from "../Types"
import { makeSocket } from "./socket"
import { generateClientID, promiseTimeout } from "../Utils/generics"
import { normalizedAuthInfo, computeChallengeResponse, validateNewConnection } from "../Utils/validate-connection"
import { generateClientID, promiseTimeout, normalizedAuthInfo, computeChallengeResponse, validateNewConnection } from "../Utils"
import { randomBytes } from "crypto"
import { AuthenticationCredentials } from "../Types"
@@ -106,7 +105,7 @@ const makeAuthSocket = (config: SocketConfig) => {
}
)
.finally(() => (
ev.off('state.update', listener)
ev.off('connection.update', listener)
))
)
}

View File

@@ -1,12 +1,15 @@
import { SocketConfig } from '../Types'
import { DEFAULT_CONNECTION_CONFIG } from '../Defaults'
import { EventEmitter } from 'events'
import * as Connection from './groups'
import _makeConnection from './groups'
// export the last socket layer
const makeConnection = (config: Partial<SocketConfig>) => (
Connection.default({
_makeConnection({
...DEFAULT_CONNECTION_CONFIG,
...config
})
)
export type Connection = ReturnType<typeof makeConnection>
export default makeConnection

View File

@@ -1,12 +1,10 @@
import BinaryNode from "../BinaryNode";
import { Boom } from '@hapi/boom'
import { EventEmitter } from 'events'
import { Chat, Presence, SocketConfig, WAMessage, WAMessageKey, ParticipantAction, WAMessageProto, WAMessageStatus, WAMessageStubType, GroupMetadata, AnyMessageContent, MiscMessageGenerationOptions, WAFlag, WAMetric, WAUrlInfo, MediaConnInfo, MessageUpdateType, MessageInfo } from "../Types";
import { isGroupID, toNumber, whatsappID } from "../Utils/generics";
import { Chat, Presence, WAMessageCursor, SocketConfig, WAMessage, WAMessageKey, ParticipantAction, WAMessageProto, WAMessageStatus, WAMessageStubType, GroupMetadata, AnyMessageContent, MiscMessageGenerationOptions, WAFlag, WAMetric, WAUrlInfo, MediaConnInfo, MessageUpdateType, MessageInfo } from "../Types";
import { isGroupID, toNumber, whatsappID, generateWAMessage, decryptMediaMessageBuffer } from "../Utils";
import makeChatsSocket from "./chats";
import { WA_DEFAULT_EPHEMERAL } from "../Defaults";
import { generateWAMessage } from "../Utils/messages";
import { decryptMediaMessageBuffer } from "../Utils/messages-media";
const STATUS_MAP = {
read: WAMessageStatus.READ,
@@ -47,9 +45,12 @@ const makeMessagesSocket = (config: SocketConfig) => {
const fetchMessagesFromWA = async(
jid: string,
count: number,
indexMessage?: { id?: string; fromMe?: boolean },
mostRecentFirst: boolean = true
cursor?: WAMessageCursor
) => {
let key: WAMessageKey
if(cursor) {
key = 'before' in cursor ? cursor.before : cursor.after
}
const { data }:BinaryNode = await query({
json: new BinaryNode(
'query',
@@ -57,10 +58,10 @@ const makeMessagesSocket = (config: SocketConfig) => {
epoch: currentEpoch().toString(),
type: 'message',
jid: jid,
kind: mostRecentFirst ? 'before' : 'after',
kind: !cursor || 'before' in cursor ? 'before' : 'after',
count: count.toString(),
index: indexMessage?.id,
owner: indexMessage?.fromMe === false ? 'false' : 'true',
index: key?.id,
owner: key?.fromMe === false ? 'false' : 'true',
}
),
binaryTag: [WAMetric.queryMessages, WAFlag.ignore],
@@ -91,7 +92,7 @@ const makeMessagesSocket = (config: SocketConfig) => {
})
Object.keys(response[1]).forEach (key => content[key] = response[1][key]) // update message
ev.emit('messages.upsert', { messages: [message], type: 'append' })
ev.emit('messages.update', [{ key: message.key, message: message.message }])
return response
}
@@ -365,6 +366,18 @@ const makeMessagesSocket = (config: SocketConfig) => {
},
updateMediaMessage,
fetchMessagesFromWA,
/** Load a single message specified by the ID */
loadMessageFromWA: async(jid: string, id: string) => {
let message: WAMessage
// load the message before the given message
let messages = (await fetchMessagesFromWA(jid, 1, { before: {id, fromMe: true} }))
if(!messages[0]) messages = (await fetchMessagesFromWA(jid, 1, { before: {id, fromMe: false} }))
// the message after the loaded message is the message required
const [actual] = await fetchMessagesFromWA(jid, 1, { after: messages[0] && messages[0].key })
message = actual
return message
},
searchMessages: async(txt: string, inJid: string | null, count: number, page: number) => {
const {data, attributes}: BinaryNode = await query({
json: new BinaryNode(
@@ -419,10 +432,6 @@ const makeMessagesSocket = (config: SocketConfig) => {
{
...options,
userJid: userJid,
/*ephemeralOptions: chat?.ephemeral ? {
expiration: chat.ephemeral,
eph_setting_ts: chat.eph_setting_ts
} : undefined,*/
getUrlInfo: generateUrlInfo,
getMediaOptions: refreshMediaConn
}

View File

@@ -5,8 +5,7 @@ import { promisify } from "util"
import WebSocket from "ws"
import BinaryNode from "../BinaryNode"
import { DisconnectReason, SocketConfig, SocketQueryOptions, SocketSendMessageOptions } from "../Types"
import { aesEncrypt, hmacSign, promiseTimeout, unixTimestampSeconds } from "../Utils/generics"
import { decodeWAMessage } from "../Utils/decode-wa-message"
import { aesEncrypt, hmacSign, promiseTimeout, unixTimestampSeconds, decodeWAMessage } from "../Utils"
import { WAFlag, WAMetric, WATag } from "../Types"
import { DEFAULT_ORIGIN, DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, PHONE_CONNECTION_CB } from "../Defaults"