mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
chore: format everything
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
lib
|
lib
|
||||||
coverage
|
coverage
|
||||||
*.lock
|
*.lock
|
||||||
|
*.json
|
||||||
src/WABinary/index.ts
|
src/WABinary/index.ts
|
||||||
WAProto
|
WAProto
|
||||||
WASignalGroup
|
WASignalGroup
|
||||||
|
|||||||
@@ -30,8 +30,9 @@
|
|||||||
"changelog:update": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
|
"changelog:update": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
|
||||||
"example": "node --inspect -r ts-node/register Example/example.ts",
|
"example": "node --inspect -r ts-node/register Example/example.ts",
|
||||||
"gen:protobuf": "sh WAProto/GenerateStatics.sh",
|
"gen:protobuf": "sh WAProto/GenerateStatics.sh",
|
||||||
|
"format": "prettier --write \"src/**/*.{ts,js,json,md}\"",
|
||||||
"lint": "eslint src --ext .js,.ts",
|
"lint": "eslint src --ext .js,.ts",
|
||||||
"lint:fix": "yarn lint --fix",
|
"lint:fix": "yarn format && yarn lint --fix",
|
||||||
"prepack": "tsc",
|
"prepack": "tsc",
|
||||||
"prepare": "tsc",
|
"prepare": "tsc",
|
||||||
"preinstall": "node ./engine-requirements.js",
|
"preinstall": "node ./engine-requirements.js",
|
||||||
|
|||||||
@@ -17,14 +17,12 @@ export const WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60
|
|||||||
export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0'
|
export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0'
|
||||||
export const DICT_VERSION = 2
|
export const DICT_VERSION = 2
|
||||||
export const KEY_BUNDLE_TYPE = Buffer.from([5])
|
export const KEY_BUNDLE_TYPE = Buffer.from([5])
|
||||||
export const NOISE_WA_HEADER = Buffer.from(
|
export const NOISE_WA_HEADER = Buffer.from([87, 65, 6, DICT_VERSION]) // last is "DICT_VERSION"
|
||||||
[ 87, 65, 6, DICT_VERSION ]
|
|
||||||
) // last is "DICT_VERSION"
|
|
||||||
/** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
|
/** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
|
||||||
export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g
|
export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g
|
||||||
|
|
||||||
export const WA_CERT_DETAILS = {
|
export const WA_CERT_DETAILS = {
|
||||||
SERIAL: 0,
|
SERIAL: 0
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PROCESSABLE_HISTORY_TYPES = [
|
export const PROCESSABLE_HISTORY_TYPES = [
|
||||||
@@ -32,7 +30,7 @@ export const PROCESSABLE_HISTORY_TYPES = [
|
|||||||
proto.Message.HistorySyncNotification.HistorySyncType.PUSH_NAME,
|
proto.Message.HistorySyncNotification.HistorySyncType.PUSH_NAME,
|
||||||
proto.Message.HistorySyncNotification.HistorySyncType.RECENT,
|
proto.Message.HistorySyncNotification.HistorySyncType.RECENT,
|
||||||
proto.Message.HistorySyncNotification.HistorySyncType.FULL,
|
proto.Message.HistorySyncNotification.HistorySyncType.FULL,
|
||||||
proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND,
|
proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND
|
||||||
]
|
]
|
||||||
|
|
||||||
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
||||||
@@ -57,14 +55,14 @@ export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
|||||||
linkPreviewImageThumbnailWidth: 192,
|
linkPreviewImageThumbnailWidth: 192,
|
||||||
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
|
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
|
||||||
generateHighQualityLinkPreview: false,
|
generateHighQualityLinkPreview: false,
|
||||||
options: { },
|
options: {},
|
||||||
appStateMacVerification: {
|
appStateMacVerification: {
|
||||||
patch: false,
|
patch: false,
|
||||||
snapshot: false,
|
snapshot: false
|
||||||
},
|
},
|
||||||
countryCode: 'US',
|
countryCode: 'US',
|
||||||
getMessage: async() => undefined,
|
getMessage: async () => undefined,
|
||||||
cachedGroupMetadata: async() => undefined,
|
cachedGroupMetadata: async () => undefined,
|
||||||
makeSignalRepository: makeLibSignalRepository
|
makeSignalRepository: makeLibSignalRepository
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,19 +75,19 @@ export const MEDIA_PATH_MAP: { [T in MediaType]?: string } = {
|
|||||||
'thumbnail-link': '/mms/image',
|
'thumbnail-link': '/mms/image',
|
||||||
'product-catalog-image': '/product/image',
|
'product-catalog-image': '/product/image',
|
||||||
'md-app-state': '',
|
'md-app-state': '',
|
||||||
'md-msg-hist': '/mms/md-app-state',
|
'md-msg-hist': '/mms/md-app-state'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MEDIA_HKDF_KEY_MAPPING = {
|
export const MEDIA_HKDF_KEY_MAPPING = {
|
||||||
'audio': 'Audio',
|
audio: 'Audio',
|
||||||
'document': 'Document',
|
document: 'Document',
|
||||||
'gif': 'Video',
|
gif: 'Video',
|
||||||
'image': 'Image',
|
image: 'Image',
|
||||||
'ppic': '',
|
ppic: '',
|
||||||
'product': 'Image',
|
product: 'Image',
|
||||||
'ptt': 'Audio',
|
ptt: 'Audio',
|
||||||
'sticker': 'Image',
|
sticker: 'Image',
|
||||||
'video': 'Video',
|
video: 'Video',
|
||||||
'thumbnail-document': 'Document Thumbnail',
|
'thumbnail-document': 'Document Thumbnail',
|
||||||
'thumbnail-image': 'Image Thumbnail',
|
'thumbnail-image': 'Image Thumbnail',
|
||||||
'thumbnail-video': 'Video Thumbnail',
|
'thumbnail-video': 'Video Thumbnail',
|
||||||
@@ -98,7 +96,7 @@ export const MEDIA_HKDF_KEY_MAPPING = {
|
|||||||
'md-app-state': 'App State',
|
'md-app-state': 'App State',
|
||||||
'product-catalog-image': '',
|
'product-catalog-image': '',
|
||||||
'payment-bg-image': 'Payment Background',
|
'payment-bg-image': 'Payment Background',
|
||||||
'ptv': 'Video'
|
ptv: 'Video'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP) as MediaType[]
|
export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP) as MediaType[]
|
||||||
@@ -111,5 +109,5 @@ export const DEFAULT_CACHE_TTLS = {
|
|||||||
SIGNAL_STORE: 5 * 60, // 5 minutes
|
SIGNAL_STORE: 5 * 60, // 5 minutes
|
||||||
MSG_RETRY: 60 * 60, // 1 hour
|
MSG_RETRY: 60 * 60, // 1 hour
|
||||||
CALL_OFFER: 5 * 60, // 5 minutes
|
CALL_OFFER: 5 * 60, // 5 minutes
|
||||||
USER_DEVICES: 5 * 60, // 5 minutes
|
USER_DEVICES: 5 * 60 // 5 minutes
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import * as libsignal from 'libsignal'
|
import * as libsignal from 'libsignal'
|
||||||
import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage, SenderKeyName, SenderKeyRecord } from '../../WASignalGroup'
|
import {
|
||||||
|
GroupCipher,
|
||||||
|
GroupSessionBuilder,
|
||||||
|
SenderKeyDistributionMessage,
|
||||||
|
SenderKeyName,
|
||||||
|
SenderKeyRecord
|
||||||
|
} from '../../WASignalGroup'
|
||||||
import { SignalAuthState } from '../Types'
|
import { SignalAuthState } from '../Types'
|
||||||
import { SignalRepository } from '../Types/Signal'
|
import { SignalRepository } from '../Types/Signal'
|
||||||
import { generateSignalPubKey } from '../Utils'
|
import { generateSignalPubKey } from '../Utils'
|
||||||
@@ -18,9 +24,15 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
|||||||
const builder = new GroupSessionBuilder(storage)
|
const builder = new GroupSessionBuilder(storage)
|
||||||
const senderName = jidToSignalSenderKeyName(item.groupId!, authorJid)
|
const senderName = jidToSignalSenderKeyName(item.groupId!, authorJid)
|
||||||
|
|
||||||
const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage)
|
const senderMsg = new SenderKeyDistributionMessage(
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
item.axolotlSenderKeyDistributionMessage
|
||||||
|
)
|
||||||
const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
|
const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
|
||||||
if(!senderKey) {
|
if (!senderKey) {
|
||||||
await storage.storeSenderKey(senderName, new SenderKeyRecord())
|
await storage.storeSenderKey(senderName, new SenderKeyRecord())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +66,7 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
|||||||
const builder = new GroupSessionBuilder(storage)
|
const builder = new GroupSessionBuilder(storage)
|
||||||
|
|
||||||
const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
|
const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
|
||||||
if(!senderKey) {
|
if (!senderKey) {
|
||||||
await storage.storeSenderKey(senderName, new SenderKeyRecord())
|
await storage.storeSenderKey(senderName, new SenderKeyRecord())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,7 +76,7 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
ciphertext,
|
ciphertext,
|
||||||
senderKeyDistributionMessage: senderKeyDistributionMessage.serialize(),
|
senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async injectE2ESession({ jid, session }) {
|
async injectE2ESession({ jid, session }) {
|
||||||
@@ -73,7 +85,7 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
|||||||
},
|
},
|
||||||
jidToSignalProtocolAddress(jid) {
|
jidToSignalProtocolAddress(jid) {
|
||||||
return jidToSignalProtocolAddress(jid).toString()
|
return jidToSignalProtocolAddress(jid).toString()
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,22 +100,22 @@ const jidToSignalSenderKeyName = (group: string, user: string): string => {
|
|||||||
|
|
||||||
function signalStorage({ creds, keys }: SignalAuthState) {
|
function signalStorage({ creds, keys }: SignalAuthState) {
|
||||||
return {
|
return {
|
||||||
loadSession: async(id: string) => {
|
loadSession: async (id: string) => {
|
||||||
const { [id]: sess } = await keys.get('session', [id])
|
const { [id]: sess } = await keys.get('session', [id])
|
||||||
if(sess) {
|
if (sess) {
|
||||||
return libsignal.SessionRecord.deserialize(sess)
|
return libsignal.SessionRecord.deserialize(sess)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
storeSession: async(id, session) => {
|
storeSession: async (id, session) => {
|
||||||
await keys.set({ 'session': { [id]: session.serialize() } })
|
await keys.set({ session: { [id]: session.serialize() } })
|
||||||
},
|
},
|
||||||
isTrustedIdentity: () => {
|
isTrustedIdentity: () => {
|
||||||
return true
|
return true
|
||||||
},
|
},
|
||||||
loadPreKey: async(id: number | string) => {
|
loadPreKey: async (id: number | string) => {
|
||||||
const keyId = id.toString()
|
const keyId = id.toString()
|
||||||
const { [keyId]: key } = await keys.get('pre-key', [keyId])
|
const { [keyId]: key } = await keys.get('pre-key', [keyId])
|
||||||
if(key) {
|
if (key) {
|
||||||
return {
|
return {
|
||||||
privKey: Buffer.from(key.private),
|
privKey: Buffer.from(key.private),
|
||||||
pubKey: Buffer.from(key.public)
|
pubKey: Buffer.from(key.public)
|
||||||
@@ -118,23 +130,21 @@ function signalStorage({ creds, keys }: SignalAuthState) {
|
|||||||
pubKey: Buffer.from(key.keyPair.public)
|
pubKey: Buffer.from(key.keyPair.public)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
loadSenderKey: async(keyId: string) => {
|
loadSenderKey: async (keyId: string) => {
|
||||||
const { [keyId]: key } = await keys.get('sender-key', [keyId])
|
const { [keyId]: key } = await keys.get('sender-key', [keyId])
|
||||||
if(key) {
|
if (key) {
|
||||||
return new SenderKeyRecord(key)
|
return new SenderKeyRecord(key)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
storeSenderKey: async(keyId, key) => {
|
storeSenderKey: async (keyId, key) => {
|
||||||
await keys.set({ 'sender-key': { [keyId]: key.serialize() } })
|
await keys.set({ 'sender-key': { [keyId]: key.serialize() } })
|
||||||
},
|
},
|
||||||
getOurRegistrationId: () => (
|
getOurRegistrationId: () => creds.registrationId,
|
||||||
creds.registrationId
|
|
||||||
),
|
|
||||||
getOurIdentity: () => {
|
getOurIdentity: () => {
|
||||||
const { signedIdentityKey } = creds
|
const { signedIdentityKey } = creds
|
||||||
return {
|
return {
|
||||||
privKey: Buffer.from(signedIdentityKey.private),
|
privKey: Buffer.from(signedIdentityKey.private),
|
||||||
pubKey: generateSignalPubKey(signedIdentityKey.public),
|
pubKey: generateSignalPubKey(signedIdentityKey.public)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,12 +8,15 @@ export abstract class AbstractSocketClient extends EventEmitter {
|
|||||||
abstract get isClosing(): boolean
|
abstract get isClosing(): boolean
|
||||||
abstract get isConnecting(): boolean
|
abstract get isConnecting(): boolean
|
||||||
|
|
||||||
constructor(public url: URL, public config: SocketConfig) {
|
constructor(
|
||||||
|
public url: URL,
|
||||||
|
public config: SocketConfig
|
||||||
|
) {
|
||||||
super()
|
super()
|
||||||
this.setMaxListeners(0)
|
this.setMaxListeners(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract connect(): Promise<void>
|
abstract connect(): Promise<void>
|
||||||
abstract close(): Promise<void>
|
abstract close(): Promise<void>
|
||||||
abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean;
|
abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,6 @@ import { DEFAULT_ORIGIN } from '../../Defaults'
|
|||||||
import { AbstractSocketClient } from './types'
|
import { AbstractSocketClient } from './types'
|
||||||
|
|
||||||
export class WebSocketClient extends AbstractSocketClient {
|
export class WebSocketClient extends AbstractSocketClient {
|
||||||
|
|
||||||
protected socket: WebSocket | null = null
|
protected socket: WebSocket | null = null
|
||||||
|
|
||||||
get isOpen(): boolean {
|
get isOpen(): boolean {
|
||||||
@@ -20,7 +19,7 @@ export class WebSocketClient extends AbstractSocketClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async connect(): Promise<void> {
|
async connect(): Promise<void> {
|
||||||
if(this.socket) {
|
if (this.socket) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,20 +28,20 @@ export class WebSocketClient extends AbstractSocketClient {
|
|||||||
headers: this.config.options?.headers as {},
|
headers: this.config.options?.headers as {},
|
||||||
handshakeTimeout: this.config.connectTimeoutMs,
|
handshakeTimeout: this.config.connectTimeoutMs,
|
||||||
timeout: this.config.connectTimeoutMs,
|
timeout: this.config.connectTimeoutMs,
|
||||||
agent: this.config.agent,
|
agent: this.config.agent
|
||||||
})
|
})
|
||||||
|
|
||||||
this.socket.setMaxListeners(0)
|
this.socket.setMaxListeners(0)
|
||||||
|
|
||||||
const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response']
|
const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response']
|
||||||
|
|
||||||
for(const event of events) {
|
for (const event of events) {
|
||||||
this.socket?.on(event, (...args: any[]) => this.emit(event, ...args))
|
this.socket?.on(event, (...args: any[]) => this.emit(event, ...args))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async close(): Promise<void> {
|
async close(): Promise<void> {
|
||||||
if(!this.socket) {
|
if (!this.socket) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,43 +1,46 @@
|
|||||||
import { GetCatalogOptions, ProductCreate, ProductUpdate, SocketConfig } from '../Types'
|
import { GetCatalogOptions, ProductCreate, ProductUpdate, SocketConfig } from '../Types'
|
||||||
import { parseCatalogNode, parseCollectionsNode, parseOrderDetailsNode, parseProductNode, toProductNode, uploadingNecessaryImagesOfProduct } from '../Utils/business'
|
import {
|
||||||
|
parseCatalogNode,
|
||||||
|
parseCollectionsNode,
|
||||||
|
parseOrderDetailsNode,
|
||||||
|
parseProductNode,
|
||||||
|
toProductNode,
|
||||||
|
uploadingNecessaryImagesOfProduct
|
||||||
|
} from '../Utils/business'
|
||||||
import { BinaryNode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary'
|
import { BinaryNode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary'
|
||||||
import { getBinaryNodeChild } from '../WABinary/generic-utils'
|
import { getBinaryNodeChild } from '../WABinary/generic-utils'
|
||||||
import { makeMessagesRecvSocket } from './messages-recv'
|
import { makeMessagesRecvSocket } from './messages-recv'
|
||||||
|
|
||||||
export const makeBusinessSocket = (config: SocketConfig) => {
|
export const makeBusinessSocket = (config: SocketConfig) => {
|
||||||
const sock = makeMessagesRecvSocket(config)
|
const sock = makeMessagesRecvSocket(config)
|
||||||
const {
|
const { authState, query, waUploadToServer } = sock
|
||||||
authState,
|
|
||||||
query,
|
|
||||||
waUploadToServer
|
|
||||||
} = sock
|
|
||||||
|
|
||||||
const getCatalog = async({ jid, limit, cursor }: GetCatalogOptions) => {
|
const getCatalog = async ({ jid, limit, cursor }: GetCatalogOptions) => {
|
||||||
jid = jid || authState.creds.me?.id
|
jid = jid || authState.creds.me?.id
|
||||||
jid = jidNormalizedUser(jid)
|
jid = jidNormalizedUser(jid)
|
||||||
|
|
||||||
const queryParamNodes: BinaryNode[] = [
|
const queryParamNodes: BinaryNode[] = [
|
||||||
{
|
{
|
||||||
tag: 'limit',
|
tag: 'limit',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from((limit || 10).toString())
|
content: Buffer.from((limit || 10).toString())
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'width',
|
tag: 'width',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from('100')
|
content: Buffer.from('100')
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'height',
|
tag: 'height',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from('100')
|
content: Buffer.from('100')
|
||||||
},
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
if(cursor) {
|
if (cursor) {
|
||||||
queryParamNodes.push({
|
queryParamNodes.push({
|
||||||
tag: 'after',
|
tag: 'after',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: cursor
|
content: cursor
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -54,7 +57,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
tag: 'product_catalog',
|
tag: 'product_catalog',
|
||||||
attrs: {
|
attrs: {
|
||||||
jid,
|
jid,
|
||||||
'allow_shop_source': 'true'
|
allow_shop_source: 'true'
|
||||||
},
|
},
|
||||||
content: queryParamNodes
|
content: queryParamNodes
|
||||||
}
|
}
|
||||||
@@ -63,7 +66,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
return parseCatalogNode(result)
|
return parseCatalogNode(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
const getCollections = async(jid?: string, limit = 51) => {
|
const getCollections = async (jid?: string, limit = 51) => {
|
||||||
jid = jid || authState.creds.me?.id
|
jid = jid || authState.creds.me?.id
|
||||||
jid = jidNormalizedUser(jid)
|
jid = jidNormalizedUser(jid)
|
||||||
const result = await query({
|
const result = await query({
|
||||||
@@ -72,33 +75,33 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'get',
|
type: 'get',
|
||||||
xmlns: 'w:biz:catalog',
|
xmlns: 'w:biz:catalog',
|
||||||
'smax_id': '35'
|
smax_id: '35'
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'collections',
|
tag: 'collections',
|
||||||
attrs: {
|
attrs: {
|
||||||
'biz_jid': jid,
|
biz_jid: jid
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'collection_limit',
|
tag: 'collection_limit',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(limit.toString())
|
content: Buffer.from(limit.toString())
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'item_limit',
|
tag: 'item_limit',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(limit.toString())
|
content: Buffer.from(limit.toString())
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'width',
|
tag: 'width',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from('100')
|
content: Buffer.from('100')
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'height',
|
tag: 'height',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from('100')
|
content: Buffer.from('100')
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -109,14 +112,14 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
return parseCollectionsNode(result)
|
return parseCollectionsNode(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
const getOrderDetails = async(orderId: string, tokenBase64: string) => {
|
const getOrderDetails = async (orderId: string, tokenBase64: string) => {
|
||||||
const result = await query({
|
const result = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'get',
|
type: 'get',
|
||||||
xmlns: 'fb:thrift_iq',
|
xmlns: 'fb:thrift_iq',
|
||||||
'smax_id': '5'
|
smax_id: '5'
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
@@ -128,23 +131,23 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'image_dimensions',
|
tag: 'image_dimensions',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'width',
|
tag: 'width',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from('100')
|
content: Buffer.from('100')
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'height',
|
tag: 'height',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from('100')
|
content: Buffer.from('100')
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'token',
|
tag: 'token',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(tokenBase64)
|
content: Buffer.from(tokenBase64)
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -155,7 +158,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
return parseOrderDetailsNode(result)
|
return parseOrderDetailsNode(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
const productUpdate = async(productId: string, update: ProductUpdate) => {
|
const productUpdate = async (productId: string, update: ProductUpdate) => {
|
||||||
update = await uploadingNecessaryImagesOfProduct(update, waUploadToServer)
|
update = await uploadingNecessaryImagesOfProduct(update, waUploadToServer)
|
||||||
const editNode = toProductNode(productId, update)
|
const editNode = toProductNode(productId, update)
|
||||||
|
|
||||||
@@ -174,12 +177,12 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
editNode,
|
editNode,
|
||||||
{
|
{
|
||||||
tag: 'width',
|
tag: 'width',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: '100'
|
content: '100'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'height',
|
tag: 'height',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: '100'
|
content: '100'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -193,7 +196,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
return parseProductNode(productNode!)
|
return parseProductNode(productNode!)
|
||||||
}
|
}
|
||||||
|
|
||||||
const productCreate = async(create: ProductCreate) => {
|
const productCreate = async (create: ProductCreate) => {
|
||||||
// ensure isHidden is defined
|
// ensure isHidden is defined
|
||||||
create.isHidden = !!create.isHidden
|
create.isHidden = !!create.isHidden
|
||||||
create = await uploadingNecessaryImagesOfProduct(create, waUploadToServer)
|
create = await uploadingNecessaryImagesOfProduct(create, waUploadToServer)
|
||||||
@@ -214,12 +217,12 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
createNode,
|
createNode,
|
||||||
{
|
{
|
||||||
tag: 'width',
|
tag: 'width',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: '100'
|
content: '100'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'height',
|
tag: 'height',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: '100'
|
content: '100'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -233,7 +236,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
return parseProductNode(productNode!)
|
return parseProductNode(productNode!)
|
||||||
}
|
}
|
||||||
|
|
||||||
const productDelete = async(productIds: string[]) => {
|
const productDelete = async (productIds: string[]) => {
|
||||||
const result = await query({
|
const result = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
@@ -245,19 +248,17 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
|||||||
{
|
{
|
||||||
tag: 'product_catalog_delete',
|
tag: 'product_catalog_delete',
|
||||||
attrs: { v: '1' },
|
attrs: { v: '1' },
|
||||||
content: productIds.map(
|
content: productIds.map(id => ({
|
||||||
id => ({
|
|
||||||
tag: 'product',
|
tag: 'product',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'id',
|
tag: 'id',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(id)
|
content: Buffer.from(id)
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
}))
|
||||||
)
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,62 +1,70 @@
|
|||||||
import { proto } from '../../WAProto'
|
import { proto } from '../../WAProto'
|
||||||
import { GroupMetadata, GroupParticipant, ParticipantAction, SocketConfig, WAMessageKey, WAMessageStubType } from '../Types'
|
import {
|
||||||
|
GroupMetadata,
|
||||||
|
GroupParticipant,
|
||||||
|
ParticipantAction,
|
||||||
|
SocketConfig,
|
||||||
|
WAMessageKey,
|
||||||
|
WAMessageStubType
|
||||||
|
} from '../Types'
|
||||||
import { generateMessageIDV2, unixTimestampSeconds } from '../Utils'
|
import { generateMessageIDV2, unixTimestampSeconds } from '../Utils'
|
||||||
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, jidEncode, jidNormalizedUser } from '../WABinary'
|
import {
|
||||||
|
BinaryNode,
|
||||||
|
getBinaryNodeChild,
|
||||||
|
getBinaryNodeChildren,
|
||||||
|
getBinaryNodeChildString,
|
||||||
|
jidEncode,
|
||||||
|
jidNormalizedUser
|
||||||
|
} from '../WABinary'
|
||||||
import { makeChatsSocket } from './chats'
|
import { makeChatsSocket } from './chats'
|
||||||
|
|
||||||
export const makeGroupsSocket = (config: SocketConfig) => {
|
export const makeGroupsSocket = (config: SocketConfig) => {
|
||||||
const sock = makeChatsSocket(config)
|
const sock = makeChatsSocket(config)
|
||||||
const { authState, ev, query, upsertMessage } = sock
|
const { authState, ev, query, upsertMessage } = sock
|
||||||
|
|
||||||
const groupQuery = async(jid: string, type: 'get' | 'set', content: BinaryNode[]) => (
|
const groupQuery = async (jid: string, type: 'get' | 'set', content: BinaryNode[]) =>
|
||||||
query({
|
query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
type,
|
type,
|
||||||
xmlns: 'w:g2',
|
xmlns: 'w:g2',
|
||||||
to: jid,
|
to: jid
|
||||||
},
|
},
|
||||||
content
|
content
|
||||||
})
|
})
|
||||||
)
|
|
||||||
|
|
||||||
const groupMetadata = async(jid: string) => {
|
const groupMetadata = async (jid: string) => {
|
||||||
const result = await groupQuery(
|
const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
|
||||||
jid,
|
|
||||||
'get',
|
|
||||||
[ { tag: 'query', attrs: { request: 'interactive' } } ]
|
|
||||||
)
|
|
||||||
return extractGroupMetadata(result)
|
return extractGroupMetadata(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const groupFetchAllParticipating = async () => {
|
||||||
const groupFetchAllParticipating = async() => {
|
|
||||||
const result = await query({
|
const result = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
to: '@g.us',
|
to: '@g.us',
|
||||||
xmlns: 'w:g2',
|
xmlns: 'w:g2',
|
||||||
type: 'get',
|
type: 'get'
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'participating',
|
tag: 'participating',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{ tag: 'participants', attrs: { } },
|
{ tag: 'participants', attrs: {} },
|
||||||
{ tag: 'description', attrs: { } }
|
{ tag: 'description', attrs: {} }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
const data: { [_: string]: GroupMetadata } = { }
|
const data: { [_: string]: GroupMetadata } = {}
|
||||||
const groupsChild = getBinaryNodeChild(result, 'groups')
|
const groupsChild = getBinaryNodeChild(result, 'groups')
|
||||||
if(groupsChild) {
|
if (groupsChild) {
|
||||||
const groups = getBinaryNodeChildren(groupsChild, 'group')
|
const groups = getBinaryNodeChildren(groupsChild, 'group')
|
||||||
for(const groupNode of groups) {
|
for (const groupNode of groups) {
|
||||||
const meta = extractGroupMetadata({
|
const meta = extractGroupMetadata({
|
||||||
tag: 'result',
|
tag: 'result',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [groupNode]
|
content: [groupNode]
|
||||||
})
|
})
|
||||||
data[meta.id] = meta
|
data[meta.id] = meta
|
||||||
@@ -68,9 +76,9 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
sock.ws.on('CB:ib,,dirty', async(node: BinaryNode) => {
|
sock.ws.on('CB:ib,,dirty', async (node: BinaryNode) => {
|
||||||
const { attrs } = getBinaryNodeChild(node, 'dirty')!
|
const { attrs } = getBinaryNodeChild(node, 'dirty')!
|
||||||
if(attrs.type !== 'groups') {
|
if (attrs.type !== 'groups') {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,12 +89,9 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
return {
|
return {
|
||||||
...sock,
|
...sock,
|
||||||
groupMetadata,
|
groupMetadata,
|
||||||
groupCreate: async(subject: string, participants: string[]) => {
|
groupCreate: async (subject: string, participants: string[]) => {
|
||||||
const key = generateMessageIDV2()
|
const key = generateMessageIDV2()
|
||||||
const result = await groupQuery(
|
const result = await groupQuery('@g.us', 'set', [
|
||||||
'@g.us',
|
|
||||||
'set',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
tag: 'create',
|
tag: 'create',
|
||||||
attrs: {
|
attrs: {
|
||||||
@@ -98,72 +103,55 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
attrs: { jid }
|
attrs: { jid }
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
|
||||||
return extractGroupMetadata(result)
|
return extractGroupMetadata(result)
|
||||||
},
|
},
|
||||||
groupLeave: async(id: string) => {
|
groupLeave: async (id: string) => {
|
||||||
await groupQuery(
|
await groupQuery('@g.us', 'set', [
|
||||||
'@g.us',
|
|
||||||
'set',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
tag: 'leave',
|
tag: 'leave',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [{ tag: 'group', attrs: { id } }]
|
||||||
{ tag: 'group', attrs: { id } }
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
|
||||||
},
|
},
|
||||||
groupUpdateSubject: async(jid: string, subject: string) => {
|
groupUpdateSubject: async (jid: string, subject: string) => {
|
||||||
await groupQuery(
|
await groupQuery(jid, 'set', [
|
||||||
jid,
|
|
||||||
'set',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
tag: 'subject',
|
tag: 'subject',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(subject, 'utf-8')
|
content: Buffer.from(subject, 'utf-8')
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
|
||||||
},
|
},
|
||||||
groupRequestParticipantsList: async(jid: string) => {
|
groupRequestParticipantsList: async (jid: string) => {
|
||||||
const result = await groupQuery(
|
const result = await groupQuery(jid, 'get', [
|
||||||
jid,
|
|
||||||
'get',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
tag: 'membership_approval_requests',
|
tag: 'membership_approval_requests',
|
||||||
attrs: {}
|
attrs: {}
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
|
||||||
const node = getBinaryNodeChild(result, 'membership_approval_requests')
|
const node = getBinaryNodeChild(result, 'membership_approval_requests')
|
||||||
const participants = getBinaryNodeChildren(node, 'membership_approval_request')
|
const participants = getBinaryNodeChildren(node, 'membership_approval_request')
|
||||||
return participants.map(v => v.attrs)
|
return participants.map(v => v.attrs)
|
||||||
},
|
},
|
||||||
groupRequestParticipantsUpdate: async(jid: string, participants: string[], action: 'approve' | 'reject') => {
|
groupRequestParticipantsUpdate: async (jid: string, participants: string[], action: 'approve' | 'reject') => {
|
||||||
const result = await groupQuery(
|
const result = await groupQuery(jid, 'set', [
|
||||||
jid,
|
{
|
||||||
'set',
|
|
||||||
[{
|
|
||||||
tag: 'membership_requests_action',
|
tag: 'membership_requests_action',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: action,
|
tag: action,
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: participants.map(jid => ({
|
content: participants.map(jid => ({
|
||||||
tag: 'participant',
|
tag: 'participant',
|
||||||
attrs: { jid }
|
attrs: { jid }
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}]
|
}
|
||||||
)
|
])
|
||||||
const node = getBinaryNodeChild(result, 'membership_requests_action')
|
const node = getBinaryNodeChild(result, 'membership_requests_action')
|
||||||
const nodeAction = getBinaryNodeChild(node, action)
|
const nodeAction = getBinaryNodeChild(node, action)
|
||||||
const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant')
|
const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant')
|
||||||
@@ -171,63 +159,49 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
return { status: p.attrs.error || '200', jid: p.attrs.jid }
|
return { status: p.attrs.error || '200', jid: p.attrs.jid }
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
groupParticipantsUpdate: async(
|
groupParticipantsUpdate: async (jid: string, participants: string[], action: ParticipantAction) => {
|
||||||
jid: string,
|
const result = await groupQuery(jid, 'set', [
|
||||||
participants: string[],
|
|
||||||
action: ParticipantAction
|
|
||||||
) => {
|
|
||||||
const result = await groupQuery(
|
|
||||||
jid,
|
|
||||||
'set',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
tag: action,
|
tag: action,
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: participants.map(jid => ({
|
content: participants.map(jid => ({
|
||||||
tag: 'participant',
|
tag: 'participant',
|
||||||
attrs: { jid }
|
attrs: { jid }
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
|
||||||
const node = getBinaryNodeChild(result, action)
|
const node = getBinaryNodeChild(result, action)
|
||||||
const participantsAffected = getBinaryNodeChildren(node, 'participant')
|
const participantsAffected = getBinaryNodeChildren(node, 'participant')
|
||||||
return participantsAffected.map(p => {
|
return participantsAffected.map(p => {
|
||||||
return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p }
|
return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p }
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
groupUpdateDescription: async(jid: string, description?: string) => {
|
groupUpdateDescription: async (jid: string, description?: string) => {
|
||||||
const metadata = await groupMetadata(jid)
|
const metadata = await groupMetadata(jid)
|
||||||
const prev = metadata.descId ?? null
|
const prev = metadata.descId ?? null
|
||||||
|
|
||||||
await groupQuery(
|
await groupQuery(jid, 'set', [
|
||||||
jid,
|
|
||||||
'set',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
tag: 'description',
|
tag: 'description',
|
||||||
attrs: {
|
attrs: {
|
||||||
...(description ? { id: generateMessageIDV2() } : { delete: 'true' }),
|
...(description ? { id: generateMessageIDV2() } : { delete: 'true' }),
|
||||||
...(prev ? { prev } : {})
|
...(prev ? { prev } : {})
|
||||||
},
|
},
|
||||||
content: description ? [
|
content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
|
||||||
{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }
|
|
||||||
] : undefined
|
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
|
||||||
},
|
},
|
||||||
groupInviteCode: async(jid: string) => {
|
groupInviteCode: async (jid: string) => {
|
||||||
const result = await groupQuery(jid, 'get', [{ tag: 'invite', attrs: {} }])
|
const result = await groupQuery(jid, 'get', [{ tag: 'invite', attrs: {} }])
|
||||||
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
|
||||||
},
|
},
|
||||||
groupAcceptInvite: async(code: string) => {
|
groupAcceptInvite: async (code: string) => {
|
||||||
const results = await groupQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }])
|
const results = await groupQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }])
|
||||||
const result = getBinaryNodeChild(results, 'group')
|
const result = getBinaryNodeChild(results, 'group')
|
||||||
return result?.attrs.jid
|
return result?.attrs.jid
|
||||||
@@ -239,8 +213,10 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
* @param invitedJid jid of person you invited
|
* @param invitedJid jid of person you invited
|
||||||
* @returns true if successful
|
* @returns true if successful
|
||||||
*/
|
*/
|
||||||
groupRevokeInviteV4: async(groupJid: string, invitedJid: string) => {
|
groupRevokeInviteV4: async (groupJid: string, invitedJid: string) => {
|
||||||
const result = await groupQuery(groupJid, 'set', [{ tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }])
|
const result = await groupQuery(groupJid, 'set', [
|
||||||
|
{ tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
|
||||||
|
])
|
||||||
return !!result
|
return !!result
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -249,20 +225,23 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
* @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
|
* @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
|
||||||
* @param inviteMessage the message to accept
|
* @param inviteMessage the message to accept
|
||||||
*/
|
*/
|
||||||
groupAcceptInviteV4: ev.createBufferedFunction(async(key: string | WAMessageKey, inviteMessage: proto.Message.IGroupInviteMessage) => {
|
groupAcceptInviteV4: ev.createBufferedFunction(
|
||||||
|
async (key: string | WAMessageKey, inviteMessage: proto.Message.IGroupInviteMessage) => {
|
||||||
key = typeof key === 'string' ? { remoteJid: key } : key
|
key = typeof key === 'string' ? { remoteJid: key } : key
|
||||||
const results = await groupQuery(inviteMessage.groupJid!, 'set', [{
|
const results = await groupQuery(inviteMessage.groupJid!, 'set', [
|
||||||
|
{
|
||||||
tag: 'accept',
|
tag: 'accept',
|
||||||
attrs: {
|
attrs: {
|
||||||
code: inviteMessage.inviteCode!,
|
code: inviteMessage.inviteCode!,
|
||||||
expiration: inviteMessage.inviteExpiration!.toString(),
|
expiration: inviteMessage.inviteExpiration!.toString(),
|
||||||
admin: key.remoteJid!
|
admin: key.remoteJid!
|
||||||
}
|
}
|
||||||
}])
|
}
|
||||||
|
])
|
||||||
|
|
||||||
// if we have the full message key
|
// if we have the full message key
|
||||||
// update the invite message to be expired
|
// update the invite message to be expired
|
||||||
if(key.id) {
|
if (key.id) {
|
||||||
// create new invite message that is expired
|
// create new invite message that is expired
|
||||||
inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage)
|
inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage)
|
||||||
inviteMessage.inviteExpiration = 0
|
inviteMessage.inviteExpiration = 0
|
||||||
@@ -286,12 +265,10 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
remoteJid: inviteMessage.groupJid,
|
remoteJid: inviteMessage.groupJid,
|
||||||
id: generateMessageIDV2(sock.user?.id),
|
id: generateMessageIDV2(sock.user?.id),
|
||||||
fromMe: false,
|
fromMe: false,
|
||||||
participant: key.remoteJid,
|
participant: key.remoteJid
|
||||||
},
|
},
|
||||||
messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
|
messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
|
||||||
messageStubParameters: [
|
messageStubParameters: [authState.creds.me!.id],
|
||||||
authState.creds.me!.id
|
|
||||||
],
|
|
||||||
participant: key.remoteJid,
|
participant: key.remoteJid,
|
||||||
messageTimestamp: unixTimestampSeconds()
|
messageTimestamp: unixTimestampSeconds()
|
||||||
},
|
},
|
||||||
@@ -299,37 +276,39 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
return results.attrs.from
|
return results.attrs.from
|
||||||
}),
|
}
|
||||||
groupGetInviteInfo: async(code: string) => {
|
),
|
||||||
|
groupGetInviteInfo: async (code: string) => {
|
||||||
const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
|
const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
|
||||||
return extractGroupMetadata(results)
|
return extractGroupMetadata(results)
|
||||||
},
|
},
|
||||||
groupToggleEphemeral: async(jid: string, ephemeralExpiration: number) => {
|
groupToggleEphemeral: async (jid: string, ephemeralExpiration: number) => {
|
||||||
const content: BinaryNode = ephemeralExpiration ?
|
const content: BinaryNode = ephemeralExpiration
|
||||||
{ tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } } :
|
? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
|
||||||
{ tag: 'not_ephemeral', attrs: { } }
|
: { tag: 'not_ephemeral', attrs: {} }
|
||||||
await groupQuery(jid, 'set', [content])
|
await groupQuery(jid, 'set', [content])
|
||||||
},
|
},
|
||||||
groupSettingUpdate: async(jid: string, setting: 'announcement' | 'not_announcement' | 'locked' | 'unlocked') => {
|
groupSettingUpdate: async (jid: string, setting: 'announcement' | 'not_announcement' | 'locked' | 'unlocked') => {
|
||||||
await groupQuery(jid, 'set', [ { tag: setting, attrs: { } } ])
|
await groupQuery(jid, 'set', [{ tag: setting, attrs: {} }])
|
||||||
},
|
},
|
||||||
groupMemberAddMode: async(jid: string, mode: 'admin_add' | 'all_member_add') => {
|
groupMemberAddMode: async (jid: string, mode: 'admin_add' | 'all_member_add') => {
|
||||||
await groupQuery(jid, 'set', [ { tag: 'member_add_mode', attrs: { }, content: mode } ])
|
await groupQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }])
|
||||||
},
|
},
|
||||||
groupJoinApprovalMode: async(jid: string, mode: 'on' | 'off') => {
|
groupJoinApprovalMode: async (jid: string, mode: 'on' | 'off') => {
|
||||||
await groupQuery(jid, 'set', [ { tag: 'membership_approval_mode', attrs: { }, content: [ { tag: 'group_join', attrs: { state: mode } } ] } ])
|
await groupQuery(jid, 'set', [
|
||||||
|
{ tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'group_join', attrs: { state: mode } }] }
|
||||||
|
])
|
||||||
},
|
},
|
||||||
groupFetchAllParticipating
|
groupFetchAllParticipating
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const extractGroupMetadata = (result: BinaryNode) => {
|
export const extractGroupMetadata = (result: BinaryNode) => {
|
||||||
const group = getBinaryNodeChild(result, 'group')!
|
const group = getBinaryNodeChild(result, 'group')!
|
||||||
const descChild = getBinaryNodeChild(group, 'description')
|
const descChild = getBinaryNodeChild(group, 'description')
|
||||||
let desc: string | undefined
|
let desc: string | undefined
|
||||||
let descId: string | undefined
|
let descId: string | undefined
|
||||||
if(descChild) {
|
if (descChild) {
|
||||||
desc = getBinaryNodeChildString(descChild, 'body')
|
desc = getBinaryNodeChildString(descChild, 'body')
|
||||||
descId = descChild.attrs.id
|
descId = descChild.attrs.id
|
||||||
}
|
}
|
||||||
@@ -355,14 +334,12 @@ export const extractGroupMetadata = (result: BinaryNode) => {
|
|||||||
isCommunityAnnounce: !!getBinaryNodeChild(group, 'default_sub_group'),
|
isCommunityAnnounce: !!getBinaryNodeChild(group, 'default_sub_group'),
|
||||||
joinApprovalMode: !!getBinaryNodeChild(group, 'membership_approval_mode'),
|
joinApprovalMode: !!getBinaryNodeChild(group, 'membership_approval_mode'),
|
||||||
memberAddMode,
|
memberAddMode,
|
||||||
participants: getBinaryNodeChildren(group, 'participant').map(
|
participants: getBinaryNodeChildren(group, 'participant').map(({ attrs }) => {
|
||||||
({ attrs }) => {
|
|
||||||
return {
|
return {
|
||||||
id: attrs.jid,
|
id: attrs.jid,
|
||||||
admin: (attrs.type || null) as GroupParticipant['admin'],
|
admin: (attrs.type || null) as GroupParticipant['admin']
|
||||||
}
|
}
|
||||||
}
|
}),
|
||||||
),
|
|
||||||
ephemeralDuration: eph ? +eph : undefined
|
ephemeralDuration: eph ? +eph : undefined
|
||||||
}
|
}
|
||||||
return metadata
|
return metadata
|
||||||
|
|||||||
@@ -3,11 +3,10 @@ import { UserFacingSocketConfig } from '../Types'
|
|||||||
import { makeBusinessSocket } from './business'
|
import { makeBusinessSocket } from './business'
|
||||||
|
|
||||||
// export the last socket layer
|
// export the last socket layer
|
||||||
const makeWASocket = (config: UserFacingSocketConfig) => (
|
const makeWASocket = (config: UserFacingSocketConfig) =>
|
||||||
makeBusinessSocket({
|
makeBusinessSocket({
|
||||||
...DEFAULT_CONNECTION_CONFIG,
|
...DEFAULT_CONNECTION_CONFIG,
|
||||||
...config
|
...config
|
||||||
})
|
})
|
||||||
)
|
|
||||||
|
|
||||||
export default makeWASocket
|
export default makeWASocket
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,49 @@
|
|||||||
|
|
||||||
import NodeCache from '@cacheable/node-cache'
|
import NodeCache from '@cacheable/node-cache'
|
||||||
import { Boom } from '@hapi/boom'
|
import { Boom } from '@hapi/boom'
|
||||||
import { proto } from '../../WAProto'
|
import { proto } from '../../WAProto'
|
||||||
import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults'
|
import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults'
|
||||||
import { AnyMessageContent, MediaConnInfo, MessageReceiptType, MessageRelayOptions, MiscMessageGenerationOptions, SocketConfig, WAMessageKey } from '../Types'
|
import {
|
||||||
import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils'
|
AnyMessageContent,
|
||||||
|
MediaConnInfo,
|
||||||
|
MessageReceiptType,
|
||||||
|
MessageRelayOptions,
|
||||||
|
MiscMessageGenerationOptions,
|
||||||
|
SocketConfig,
|
||||||
|
WAMessageKey
|
||||||
|
} from '../Types'
|
||||||
|
import {
|
||||||
|
aggregateMessageKeysNotFromMe,
|
||||||
|
assertMediaContent,
|
||||||
|
bindWaitForEvent,
|
||||||
|
decryptMediaRetryData,
|
||||||
|
encodeSignedDeviceIdentity,
|
||||||
|
encodeWAMessage,
|
||||||
|
encryptMediaRetryRequest,
|
||||||
|
extractDeviceJids,
|
||||||
|
generateMessageIDV2,
|
||||||
|
generateWAMessage,
|
||||||
|
getStatusCodeForMediaRetry,
|
||||||
|
getUrlFromDirectPath,
|
||||||
|
getWAUploadToServer,
|
||||||
|
normalizeMessageContent,
|
||||||
|
parseAndInjectE2ESessions,
|
||||||
|
unixTimestampSeconds
|
||||||
|
} from '../Utils'
|
||||||
import { getUrlInfo } from '../Utils/link-preview'
|
import { getUrlInfo } from '../Utils/link-preview'
|
||||||
import { areJidsSameUser, BinaryNode, BinaryNodeAttributes, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, isJidUser, jidDecode, jidEncode, jidNormalizedUser, JidWithDevice, S_WHATSAPP_NET } from '../WABinary'
|
import {
|
||||||
|
areJidsSameUser,
|
||||||
|
BinaryNode,
|
||||||
|
BinaryNodeAttributes,
|
||||||
|
getBinaryNodeChild,
|
||||||
|
getBinaryNodeChildren,
|
||||||
|
isJidGroup,
|
||||||
|
isJidUser,
|
||||||
|
jidDecode,
|
||||||
|
jidEncode,
|
||||||
|
jidNormalizedUser,
|
||||||
|
JidWithDevice,
|
||||||
|
S_WHATSAPP_NET
|
||||||
|
} from '../WABinary'
|
||||||
import { USyncQuery, USyncUser } from '../WAUSync'
|
import { USyncQuery, USyncUser } from '../WAUSync'
|
||||||
import { makeGroupsSocket } from './groups'
|
import { makeGroupsSocket } from './groups'
|
||||||
|
|
||||||
@@ -17,7 +54,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
generateHighQualityLinkPreview,
|
generateHighQualityLinkPreview,
|
||||||
options: axiosOptions,
|
options: axiosOptions,
|
||||||
patchMessageBeforeSending,
|
patchMessageBeforeSending,
|
||||||
cachedGroupMetadata,
|
cachedGroupMetadata
|
||||||
} = config
|
} = config
|
||||||
const sock = makeGroupsSocket(config)
|
const sock = makeGroupsSocket(config)
|
||||||
const {
|
const {
|
||||||
@@ -30,36 +67,36 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
fetchPrivacySettings,
|
fetchPrivacySettings,
|
||||||
sendNode,
|
sendNode,
|
||||||
groupMetadata,
|
groupMetadata,
|
||||||
groupToggleEphemeral,
|
groupToggleEphemeral
|
||||||
} = sock
|
} = sock
|
||||||
|
|
||||||
const userDevicesCache = config.userDevicesCache || new NodeCache({
|
const userDevicesCache =
|
||||||
|
config.userDevicesCache ||
|
||||||
|
new NodeCache({
|
||||||
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
||||||
useClones: false
|
useClones: false
|
||||||
})
|
})
|
||||||
|
|
||||||
let mediaConn: Promise<MediaConnInfo>
|
let mediaConn: Promise<MediaConnInfo>
|
||||||
const refreshMediaConn = async(forceGet = false) => {
|
const refreshMediaConn = async (forceGet = false) => {
|
||||||
const media = await mediaConn
|
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() => {
|
mediaConn = (async () => {
|
||||||
const result = await query({
|
const result = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
type: 'set',
|
type: 'set',
|
||||||
xmlns: 'w:m',
|
xmlns: 'w:m',
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET
|
||||||
},
|
},
|
||||||
content: [ { tag: 'media_conn', attrs: { } } ]
|
content: [{ tag: 'media_conn', attrs: {} }]
|
||||||
})
|
})
|
||||||
const mediaConnNode = getBinaryNodeChild(result, 'media_conn')
|
const mediaConnNode = getBinaryNodeChild(result, 'media_conn')
|
||||||
const node: MediaConnInfo = {
|
const node: MediaConnInfo = {
|
||||||
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(
|
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
|
||||||
({ attrs }) => ({
|
|
||||||
hostname: attrs.hostname,
|
hostname: attrs.hostname,
|
||||||
maxContentLengthBytes: +attrs.maxContentLengthBytes,
|
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
||||||
})
|
})),
|
||||||
),
|
|
||||||
auth: mediaConnNode!.attrs.auth,
|
auth: mediaConnNode!.attrs.auth,
|
||||||
ttl: +mediaConnNode!.attrs.ttl,
|
ttl: +mediaConnNode!.attrs.ttl,
|
||||||
fetchDate: new Date()
|
fetchDate: new Date()
|
||||||
@@ -76,38 +113,43 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
* generic send receipt function
|
* generic send receipt function
|
||||||
* used for receipts of phone call, read, delivery etc.
|
* used for receipts of phone call, read, delivery etc.
|
||||||
* */
|
* */
|
||||||
const sendReceipt = async(jid: string, participant: string | undefined, messageIds: string[], type: MessageReceiptType) => {
|
const sendReceipt = async (
|
||||||
|
jid: string,
|
||||||
|
participant: string | undefined,
|
||||||
|
messageIds: string[],
|
||||||
|
type: MessageReceiptType
|
||||||
|
) => {
|
||||||
const node: BinaryNode = {
|
const node: BinaryNode = {
|
||||||
tag: 'receipt',
|
tag: 'receipt',
|
||||||
attrs: {
|
attrs: {
|
||||||
id: messageIds[0],
|
id: messageIds[0]
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
const isReadReceipt = type === 'read' || type === 'read-self'
|
const isReadReceipt = type === 'read' || type === 'read-self'
|
||||||
if(isReadReceipt) {
|
if (isReadReceipt) {
|
||||||
node.attrs.t = unixTimestampSeconds().toString()
|
node.attrs.t = unixTimestampSeconds().toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
if(type === 'sender' && isJidUser(jid)) {
|
if (type === 'sender' && isJidUser(jid)) {
|
||||||
node.attrs.recipient = jid
|
node.attrs.recipient = jid
|
||||||
node.attrs.to = participant!
|
node.attrs.to = participant!
|
||||||
} else {
|
} else {
|
||||||
node.attrs.to = jid
|
node.attrs.to = jid
|
||||||
if(participant) {
|
if (participant) {
|
||||||
node.attrs.participant = participant
|
node.attrs.participant = participant
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(type) {
|
if (type) {
|
||||||
node.attrs.type = type
|
node.attrs.type = type
|
||||||
}
|
}
|
||||||
|
|
||||||
const remainingMessageIds = messageIds.slice(1)
|
const remainingMessageIds = messageIds.slice(1)
|
||||||
if(remainingMessageIds.length) {
|
if (remainingMessageIds.length) {
|
||||||
node.content = [
|
node.content = [
|
||||||
{
|
{
|
||||||
tag: 'list',
|
tag: 'list',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: remainingMessageIds.map(id => ({
|
content: remainingMessageIds.map(id => ({
|
||||||
tag: 'item',
|
tag: 'item',
|
||||||
attrs: { id }
|
attrs: { id }
|
||||||
@@ -121,15 +163,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Correctly bulk send receipts to multiple chats, participants */
|
/** Correctly bulk send receipts to multiple chats, participants */
|
||||||
const sendReceipts = async(keys: WAMessageKey[], type: MessageReceiptType) => {
|
const sendReceipts = async (keys: WAMessageKey[], type: MessageReceiptType) => {
|
||||||
const recps = aggregateMessageKeysNotFromMe(keys)
|
const recps = aggregateMessageKeysNotFromMe(keys)
|
||||||
for(const { jid, participant, messageIds } of recps) {
|
for (const { jid, participant, messageIds } of recps) {
|
||||||
await sendReceipt(jid, participant, messageIds, type)
|
await sendReceipt(jid, participant, messageIds, type)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Bulk read messages. Keys can be from different chats & participants */
|
/** Bulk read messages. Keys can be from different chats & participants */
|
||||||
const readMessages = async(keys: WAMessageKey[]) => {
|
const readMessages = async (keys: WAMessageKey[]) => {
|
||||||
const privacySettings = await fetchPrivacySettings()
|
const privacySettings = await fetchPrivacySettings()
|
||||||
// based on privacy settings, we have to change the read type
|
// based on privacy settings, we have to change the read type
|
||||||
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
|
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
|
||||||
@@ -137,22 +179,22 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Fetch all the devices we've to send a message to */
|
/** Fetch all the devices we've to send a message to */
|
||||||
const getUSyncDevices = async(jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => {
|
const getUSyncDevices = async (jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => {
|
||||||
const deviceResults: JidWithDevice[] = []
|
const deviceResults: JidWithDevice[] = []
|
||||||
|
|
||||||
if(!useCache) {
|
if (!useCache) {
|
||||||
logger.debug('not using cache for devices')
|
logger.debug('not using cache for devices')
|
||||||
}
|
}
|
||||||
|
|
||||||
const toFetch: string[] = []
|
const toFetch: string[] = []
|
||||||
jids = Array.from(new Set(jids))
|
jids = Array.from(new Set(jids))
|
||||||
|
|
||||||
for(let jid of jids) {
|
for (let jid of jids) {
|
||||||
const user = jidDecode(jid)?.user
|
const user = jidDecode(jid)?.user
|
||||||
jid = jidNormalizedUser(jid)
|
jid = jidNormalizedUser(jid)
|
||||||
if(useCache) {
|
if (useCache) {
|
||||||
const devices = userDevicesCache.get<JidWithDevice[]>(user!)
|
const devices = userDevicesCache.get<JidWithDevice[]>(user!)
|
||||||
if(devices) {
|
if (devices) {
|
||||||
deviceResults.push(...devices)
|
deviceResults.push(...devices)
|
||||||
|
|
||||||
logger.trace({ user }, 'using cache for devices')
|
logger.trace({ user }, 'using cache for devices')
|
||||||
@@ -164,32 +206,30 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!toFetch.length) {
|
if (!toFetch.length) {
|
||||||
return deviceResults
|
return deviceResults
|
||||||
}
|
}
|
||||||
|
|
||||||
const query = new USyncQuery()
|
const query = new USyncQuery().withContext('message').withDeviceProtocol()
|
||||||
.withContext('message')
|
|
||||||
.withDeviceProtocol()
|
|
||||||
|
|
||||||
for(const jid of toFetch) {
|
for (const jid of toFetch) {
|
||||||
query.withUser(new USyncUser().withId(jid))
|
query.withUser(new USyncUser().withId(jid))
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await sock.executeUSyncQuery(query)
|
const result = await sock.executeUSyncQuery(query)
|
||||||
|
|
||||||
if(result) {
|
if (result) {
|
||||||
const extracted = extractDeviceJids(result?.list, authState.creds.me!.id, ignoreZeroDevices)
|
const extracted = extractDeviceJids(result?.list, authState.creds.me!.id, ignoreZeroDevices)
|
||||||
const deviceMap: { [_: string]: JidWithDevice[] } = {}
|
const deviceMap: { [_: string]: JidWithDevice[] } = {}
|
||||||
|
|
||||||
for(const item of extracted) {
|
for (const item of extracted) {
|
||||||
deviceMap[item.user] = deviceMap[item.user] || []
|
deviceMap[item.user] = deviceMap[item.user] || []
|
||||||
deviceMap[item.user].push(item)
|
deviceMap[item.user].push(item)
|
||||||
|
|
||||||
deviceResults.push(item)
|
deviceResults.push(item)
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const key in deviceMap) {
|
for (const key in deviceMap) {
|
||||||
userDevicesCache.set(key, deviceMap[key])
|
userDevicesCache.set(key, deviceMap[key])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -197,45 +237,39 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
return deviceResults
|
return deviceResults
|
||||||
}
|
}
|
||||||
|
|
||||||
const assertSessions = async(jids: string[], force: boolean) => {
|
const assertSessions = async (jids: string[], force: boolean) => {
|
||||||
let didFetchNewSession = false
|
let didFetchNewSession = false
|
||||||
let jidsRequiringFetch: string[] = []
|
let jidsRequiringFetch: string[] = []
|
||||||
if(force) {
|
if (force) {
|
||||||
jidsRequiringFetch = jids
|
jidsRequiringFetch = jids
|
||||||
} else {
|
} else {
|
||||||
const addrs = jids.map(jid => (
|
const addrs = jids.map(jid => signalRepository.jidToSignalProtocolAddress(jid))
|
||||||
signalRepository
|
|
||||||
.jidToSignalProtocolAddress(jid)
|
|
||||||
))
|
|
||||||
const sessions = await authState.keys.get('session', addrs)
|
const sessions = await authState.keys.get('session', addrs)
|
||||||
for(const jid of jids) {
|
for (const jid of jids) {
|
||||||
const signalId = signalRepository
|
const signalId = signalRepository.jidToSignalProtocolAddress(jid)
|
||||||
.jidToSignalProtocolAddress(jid)
|
if (!sessions[signalId]) {
|
||||||
if(!sessions[signalId]) {
|
|
||||||
jidsRequiringFetch.push(jid)
|
jidsRequiringFetch.push(jid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(jidsRequiringFetch.length) {
|
if (jidsRequiringFetch.length) {
|
||||||
logger.debug({ jidsRequiringFetch }, 'fetching sessions')
|
logger.debug({ jidsRequiringFetch }, 'fetching sessions')
|
||||||
const result = await query({
|
const result = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
xmlns: 'encrypt',
|
xmlns: 'encrypt',
|
||||||
type: 'get',
|
type: 'get',
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'key',
|
tag: 'key',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: jidsRequiringFetch.map(
|
content: jidsRequiringFetch.map(jid => ({
|
||||||
jid => ({
|
|
||||||
tag: 'user',
|
tag: 'user',
|
||||||
attrs: { jid },
|
attrs: { jid }
|
||||||
})
|
}))
|
||||||
)
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
@@ -247,11 +281,11 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
return didFetchNewSession
|
return didFetchNewSession
|
||||||
}
|
}
|
||||||
|
|
||||||
const sendPeerDataOperationMessage = async(
|
const sendPeerDataOperationMessage = async (
|
||||||
pdoMessage: proto.Message.IPeerDataOperationRequestMessage
|
pdoMessage: proto.Message.IPeerDataOperationRequestMessage
|
||||||
): Promise<string> => {
|
): Promise<string> => {
|
||||||
//TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
|
//TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
|
||||||
if(!authState.creds.me?.id) {
|
if (!authState.creds.me?.id) {
|
||||||
throw new Boom('Not authenticated')
|
throw new Boom('Not authenticated')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,64 +302,67 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
additionalAttributes: {
|
additionalAttributes: {
|
||||||
category: 'peer',
|
category: 'peer',
|
||||||
// eslint-disable-next-line camelcase
|
// eslint-disable-next-line camelcase
|
||||||
push_priority: 'high_force',
|
push_priority: 'high_force'
|
||||||
},
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
return msgId
|
return msgId
|
||||||
}
|
}
|
||||||
|
|
||||||
const createParticipantNodes = async(
|
const createParticipantNodes = async (jids: string[], message: proto.IMessage, extraAttrs?: BinaryNode['attrs']) => {
|
||||||
jids: string[],
|
|
||||||
message: proto.IMessage,
|
|
||||||
extraAttrs?: BinaryNode['attrs']
|
|
||||||
) => {
|
|
||||||
let patched = await patchMessageBeforeSending(message, jids)
|
let patched = await patchMessageBeforeSending(message, jids)
|
||||||
if(!Array.isArray(patched)) {
|
if (!Array.isArray(patched)) {
|
||||||
patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched]
|
patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched]
|
||||||
}
|
}
|
||||||
|
|
||||||
let shouldIncludeDeviceIdentity = false
|
let shouldIncludeDeviceIdentity = false
|
||||||
|
|
||||||
const nodes = await Promise.all(
|
const nodes = await Promise.all(
|
||||||
patched.map(
|
patched.map(async patchedMessageWithJid => {
|
||||||
async patchedMessageWithJid => {
|
|
||||||
const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid
|
const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid
|
||||||
if(!jid) {
|
if (!jid) {
|
||||||
return {} as BinaryNode
|
return {} as BinaryNode
|
||||||
}
|
}
|
||||||
|
|
||||||
const bytes = encodeWAMessage(patchedMessage)
|
const bytes = encodeWAMessage(patchedMessage)
|
||||||
const { type, ciphertext } = await signalRepository
|
const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
|
||||||
.encryptMessage({ jid, data: bytes })
|
if (type === 'pkmsg') {
|
||||||
if(type === 'pkmsg') {
|
|
||||||
shouldIncludeDeviceIdentity = true
|
shouldIncludeDeviceIdentity = true
|
||||||
}
|
}
|
||||||
|
|
||||||
const node: BinaryNode = {
|
const node: BinaryNode = {
|
||||||
tag: 'to',
|
tag: 'to',
|
||||||
attrs: { jid },
|
attrs: { jid },
|
||||||
content: [{
|
content: [
|
||||||
|
{
|
||||||
tag: 'enc',
|
tag: 'enc',
|
||||||
attrs: {
|
attrs: {
|
||||||
v: '2',
|
v: '2',
|
||||||
type,
|
type,
|
||||||
...extraAttrs || {}
|
...(extraAttrs || {})
|
||||||
},
|
},
|
||||||
content: ciphertext
|
content: ciphertext
|
||||||
}]
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
return node
|
return node
|
||||||
}
|
})
|
||||||
)
|
|
||||||
)
|
)
|
||||||
return { nodes, shouldIncludeDeviceIdentity }
|
return { nodes, shouldIncludeDeviceIdentity }
|
||||||
}
|
}
|
||||||
|
|
||||||
const relayMessage = async(
|
const relayMessage = async (
|
||||||
jid: string,
|
jid: string,
|
||||||
message: proto.IMessage,
|
message: proto.IMessage,
|
||||||
{ messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }: MessageRelayOptions
|
{
|
||||||
|
messageId: msgId,
|
||||||
|
participant,
|
||||||
|
additionalAttributes,
|
||||||
|
additionalNodes,
|
||||||
|
useUserDevicesCache,
|
||||||
|
useCachedGroupMetadata,
|
||||||
|
statusJidList
|
||||||
|
}: MessageRelayOptions
|
||||||
) => {
|
) => {
|
||||||
const meId = authState.creds.me!.id
|
const meId = authState.creds.me!.id
|
||||||
|
|
||||||
@@ -342,7 +379,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
|
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
|
||||||
|
|
||||||
const participants: BinaryNode[] = []
|
const participants: BinaryNode[] = []
|
||||||
const destinationJid = (!isStatus) ? jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : 's.whatsapp.net') : statusJid
|
const destinationJid = !isStatus ? jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : 's.whatsapp.net') : statusJid
|
||||||
const binaryNodeContent: BinaryNode[] = []
|
const binaryNodeContent: BinaryNode[] = []
|
||||||
const devices: JidWithDevice[] = []
|
const devices: JidWithDevice[] = []
|
||||||
|
|
||||||
@@ -355,58 +392,57 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const extraAttrs = {}
|
const extraAttrs = {}
|
||||||
|
|
||||||
if(participant) {
|
if (participant) {
|
||||||
// when the retry request is not for a group
|
// when the retry request is not for a group
|
||||||
// only send to the specific device that asked for a retry
|
// only send to the specific device that asked for a retry
|
||||||
// otherwise the message is sent out to every device that should be a recipient
|
// otherwise the message is sent out to every device that should be a recipient
|
||||||
if(!isGroup && !isStatus) {
|
if (!isGroup && !isStatus) {
|
||||||
additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' }
|
additionalAttributes = { ...additionalAttributes, device_fanout: 'false' }
|
||||||
}
|
}
|
||||||
|
|
||||||
const { user, device } = jidDecode(participant.jid)!
|
const { user, device } = jidDecode(participant.jid)!
|
||||||
devices.push({ user, device })
|
devices.push({ user, device })
|
||||||
}
|
}
|
||||||
|
|
||||||
await authState.keys.transaction(
|
await authState.keys.transaction(async () => {
|
||||||
async() => {
|
|
||||||
const mediaType = getMediaType(message)
|
const mediaType = getMediaType(message)
|
||||||
if(mediaType) {
|
if (mediaType) {
|
||||||
extraAttrs['mediatype'] = mediaType
|
extraAttrs['mediatype'] = mediaType
|
||||||
}
|
}
|
||||||
|
|
||||||
if(normalizeMessageContent(message)?.pinInChatMessage) {
|
if (normalizeMessageContent(message)?.pinInChatMessage) {
|
||||||
extraAttrs['decrypt-fail'] = 'hide'
|
extraAttrs['decrypt-fail'] = 'hide'
|
||||||
}
|
}
|
||||||
|
|
||||||
if(isGroup || isStatus) {
|
if (isGroup || isStatus) {
|
||||||
const [groupData, senderKeyMap] = await Promise.all([
|
const [groupData, senderKeyMap] = await Promise.all([
|
||||||
(async() => {
|
(async () => {
|
||||||
let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
|
let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
|
||||||
if(groupData && Array.isArray(groupData?.participants)) {
|
if (groupData && Array.isArray(groupData?.participants)) {
|
||||||
logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
|
logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
|
||||||
} else if(!isStatus) {
|
} else if (!isStatus) {
|
||||||
groupData = await groupMetadata(jid)
|
groupData = await groupMetadata(jid)
|
||||||
}
|
}
|
||||||
|
|
||||||
return groupData
|
return groupData
|
||||||
})(),
|
})(),
|
||||||
(async() => {
|
(async () => {
|
||||||
if(!participant && !isStatus) {
|
if (!participant && !isStatus) {
|
||||||
const result = await authState.keys.get('sender-key-memory', [jid])
|
const result = await authState.keys.get('sender-key-memory', [jid])
|
||||||
return result[jid] || { }
|
return result[jid] || {}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { }
|
return {}
|
||||||
})()
|
})()
|
||||||
])
|
])
|
||||||
|
|
||||||
if(!participant) {
|
if (!participant) {
|
||||||
const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
|
const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : []
|
||||||
if(isStatus && statusJidList) {
|
if (isStatus && statusJidList) {
|
||||||
participantsList.push(...statusJidList)
|
participantsList.push(...statusJidList)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!isStatus) {
|
if (!isStatus) {
|
||||||
additionalAttributes = {
|
additionalAttributes = {
|
||||||
...additionalAttributes,
|
...additionalAttributes,
|
||||||
addressing_mode: groupData?.addressingMode || 'pn'
|
addressing_mode: groupData?.addressingMode || 'pn'
|
||||||
@@ -419,25 +455,23 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const patched = await patchMessageBeforeSending(message)
|
const patched = await patchMessageBeforeSending(message)
|
||||||
|
|
||||||
if(Array.isArray(patched)) {
|
if (Array.isArray(patched)) {
|
||||||
throw new Boom('Per-jid patching is not supported in groups')
|
throw new Boom('Per-jid patching is not supported in groups')
|
||||||
}
|
}
|
||||||
|
|
||||||
const bytes = encodeWAMessage(patched)
|
const bytes = encodeWAMessage(patched)
|
||||||
|
|
||||||
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage(
|
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
||||||
{
|
|
||||||
group: destinationJid,
|
group: destinationJid,
|
||||||
data: bytes,
|
data: bytes,
|
||||||
meId,
|
meId
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
const senderKeyJids: string[] = []
|
const senderKeyJids: string[] = []
|
||||||
// ensure a connection is established with every device
|
// ensure a connection is established with every device
|
||||||
for(const { user, device } of devices) {
|
for (const { user, device } of devices) {
|
||||||
const jid = jidEncode(user, groupData?.addressingMode === 'lid' ? 'lid' : 's.whatsapp.net', device)
|
const jid = jidEncode(user, groupData?.addressingMode === 'lid' ? 'lid' : 's.whatsapp.net', device)
|
||||||
if(!senderKeyMap[jid] || !!participant) {
|
if (!senderKeyMap[jid] || !!participant) {
|
||||||
senderKeyJids.push(jid)
|
senderKeyJids.push(jid)
|
||||||
// store that this person has had the sender keys sent to them
|
// store that this person has had the sender keys sent to them
|
||||||
senderKeyMap[jid] = true
|
senderKeyMap[jid] = true
|
||||||
@@ -446,7 +480,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
// if there are some participants with whom the session has not been established
|
// if there are some participants with whom the session has not been established
|
||||||
// if there are, we re-send the senderkey
|
// if there are, we re-send the senderkey
|
||||||
if(senderKeyJids.length) {
|
if (senderKeyJids.length) {
|
||||||
logger.debug({ senderKeyJids }, 'sending new sender key')
|
logger.debug({ senderKeyJids }, 'sending new sender key')
|
||||||
|
|
||||||
const senderKeyMsg: proto.IMessage = {
|
const senderKeyMsg: proto.IMessage = {
|
||||||
@@ -474,14 +508,14 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
} else {
|
} else {
|
||||||
const { user: meUser } = jidDecode(meId)!
|
const { user: meUser } = jidDecode(meId)!
|
||||||
|
|
||||||
if(!participant) {
|
if (!participant) {
|
||||||
devices.push({ user })
|
devices.push({ user })
|
||||||
if(user !== meUser) {
|
if (user !== meUser) {
|
||||||
devices.push({ user: meUser })
|
devices.push({ user: meUser })
|
||||||
}
|
}
|
||||||
|
|
||||||
if(additionalAttributes?.['category'] !== 'peer') {
|
if (additionalAttributes?.['category'] !== 'peer') {
|
||||||
const additionalDevices = await getUSyncDevices([ meId, jid ], !!useUserDevicesCache, true)
|
const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
|
||||||
devices.push(...additionalDevices)
|
devices.push(...additionalDevices)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -489,10 +523,14 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
const allJids: string[] = []
|
const allJids: string[] = []
|
||||||
const meJids: string[] = []
|
const meJids: string[] = []
|
||||||
const otherJids: string[] = []
|
const otherJids: string[] = []
|
||||||
for(const { user, device } of devices) {
|
for (const { user, device } of devices) {
|
||||||
const isMe = user === meUser
|
const isMe = user === meUser
|
||||||
const jid = jidEncode(isMe && isLid ? authState.creds?.me?.lid!.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
|
const jid = jidEncode(
|
||||||
if(isMe) {
|
isMe && isLid ? authState.creds?.me?.lid!.split(':')[0] || user : user,
|
||||||
|
isLid ? 'lid' : 's.whatsapp.net',
|
||||||
|
device
|
||||||
|
)
|
||||||
|
if (isMe) {
|
||||||
meJids.push(jid)
|
meJids.push(jid)
|
||||||
} else {
|
} else {
|
||||||
otherJids.push(jid)
|
otherJids.push(jid)
|
||||||
@@ -516,16 +554,16 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
|
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
|
||||||
}
|
}
|
||||||
|
|
||||||
if(participants.length) {
|
if (participants.length) {
|
||||||
if(additionalAttributes?.['category'] === 'peer') {
|
if (additionalAttributes?.['category'] === 'peer') {
|
||||||
const peerNode = participants[0]?.content?.[0] as BinaryNode
|
const peerNode = participants[0]?.content?.[0] as BinaryNode
|
||||||
if(peerNode) {
|
if (peerNode) {
|
||||||
binaryNodeContent.push(peerNode) // push only enc
|
binaryNodeContent.push(peerNode) // push only enc
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
binaryNodeContent.push({
|
binaryNodeContent.push({
|
||||||
tag: 'participants',
|
tag: 'participants',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: participants
|
content: participants
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -543,11 +581,11 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
// if the participant to send to is explicitly specified (generally retry recp)
|
// if the participant to send to is explicitly specified (generally retry recp)
|
||||||
// ensure the message is only sent to that person
|
// ensure the message is only sent to that person
|
||||||
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
||||||
if(participant) {
|
if (participant) {
|
||||||
if(isJidGroup(destinationJid)) {
|
if (isJidGroup(destinationJid)) {
|
||||||
stanza.attrs.to = destinationJid
|
stanza.attrs.to = destinationJid
|
||||||
stanza.attrs.participant = participant.jid
|
stanza.attrs.participant = participant.jid
|
||||||
} else if(areJidsSameUser(participant.jid, meId)) {
|
} else if (areJidsSameUser(participant.jid, meId)) {
|
||||||
stanza.attrs.to = participant.jid
|
stanza.attrs.to = participant.jid
|
||||||
stanza.attrs.recipient = destinationJid
|
stanza.attrs.recipient = destinationJid
|
||||||
} else {
|
} else {
|
||||||
@@ -557,32 +595,30 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
stanza.attrs.to = destinationJid
|
stanza.attrs.to = destinationJid
|
||||||
}
|
}
|
||||||
|
|
||||||
if(shouldIncludeDeviceIdentity) {
|
if (shouldIncludeDeviceIdentity) {
|
||||||
(stanza.content as BinaryNode[]).push({
|
;(stanza.content as BinaryNode[]).push({
|
||||||
tag: 'device-identity',
|
tag: 'device-identity',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: encodeSignedDeviceIdentity(authState.creds.account!, true)
|
content: encodeSignedDeviceIdentity(authState.creds.account!, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
logger.debug({ jid }, 'adding device identity')
|
logger.debug({ jid }, 'adding device identity')
|
||||||
}
|
}
|
||||||
|
|
||||||
if(additionalNodes && additionalNodes.length > 0) {
|
if (additionalNodes && additionalNodes.length > 0) {
|
||||||
(stanza.content as BinaryNode[]).push(...additionalNodes)
|
;(stanza.content as BinaryNode[]).push(...additionalNodes)
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug({ msgId }, `sending message to ${participants.length} devices`)
|
logger.debug({ msgId }, `sending message to ${participants.length} devices`)
|
||||||
|
|
||||||
await sendNode(stanza)
|
await sendNode(stanza)
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
return msgId
|
return msgId
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const getMessageType = (message: proto.IMessage) => {
|
const getMessageType = (message: proto.IMessage) => {
|
||||||
if(message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
|
if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
|
||||||
return 'poll'
|
return 'poll'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -590,40 +626,40 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getMediaType = (message: proto.IMessage) => {
|
const getMediaType = (message: proto.IMessage) => {
|
||||||
if(message.imageMessage) {
|
if (message.imageMessage) {
|
||||||
return 'image'
|
return 'image'
|
||||||
} else if(message.videoMessage) {
|
} else if (message.videoMessage) {
|
||||||
return message.videoMessage.gifPlayback ? 'gif' : 'video'
|
return message.videoMessage.gifPlayback ? 'gif' : 'video'
|
||||||
} else if(message.audioMessage) {
|
} else if (message.audioMessage) {
|
||||||
return message.audioMessage.ptt ? 'ptt' : 'audio'
|
return message.audioMessage.ptt ? 'ptt' : 'audio'
|
||||||
} else if(message.contactMessage) {
|
} else if (message.contactMessage) {
|
||||||
return 'vcard'
|
return 'vcard'
|
||||||
} else if(message.documentMessage) {
|
} else if (message.documentMessage) {
|
||||||
return 'document'
|
return 'document'
|
||||||
} else if(message.contactsArrayMessage) {
|
} else if (message.contactsArrayMessage) {
|
||||||
return 'contact_array'
|
return 'contact_array'
|
||||||
} else if(message.liveLocationMessage) {
|
} else if (message.liveLocationMessage) {
|
||||||
return 'livelocation'
|
return 'livelocation'
|
||||||
} else if(message.stickerMessage) {
|
} else if (message.stickerMessage) {
|
||||||
return 'sticker'
|
return 'sticker'
|
||||||
} else if(message.listMessage) {
|
} else if (message.listMessage) {
|
||||||
return 'list'
|
return 'list'
|
||||||
} else if(message.listResponseMessage) {
|
} else if (message.listResponseMessage) {
|
||||||
return 'list_response'
|
return 'list_response'
|
||||||
} else if(message.buttonsResponseMessage) {
|
} else if (message.buttonsResponseMessage) {
|
||||||
return 'buttons_response'
|
return 'buttons_response'
|
||||||
} else if(message.orderMessage) {
|
} else if (message.orderMessage) {
|
||||||
return 'order'
|
return 'order'
|
||||||
} else if(message.productMessage) {
|
} else if (message.productMessage) {
|
||||||
return 'product'
|
return 'product'
|
||||||
} else if(message.interactiveResponseMessage) {
|
} else if (message.interactiveResponseMessage) {
|
||||||
return 'native_flow_response'
|
return 'native_flow_response'
|
||||||
} else if(message.groupInviteMessage) {
|
} else if (message.groupInviteMessage) {
|
||||||
return 'url'
|
return 'url'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const getPrivacyTokens = async(jids: string[]) => {
|
const getPrivacyTokens = async (jids: string[]) => {
|
||||||
const t = unixTimestampSeconds().toString()
|
const t = unixTimestampSeconds().toString()
|
||||||
const result = await query({
|
const result = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
@@ -635,17 +671,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'tokens',
|
tag: 'tokens',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: jids.map(
|
content: jids.map(jid => ({
|
||||||
jid => ({
|
|
||||||
tag: 'token',
|
tag: 'token',
|
||||||
attrs: {
|
attrs: {
|
||||||
jid: jidNormalizedUser(jid),
|
jid: jidNormalizedUser(jid),
|
||||||
t,
|
t,
|
||||||
type: 'trusted_contact'
|
type: 'trusted_contact'
|
||||||
}
|
}
|
||||||
})
|
}))
|
||||||
)
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
@@ -671,37 +705,36 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
sendPeerDataOperationMessage,
|
sendPeerDataOperationMessage,
|
||||||
createParticipantNodes,
|
createParticipantNodes,
|
||||||
getUSyncDevices,
|
getUSyncDevices,
|
||||||
updateMediaMessage: async(message: proto.IWebMessageInfo) => {
|
updateMediaMessage: async (message: proto.IWebMessageInfo) => {
|
||||||
const content = assertMediaContent(message.message)
|
const content = assertMediaContent(message.message)
|
||||||
const mediaKey = content.mediaKey!
|
const mediaKey = content.mediaKey!
|
||||||
const meId = authState.creds.me!.id
|
const meId = authState.creds.me!.id
|
||||||
const node = await encryptMediaRetryRequest(message.key, mediaKey, meId)
|
const node = await encryptMediaRetryRequest(message.key, mediaKey, meId)
|
||||||
|
|
||||||
let error: Error | undefined = undefined
|
let error: Error | undefined = undefined
|
||||||
await Promise.all(
|
await Promise.all([
|
||||||
[
|
|
||||||
sendNode(node),
|
sendNode(node),
|
||||||
waitForMsgMediaUpdate(async(update) => {
|
waitForMsgMediaUpdate(async update => {
|
||||||
const result = update.find(c => c.key.id === message.key.id)
|
const result = update.find(c => c.key.id === message.key.id)
|
||||||
if(result) {
|
if (result) {
|
||||||
if(result.error) {
|
if (result.error) {
|
||||||
error = result.error
|
error = result.error
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
const media = await decryptMediaRetryData(result.media!, mediaKey, result.key.id!)
|
const media = await decryptMediaRetryData(result.media!, mediaKey, result.key.id!)
|
||||||
if(media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
|
if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
|
||||||
const resultStr = proto.MediaRetryNotification.ResultType[media.result!]
|
const resultStr = proto.MediaRetryNotification.ResultType[media.result!]
|
||||||
throw new Boom(
|
throw new Boom(`Media re-upload failed by device (${resultStr})`, {
|
||||||
`Media re-upload failed by device (${resultStr})`,
|
data: media,
|
||||||
{ data: media, statusCode: getStatusCodeForMediaRetry(media.result!) || 404 }
|
statusCode: getStatusCodeForMediaRetry(media.result!) || 404
|
||||||
)
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
content.directPath = media.directPath
|
content.directPath = media.directPath
|
||||||
content.url = getUrlFromDirectPath(content.directPath!)
|
content.url = getUrlFromDirectPath(content.directPath!)
|
||||||
|
|
||||||
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
|
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
|
||||||
} catch(err) {
|
} catch (err) {
|
||||||
error = err
|
error = err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -709,103 +742,97 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
]
|
])
|
||||||
)
|
|
||||||
|
|
||||||
if(error) {
|
if (error) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
ev.emit('messages.update', [
|
ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }])
|
||||||
{ key: message.key, update: { message: message.message } }
|
|
||||||
])
|
|
||||||
|
|
||||||
return message
|
return message
|
||||||
},
|
},
|
||||||
sendMessage: async(
|
sendMessage: async (jid: string, content: AnyMessageContent, options: MiscMessageGenerationOptions = {}) => {
|
||||||
jid: string,
|
|
||||||
content: AnyMessageContent,
|
|
||||||
options: MiscMessageGenerationOptions = { }
|
|
||||||
) => {
|
|
||||||
const userJid = authState.creds.me!.id
|
const userJid = authState.creds.me!.id
|
||||||
if(
|
if (
|
||||||
typeof content === 'object' &&
|
typeof content === 'object' &&
|
||||||
'disappearingMessagesInChat' in content &&
|
'disappearingMessagesInChat' in content &&
|
||||||
typeof content['disappearingMessagesInChat'] !== 'undefined' &&
|
typeof content['disappearingMessagesInChat'] !== 'undefined' &&
|
||||||
isJidGroup(jid)
|
isJidGroup(jid)
|
||||||
) {
|
) {
|
||||||
const { disappearingMessagesInChat } = content
|
const { disappearingMessagesInChat } = content
|
||||||
const value = typeof disappearingMessagesInChat === 'boolean' ?
|
const value =
|
||||||
(disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) :
|
typeof disappearingMessagesInChat === 'boolean'
|
||||||
disappearingMessagesInChat
|
? disappearingMessagesInChat
|
||||||
|
? WA_DEFAULT_EPHEMERAL
|
||||||
|
: 0
|
||||||
|
: disappearingMessagesInChat
|
||||||
await groupToggleEphemeral(jid, value)
|
await groupToggleEphemeral(jid, value)
|
||||||
} else {
|
} else {
|
||||||
const fullMsg = await generateWAMessage(
|
const fullMsg = await generateWAMessage(jid, content, {
|
||||||
jid,
|
|
||||||
content,
|
|
||||||
{
|
|
||||||
logger,
|
logger,
|
||||||
userJid,
|
userJid,
|
||||||
getUrlInfo: text => getUrlInfo(
|
getUrlInfo: text =>
|
||||||
text,
|
getUrlInfo(text, {
|
||||||
{
|
|
||||||
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
||||||
fetchOpts: {
|
fetchOpts: {
|
||||||
timeout: 3_000,
|
timeout: 3_000,
|
||||||
...axiosOptions || { }
|
...(axiosOptions || {})
|
||||||
},
|
},
|
||||||
logger,
|
logger,
|
||||||
uploadImage: generateHighQualityLinkPreview
|
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
||||||
? waUploadToServer
|
}),
|
||||||
: undefined
|
|
||||||
},
|
|
||||||
),
|
|
||||||
//TODO: CACHE
|
//TODO: CACHE
|
||||||
getProfilePicUrl: sock.profilePictureUrl,
|
getProfilePicUrl: sock.profilePictureUrl,
|
||||||
upload: waUploadToServer,
|
upload: waUploadToServer,
|
||||||
mediaCache: config.mediaCache,
|
mediaCache: config.mediaCache,
|
||||||
options: config.options,
|
options: config.options,
|
||||||
messageId: generateMessageIDV2(sock.user?.id),
|
messageId: generateMessageIDV2(sock.user?.id),
|
||||||
...options,
|
...options
|
||||||
}
|
})
|
||||||
)
|
|
||||||
const isDeleteMsg = 'delete' in content && !!content.delete
|
const isDeleteMsg = 'delete' in content && !!content.delete
|
||||||
const isEditMsg = 'edit' in content && !!content.edit
|
const isEditMsg = 'edit' in content && !!content.edit
|
||||||
const isPinMsg = 'pin' in content && !!content.pin
|
const isPinMsg = 'pin' in content && !!content.pin
|
||||||
const isPollMessage = 'poll' in content && !!content.poll
|
const isPollMessage = 'poll' in content && !!content.poll
|
||||||
const additionalAttributes: BinaryNodeAttributes = { }
|
const additionalAttributes: BinaryNodeAttributes = {}
|
||||||
const additionalNodes: BinaryNode[] = []
|
const additionalNodes: BinaryNode[] = []
|
||||||
// required for delete
|
// required for delete
|
||||||
if(isDeleteMsg) {
|
if (isDeleteMsg) {
|
||||||
// if the chat is a group, and I am not the author, then delete the message as an admin
|
// if the chat is a group, and I am not the author, then delete the message as an admin
|
||||||
if(isJidGroup(content.delete?.remoteJid as string) && !content.delete?.fromMe) {
|
if (isJidGroup(content.delete?.remoteJid as string) && !content.delete?.fromMe) {
|
||||||
additionalAttributes.edit = '8'
|
additionalAttributes.edit = '8'
|
||||||
} else {
|
} else {
|
||||||
additionalAttributes.edit = '7'
|
additionalAttributes.edit = '7'
|
||||||
}
|
}
|
||||||
} else if(isEditMsg) {
|
} else if (isEditMsg) {
|
||||||
additionalAttributes.edit = '1'
|
additionalAttributes.edit = '1'
|
||||||
} else if(isPinMsg) {
|
} else if (isPinMsg) {
|
||||||
additionalAttributes.edit = '2'
|
additionalAttributes.edit = '2'
|
||||||
} else if(isPollMessage) {
|
} else if (isPollMessage) {
|
||||||
additionalNodes.push({
|
additionalNodes.push({
|
||||||
tag: 'meta',
|
tag: 'meta',
|
||||||
attrs: {
|
attrs: {
|
||||||
polltype: 'creation'
|
polltype: 'creation'
|
||||||
},
|
}
|
||||||
} as BinaryNode)
|
} as BinaryNode)
|
||||||
}
|
}
|
||||||
|
|
||||||
if('cachedGroupMetadata' in options) {
|
if ('cachedGroupMetadata' in options) {
|
||||||
console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.')
|
console.warn(
|
||||||
|
'cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
await relayMessage(jid, fullMsg.message!, { messageId: fullMsg.key.id!, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes })
|
await relayMessage(jid, fullMsg.message!, {
|
||||||
if(config.emitOwnEvents) {
|
messageId: fullMsg.key.id!,
|
||||||
|
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
||||||
|
additionalAttributes,
|
||||||
|
statusJidList: options.statusJidList,
|
||||||
|
additionalNodes
|
||||||
|
})
|
||||||
|
if (config.emitOwnEvents) {
|
||||||
process.nextTick(() => {
|
process.nextTick(() => {
|
||||||
processingMutex.mutex(() => (
|
processingMutex.mutex(() => upsertMessage(fullMsg, 'append'))
|
||||||
upsertMessage(fullMsg, 'append')
|
|
||||||
))
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ import {
|
|||||||
getPlatformId,
|
getPlatformId,
|
||||||
makeEventBuffer,
|
makeEventBuffer,
|
||||||
makeNoiseHandler,
|
makeNoiseHandler,
|
||||||
promiseTimeout,
|
promiseTimeout
|
||||||
} from '../Utils'
|
} from '../Utils'
|
||||||
import {
|
import {
|
||||||
assertNodeErrorFree,
|
assertNodeErrorFree,
|
||||||
@@ -61,21 +61,22 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
defaultQueryTimeoutMs,
|
defaultQueryTimeoutMs,
|
||||||
transactionOpts,
|
transactionOpts,
|
||||||
qrTimeout,
|
qrTimeout,
|
||||||
makeSignalRepository,
|
makeSignalRepository
|
||||||
} = config
|
} = config
|
||||||
|
|
||||||
if(printQRInTerminal) {
|
if (printQRInTerminal) {
|
||||||
console.warn('⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.')
|
console.warn(
|
||||||
|
'⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl
|
const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl
|
||||||
|
|
||||||
|
if (config.mobile || url.protocol === 'tcp:') {
|
||||||
if(config.mobile || url.protocol === 'tcp:') {
|
|
||||||
throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut })
|
throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut })
|
||||||
}
|
}
|
||||||
|
|
||||||
if(url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
||||||
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
|
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,28 +111,25 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const sendPromise = promisify(ws.send)
|
const sendPromise = promisify(ws.send)
|
||||||
/** send a raw buffer */
|
/** send a raw buffer */
|
||||||
const sendRawMessage = async(data: Uint8Array | Buffer) => {
|
const sendRawMessage = async (data: Uint8Array | Buffer) => {
|
||||||
if(!ws.isOpen) {
|
if (!ws.isOpen) {
|
||||||
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
||||||
}
|
}
|
||||||
|
|
||||||
const bytes = noise.encodeFrame(data)
|
const bytes = noise.encodeFrame(data)
|
||||||
await promiseTimeout<void>(
|
await promiseTimeout<void>(connectTimeoutMs, async (resolve, reject) => {
|
||||||
connectTimeoutMs,
|
|
||||||
async(resolve, reject) => {
|
|
||||||
try {
|
try {
|
||||||
await sendPromise.call(ws, bytes)
|
await sendPromise.call(ws, bytes)
|
||||||
resolve()
|
resolve()
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
reject(error)
|
reject(error)
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** send a binary node */
|
/** send a binary node */
|
||||||
const sendNode = (frame: BinaryNode) => {
|
const sendNode = (frame: BinaryNode) => {
|
||||||
if(logger.level === 'trace') {
|
if (logger.level === 'trace') {
|
||||||
logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
|
logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,15 +139,12 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
/** log & process any unexpected errors */
|
/** log & process any unexpected errors */
|
||||||
const onUnexpectedError = (err: Error | Boom, msg: string) => {
|
const onUnexpectedError = (err: Error | Boom, msg: string) => {
|
||||||
logger.error(
|
logger.error({ err }, `unexpected error in '${msg}'`)
|
||||||
{ err },
|
|
||||||
`unexpected error in '${msg}'`
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** await the next incoming message */
|
/** await the next incoming message */
|
||||||
const awaitNextMessage = async<T>(sendMsg?: Uint8Array) => {
|
const awaitNextMessage = async <T>(sendMsg?: Uint8Array) => {
|
||||||
if(!ws.isOpen) {
|
if (!ws.isOpen) {
|
||||||
throw new Boom('Connection Closed', {
|
throw new Boom('Connection Closed', {
|
||||||
statusCode: DisconnectReason.connectionClosed
|
statusCode: DisconnectReason.connectionClosed
|
||||||
})
|
})
|
||||||
@@ -164,14 +159,13 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ws.on('frame', onOpen)
|
ws.on('frame', onOpen)
|
||||||
ws.on('close', onClose)
|
ws.on('close', onClose)
|
||||||
ws.on('error', onClose)
|
ws.on('error', onClose)
|
||||||
})
|
}).finally(() => {
|
||||||
.finally(() => {
|
|
||||||
ws.off('frame', onOpen)
|
ws.off('frame', onOpen)
|
||||||
ws.off('close', onClose)
|
ws.off('close', onClose)
|
||||||
ws.off('error', onClose)
|
ws.off('error', onClose)
|
||||||
})
|
})
|
||||||
|
|
||||||
if(sendMsg) {
|
if (sendMsg) {
|
||||||
sendRawMessage(sendMsg).catch(onClose!)
|
sendRawMessage(sendMsg).catch(onClose!)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,12 +177,11 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
* @param msgId the message tag to await
|
* @param msgId the message tag to await
|
||||||
* @param timeoutMs timeout after which the promise will reject
|
* @param timeoutMs timeout after which the promise will reject
|
||||||
*/
|
*/
|
||||||
const waitForMessage = async<T>(msgId: string, timeoutMs = defaultQueryTimeoutMs) => {
|
const waitForMessage = async <T>(msgId: string, timeoutMs = defaultQueryTimeoutMs) => {
|
||||||
let onRecv: (json) => void
|
let onRecv: (json) => void
|
||||||
let onErr: (err) => void
|
let onErr: (err) => void
|
||||||
try {
|
try {
|
||||||
const result = await promiseTimeout<T>(timeoutMs,
|
const result = await promiseTimeout<T>(timeoutMs, (resolve, reject) => {
|
||||||
(resolve, reject) => {
|
|
||||||
onRecv = resolve
|
onRecv = resolve
|
||||||
onErr = err => {
|
onErr = err => {
|
||||||
reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
|
reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
|
||||||
@@ -197,8 +190,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ws.on(`TAG:${msgId}`, onRecv)
|
ws.on(`TAG:${msgId}`, onRecv)
|
||||||
ws.on('close', onErr) // if the socket closes, you'll never receive the message
|
ws.on('close', onErr) // if the socket closes, you'll never receive the message
|
||||||
ws.off('error', onErr)
|
ws.off('error', onErr)
|
||||||
},
|
})
|
||||||
)
|
|
||||||
|
|
||||||
return result as any
|
return result as any
|
||||||
} finally {
|
} finally {
|
||||||
@@ -209,19 +201,16 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
||||||
const query = async(node: BinaryNode, timeoutMs?: number) => {
|
const query = async (node: BinaryNode, timeoutMs?: number) => {
|
||||||
if(!node.attrs.id) {
|
if (!node.attrs.id) {
|
||||||
node.attrs.id = generateMessageTag()
|
node.attrs.id = generateMessageTag()
|
||||||
}
|
}
|
||||||
|
|
||||||
const msgId = node.attrs.id
|
const msgId = node.attrs.id
|
||||||
|
|
||||||
const [result] = await Promise.all([
|
const [result] = await Promise.all([waitForMessage(msgId, timeoutMs), sendNode(node)])
|
||||||
waitForMessage(msgId, timeoutMs),
|
|
||||||
sendNode(node)
|
|
||||||
])
|
|
||||||
|
|
||||||
if('tag' in result) {
|
if ('tag' in result) {
|
||||||
assertNodeErrorFree(result)
|
assertNodeErrorFree(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,7 +218,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** connection handshake */
|
/** connection handshake */
|
||||||
const validateConnection = async() => {
|
const validateConnection = async () => {
|
||||||
let helloMsg: proto.IHandshakeMessage = {
|
let helloMsg: proto.IHandshakeMessage = {
|
||||||
clientHello: { ephemeral: ephemeralKeyPair.public }
|
clientHello: { ephemeral: ephemeralKeyPair.public }
|
||||||
}
|
}
|
||||||
@@ -247,7 +236,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey)
|
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey)
|
||||||
|
|
||||||
let node: proto.IClientPayload
|
let node: proto.IClientPayload
|
||||||
if(!creds.me) {
|
if (!creds.me) {
|
||||||
node = generateRegistrationNode(creds, config)
|
node = generateRegistrationNode(creds, config)
|
||||||
logger.info({ node }, 'not logged in, attempting registration...')
|
logger.info({ node }, 'not logged in, attempting registration...')
|
||||||
} else {
|
} else {
|
||||||
@@ -255,22 +244,20 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
logger.info({ node }, 'logging in...')
|
logger.info({ node }, 'logging in...')
|
||||||
}
|
}
|
||||||
|
|
||||||
const payloadEnc = noise.encrypt(
|
const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish())
|
||||||
proto.ClientPayload.encode(node).finish()
|
|
||||||
)
|
|
||||||
await sendRawMessage(
|
await sendRawMessage(
|
||||||
proto.HandshakeMessage.encode({
|
proto.HandshakeMessage.encode({
|
||||||
clientFinish: {
|
clientFinish: {
|
||||||
static: keyEnc,
|
static: keyEnc,
|
||||||
payload: payloadEnc,
|
payload: payloadEnc
|
||||||
},
|
}
|
||||||
}).finish()
|
}).finish()
|
||||||
)
|
)
|
||||||
noise.finishInit()
|
noise.finishInit()
|
||||||
startKeepAliveRequest()
|
startKeepAliveRequest()
|
||||||
}
|
}
|
||||||
|
|
||||||
const getAvailablePreKeysOnServer = async() => {
|
const getAvailablePreKeysOnServer = async () => {
|
||||||
const result = await query({
|
const result = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
@@ -279,18 +266,15 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
type: 'get',
|
type: 'get',
|
||||||
to: S_WHATSAPP_NET
|
to: S_WHATSAPP_NET
|
||||||
},
|
},
|
||||||
content: [
|
content: [{ tag: 'count', attrs: {} }]
|
||||||
{ tag: 'count', attrs: {} }
|
|
||||||
]
|
|
||||||
})
|
})
|
||||||
const countChild = getBinaryNodeChild(result, 'count')
|
const countChild = getBinaryNodeChild(result, 'count')
|
||||||
return +countChild!.attrs.value
|
return +countChild!.attrs.value
|
||||||
}
|
}
|
||||||
|
|
||||||
/** generates and uploads a set of pre-keys to the server */
|
/** generates and uploads a set of pre-keys to the server */
|
||||||
const uploadPreKeys = async(count = INITIAL_PREKEY_COUNT) => {
|
const uploadPreKeys = async (count = INITIAL_PREKEY_COUNT) => {
|
||||||
await keys.transaction(
|
await keys.transaction(async () => {
|
||||||
async() => {
|
|
||||||
logger.info({ count }, 'uploading pre-keys')
|
logger.info({ count }, 'uploading pre-keys')
|
||||||
const { update, node } = await getNextPreKeysNode({ creds, keys }, count)
|
const { update, node } = await getNextPreKeysNode({ creds, keys }, count)
|
||||||
|
|
||||||
@@ -298,14 +282,13 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ev.emit('creds.update', update)
|
ev.emit('creds.update', update)
|
||||||
|
|
||||||
logger.info({ count }, 'uploaded pre-keys')
|
logger.info({ count }, 'uploaded pre-keys')
|
||||||
}
|
})
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const uploadPreKeysToServerIfRequired = async() => {
|
const uploadPreKeysToServerIfRequired = async () => {
|
||||||
const preKeyCount = await getAvailablePreKeysOnServer()
|
const preKeyCount = await getAvailablePreKeysOnServer()
|
||||||
logger.info(`${preKeyCount} pre-keys found on server`)
|
logger.info(`${preKeyCount} pre-keys found on server`)
|
||||||
if(preKeyCount <= MIN_PREKEY_COUNT) {
|
if (preKeyCount <= MIN_PREKEY_COUNT) {
|
||||||
await uploadPreKeys()
|
await uploadPreKeys()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -319,10 +302,10 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
anyTriggered = ws.emit('frame', frame)
|
anyTriggered = ws.emit('frame', frame)
|
||||||
// if it's a binary node
|
// if it's a binary node
|
||||||
if(!(frame instanceof Uint8Array)) {
|
if (!(frame instanceof Uint8Array)) {
|
||||||
const msgId = frame.attrs.id
|
const msgId = frame.attrs.id
|
||||||
|
|
||||||
if(logger.level === 'trace') {
|
if (logger.level === 'trace') {
|
||||||
logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
|
logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,7 +316,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
const l1 = frame.attrs || {}
|
const l1 = frame.attrs || {}
|
||||||
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
|
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
|
||||||
|
|
||||||
for(const key of Object.keys(l1)) {
|
for (const key of Object.keys(l1)) {
|
||||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
|
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
|
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
|
||||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
|
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
|
||||||
@@ -342,7 +325,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
|
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
|
||||||
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
|
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
|
||||||
|
|
||||||
if(!anyTriggered && logger.level === 'debug') {
|
if (!anyTriggered && logger.level === 'debug') {
|
||||||
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -350,16 +333,13 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const end = (error: Error | undefined) => {
|
const end = (error: Error | undefined) => {
|
||||||
if(closed) {
|
if (closed) {
|
||||||
logger.trace({ trace: error?.stack }, 'connection already closed')
|
logger.trace({ trace: error?.stack }, 'connection already closed')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
closed = true
|
closed = true
|
||||||
logger.info(
|
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
|
||||||
{ trace: error?.stack },
|
|
||||||
error ? 'connection errored' : 'connection closed'
|
|
||||||
)
|
|
||||||
|
|
||||||
clearInterval(keepAliveReq)
|
clearInterval(keepAliveReq)
|
||||||
clearTimeout(qrTimer)
|
clearTimeout(qrTimer)
|
||||||
@@ -369,10 +349,10 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ws.removeAllListeners('open')
|
ws.removeAllListeners('open')
|
||||||
ws.removeAllListeners('message')
|
ws.removeAllListeners('message')
|
||||||
|
|
||||||
if(!ws.isClosed && !ws.isClosing) {
|
if (!ws.isClosed && !ws.isClosing) {
|
||||||
try {
|
try {
|
||||||
ws.close()
|
ws.close()
|
||||||
} catch{ }
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
ev.emit('connection.update', {
|
ev.emit('connection.update', {
|
||||||
@@ -385,12 +365,12 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ev.removeAllListeners('connection.update')
|
ev.removeAllListeners('connection.update')
|
||||||
}
|
}
|
||||||
|
|
||||||
const waitForSocketOpen = async() => {
|
const waitForSocketOpen = async () => {
|
||||||
if(ws.isOpen) {
|
if (ws.isOpen) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if(ws.isClosed || ws.isClosing) {
|
if (ws.isClosed || ws.isClosing) {
|
||||||
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,17 +382,16 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ws.on('open', onOpen)
|
ws.on('open', onOpen)
|
||||||
ws.on('close', onClose)
|
ws.on('close', onClose)
|
||||||
ws.on('error', onClose)
|
ws.on('error', onClose)
|
||||||
})
|
}).finally(() => {
|
||||||
.finally(() => {
|
|
||||||
ws.off('open', onOpen)
|
ws.off('open', onOpen)
|
||||||
ws.off('close', onClose)
|
ws.off('close', onClose)
|
||||||
ws.off('error', onClose)
|
ws.off('error', onClose)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const startKeepAliveRequest = () => (
|
const startKeepAliveRequest = () =>
|
||||||
keepAliveReq = setInterval(() => {
|
(keepAliveReq = setInterval(() => {
|
||||||
if(!lastDateRecv) {
|
if (!lastDateRecv) {
|
||||||
lastDateRecv = new Date()
|
lastDateRecv = new Date()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -421,49 +400,42 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
check if it's been a suspicious amount of time since the server responded with our last seen
|
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
|
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 }))
|
end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
|
||||||
} else if(ws.isOpen) {
|
} else if (ws.isOpen) {
|
||||||
// if its all good, send a keep alive request
|
// if its all good, send a keep alive request
|
||||||
query(
|
query({
|
||||||
{
|
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
id: generateMessageTag(),
|
id: generateMessageTag(),
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'get',
|
type: 'get',
|
||||||
xmlns: 'w:p',
|
xmlns: 'w:p'
|
||||||
},
|
},
|
||||||
content: [{ tag: 'ping', attrs: {} }]
|
content: [{ tag: 'ping', attrs: {} }]
|
||||||
}
|
}).catch(err => {
|
||||||
)
|
|
||||||
.catch(err => {
|
|
||||||
logger.error({ trace: err.stack }, 'error in sending keep alive')
|
logger.error({ trace: err.stack }, 'error in sending keep alive')
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
logger.warn('keep alive called when WS not open')
|
logger.warn('keep alive called when WS not open')
|
||||||
}
|
}
|
||||||
}, keepAliveIntervalMs)
|
}, keepAliveIntervalMs))
|
||||||
)
|
|
||||||
/** i have no idea why this exists. pls enlighten me */
|
/** i have no idea why this exists. pls enlighten me */
|
||||||
const sendPassiveIq = (tag: 'passive' | 'active') => (
|
const sendPassiveIq = (tag: 'passive' | 'active') =>
|
||||||
query({
|
query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
xmlns: 'passive',
|
xmlns: 'passive',
|
||||||
type: 'set',
|
type: 'set'
|
||||||
},
|
},
|
||||||
content: [
|
content: [{ tag, attrs: {} }]
|
||||||
{ tag, attrs: {} }
|
|
||||||
]
|
|
||||||
})
|
})
|
||||||
)
|
|
||||||
|
|
||||||
/** logout & invalidate connection */
|
/** logout & invalidate connection */
|
||||||
const logout = async(msg?: string) => {
|
const logout = async (msg?: string) => {
|
||||||
const jid = authState.creds.me?.id
|
const jid = authState.creds.me?.id
|
||||||
if(jid) {
|
if (jid) {
|
||||||
await sendNode({
|
await sendNode({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
@@ -487,7 +459,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }))
|
end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }))
|
||||||
}
|
}
|
||||||
|
|
||||||
const requestPairingCode = async(phoneNumber: string): Promise<string> => {
|
const requestPairingCode = async (phoneNumber: string): Promise<string> => {
|
||||||
authState.creds.pairingCode = bytesToCrockford(randomBytes(5))
|
authState.creds.pairingCode = bytesToCrockford(randomBytes(5))
|
||||||
authState.creds.me = {
|
authState.creds.me = {
|
||||||
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
||||||
@@ -572,10 +544,10 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
ws.on('message', onMessageReceived)
|
ws.on('message', onMessageReceived)
|
||||||
|
|
||||||
ws.on('open', async() => {
|
ws.on('open', async () => {
|
||||||
try {
|
try {
|
||||||
await validateConnection()
|
await validateConnection()
|
||||||
} catch(err) {
|
} catch (err) {
|
||||||
logger.error({ err }, 'error in validating connection')
|
logger.error({ err }, 'error in validating connection')
|
||||||
end(err)
|
end(err)
|
||||||
}
|
}
|
||||||
@@ -583,15 +555,17 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ws.on('error', mapWebSocketError(end))
|
ws.on('error', mapWebSocketError(end))
|
||||||
ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
|
ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
|
||||||
// the server terminated the connection
|
// the server terminated the connection
|
||||||
ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
|
ws.on('CB:xmlstreamend', () =>
|
||||||
|
end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed }))
|
||||||
|
)
|
||||||
// QR gen
|
// QR gen
|
||||||
ws.on('CB:iq,type:set,pair-device', async(stanza: BinaryNode) => {
|
ws.on('CB:iq,type:set,pair-device', async (stanza: BinaryNode) => {
|
||||||
const iq: BinaryNode = {
|
const iq: BinaryNode = {
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'result',
|
type: 'result',
|
||||||
id: stanza.attrs.id,
|
id: stanza.attrs.id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await sendNode(iq)
|
await sendNode(iq)
|
||||||
@@ -604,12 +578,12 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
let qrMs = qrTimeout || 60_000 // time to let a QR live
|
let qrMs = qrTimeout || 60_000 // time to let a QR live
|
||||||
const genPairQR = () => {
|
const genPairQR = () => {
|
||||||
if(!ws.isOpen) {
|
if (!ws.isOpen) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const refNode = refNodes.shift()
|
const refNode = refNodes.shift()
|
||||||
if(!refNode) {
|
if (!refNode) {
|
||||||
end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
|
end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -627,7 +601,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
// device paired for the first time
|
// device paired for the first time
|
||||||
// if device pairs successfully, the server asks to restart the connection
|
// if device pairs successfully, the server asks to restart the connection
|
||||||
ws.on('CB:iq,,pair-success', async(stanza: BinaryNode) => {
|
ws.on('CB:iq,,pair-success', async (stanza: BinaryNode) => {
|
||||||
logger.debug('pair success recv')
|
logger.debug('pair success recv')
|
||||||
try {
|
try {
|
||||||
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
|
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
|
||||||
@@ -641,13 +615,13 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ev.emit('connection.update', { isNewLogin: true, qr: undefined })
|
ev.emit('connection.update', { isNewLogin: true, qr: undefined })
|
||||||
|
|
||||||
await sendNode(reply)
|
await sendNode(reply)
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
logger.info({ trace: error.stack }, 'error in pairing')
|
logger.info({ trace: error.stack }, 'error in pairing')
|
||||||
end(error)
|
end(error)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
// login complete
|
// login complete
|
||||||
ws.on('CB:success', async(node: BinaryNode) => {
|
ws.on('CB:success', async (node: BinaryNode) => {
|
||||||
await uploadPreKeysToServerIfRequired()
|
await uploadPreKeysToServerIfRequired()
|
||||||
await sendPassiveIq('active')
|
await sendPassiveIq('active')
|
||||||
|
|
||||||
@@ -688,7 +662,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ws.on('CB:ib,,edge_routing', (node: BinaryNode) => {
|
ws.on('CB:ib,,edge_routing', (node: BinaryNode) => {
|
||||||
const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
|
const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
|
||||||
const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
|
const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
|
||||||
if(routingInfo?.content) {
|
if (routingInfo?.content) {
|
||||||
authState.creds.routingInfo = Buffer.from(routingInfo?.content as Uint8Array)
|
authState.creds.routingInfo = Buffer.from(routingInfo?.content as Uint8Array)
|
||||||
ev.emit('creds.update', authState.creds)
|
ev.emit('creds.update', authState.creds)
|
||||||
}
|
}
|
||||||
@@ -696,7 +670,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
let didStartBuffer = false
|
let didStartBuffer = false
|
||||||
process.nextTick(() => {
|
process.nextTick(() => {
|
||||||
if(creds.me?.id) {
|
if (creds.me?.id) {
|
||||||
// start buffering important events
|
// start buffering important events
|
||||||
// if we're logged in
|
// if we're logged in
|
||||||
ev.buffer()
|
ev.buffer()
|
||||||
@@ -712,7 +686,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
const offlineNotifs = +(child?.attrs.count || 0)
|
const offlineNotifs = +(child?.attrs.count || 0)
|
||||||
|
|
||||||
logger.info(`handled ${offlineNotifs} offline messages/notifications`)
|
logger.info(`handled ${offlineNotifs} offline messages/notifications`)
|
||||||
if(didStartBuffer) {
|
if (didStartBuffer) {
|
||||||
ev.flush()
|
ev.flush()
|
||||||
logger.trace('flushed events for initial buffer')
|
logger.trace('flushed events for initial buffer')
|
||||||
}
|
}
|
||||||
@@ -724,13 +698,12 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
ev.on('creds.update', update => {
|
ev.on('creds.update', update => {
|
||||||
const name = update.me?.name
|
const name = update.me?.name
|
||||||
// if name has just been received
|
// if name has just been received
|
||||||
if(creds.me?.name !== name) {
|
if (creds.me?.name !== name) {
|
||||||
logger.debug({ name }, 'updated pushName')
|
logger.debug({ name }, 'updated pushName')
|
||||||
sendNode({
|
sendNode({
|
||||||
tag: 'presence',
|
tag: 'presence',
|
||||||
attrs: { name: name! }
|
attrs: { name: name! }
|
||||||
})
|
}).catch(err => {
|
||||||
.catch(err => {
|
|
||||||
logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
|
logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -738,7 +711,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
Object.assign(creds, update)
|
Object.assign(creds, update)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'md' as 'md',
|
type: 'md' as 'md',
|
||||||
ws,
|
ws,
|
||||||
@@ -762,7 +734,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
requestPairingCode,
|
requestPairingCode,
|
||||||
/** Waits for the connection to WA to reach a state */
|
/** Waits for the connection to WA to reach a state */
|
||||||
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
||||||
sendWAMBuffer,
|
sendWAMBuffer
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -772,11 +744,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
* */
|
* */
|
||||||
function mapWebSocketError(handler: (err: Error) => void) {
|
function mapWebSocketError(handler: (err: Error) => void) {
|
||||||
return (error: Error) => {
|
return (error: Error) => {
|
||||||
handler(
|
handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }))
|
||||||
new Boom(
|
|
||||||
`WebSocket Error (${error?.message})`,
|
|
||||||
{ statusCode: getCodeFromWSError(error), data: error }
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,13 +7,10 @@ import { makeSocket } from './socket'
|
|||||||
export const makeUSyncSocket = (config: SocketConfig) => {
|
export const makeUSyncSocket = (config: SocketConfig) => {
|
||||||
const sock = makeSocket(config)
|
const sock = makeSocket(config)
|
||||||
|
|
||||||
const {
|
const { generateMessageTag, query } = sock
|
||||||
generateMessageTag,
|
|
||||||
query,
|
|
||||||
} = sock
|
|
||||||
|
|
||||||
const executeUSyncQuery = async(usyncQuery: USyncQuery) => {
|
const executeUSyncQuery = async (usyncQuery: USyncQuery) => {
|
||||||
if(usyncQuery.protocols.length === 0) {
|
if (usyncQuery.protocols.length === 0) {
|
||||||
throw new Boom('USyncQuery must have at least one protocol')
|
throw new Boom('USyncQuery must have at least one protocol')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,15 +18,13 @@ export const makeUSyncSocket = (config: SocketConfig) => {
|
|||||||
// variable below has only validated users
|
// variable below has only validated users
|
||||||
const validUsers = usyncQuery.users
|
const validUsers = usyncQuery.users
|
||||||
|
|
||||||
const userNodes = validUsers.map((user) => {
|
const userNodes = validUsers.map(user => {
|
||||||
return {
|
return {
|
||||||
tag: 'user',
|
tag: 'user',
|
||||||
attrs: {
|
attrs: {
|
||||||
jid: !user.phone ? user.id : undefined,
|
jid: !user.phone ? user.id : undefined
|
||||||
},
|
},
|
||||||
content: usyncQuery.protocols
|
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
||||||
.map((a) => a.getUserElement(user))
|
|
||||||
.filter(a => a !== null)
|
|
||||||
} as BinaryNode
|
} as BinaryNode
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -42,14 +37,14 @@ export const makeUSyncSocket = (config: SocketConfig) => {
|
|||||||
const queryNode: BinaryNode = {
|
const queryNode: BinaryNode = {
|
||||||
tag: 'query',
|
tag: 'query',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: usyncQuery.protocols.map((a) => a.getQueryElement())
|
content: usyncQuery.protocols.map(a => a.getQueryElement())
|
||||||
}
|
}
|
||||||
const iq = {
|
const iq = {
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'get',
|
type: 'get',
|
||||||
xmlns: 'usync',
|
xmlns: 'usync'
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
@@ -59,14 +54,11 @@ export const makeUSyncSocket = (config: SocketConfig) => {
|
|||||||
mode: usyncQuery.mode,
|
mode: usyncQuery.mode,
|
||||||
sid: generateMessageTag(),
|
sid: generateMessageTag(),
|
||||||
last: 'true',
|
last: 'true',
|
||||||
index: '0',
|
index: '0'
|
||||||
},
|
},
|
||||||
content: [
|
content: [queryNode, listNode]
|
||||||
queryNode,
|
|
||||||
listNode
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
],
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await query(iq)
|
const result = await query(iq)
|
||||||
@@ -76,6 +68,6 @@ export const makeUSyncSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...sock,
|
...sock,
|
||||||
executeUSyncQuery,
|
executeUSyncQuery
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,6 @@ import { processSyncAction } from '../Utils/chat-utils'
|
|||||||
import logger from '../Utils/logger'
|
import logger from '../Utils/logger'
|
||||||
|
|
||||||
describe('App State Sync Tests', () => {
|
describe('App State Sync Tests', () => {
|
||||||
|
|
||||||
const me: Contact = { id: randomJid() }
|
const me: Contact = { id: randomJid() }
|
||||||
// case when initial sync is off
|
// case when initial sync is off
|
||||||
it('should return archive=false event', () => {
|
it('should return archive=false event', () => {
|
||||||
@@ -57,7 +56,7 @@ describe('App State Sync Tests', () => {
|
|||||||
]
|
]
|
||||||
]
|
]
|
||||||
|
|
||||||
for(const mutations of CASES) {
|
for (const mutations of CASES) {
|
||||||
const events = processSyncAction(mutations, me, undefined, logger)
|
const events = processSyncAction(mutations, me, undefined, logger)
|
||||||
expect(events['chats.update']).toHaveLength(1)
|
expect(events['chats.update']).toHaveLength(1)
|
||||||
const event = events['chats.update']?.[0]
|
const event = events['chats.update']?.[0]
|
||||||
@@ -129,7 +128,7 @@ describe('App State Sync Tests', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
]
|
||||||
]
|
]
|
||||||
|
|
||||||
const ctx: InitialAppStateSyncOptions = {
|
const ctx: InitialAppStateSyncOptions = {
|
||||||
@@ -139,7 +138,7 @@ describe('App State Sync Tests', () => {
|
|||||||
accountSettings: { unarchiveChats: true }
|
accountSettings: { unarchiveChats: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const mutations of CASES) {
|
for (const mutations of CASES) {
|
||||||
const events = processSyncActions(mutations, me, ctx, logger)
|
const events = processSyncActions(mutations, me, ctx, logger)
|
||||||
expect(events['chats.update']?.length).toBeFalsy()
|
expect(events['chats.update']?.length).toBeFalsy()
|
||||||
}
|
}
|
||||||
@@ -152,7 +151,7 @@ describe('App State Sync Tests', () => {
|
|||||||
const index = ['archive', jid]
|
const index = ['archive', jid]
|
||||||
const now = unixTimestampSeconds()
|
const now = unixTimestampSeconds()
|
||||||
|
|
||||||
const CASES: { settings: AccountSettings, mutations: ChatMutation[] }[] = [
|
const CASES: { settings: AccountSettings; mutations: ChatMutation[] }[] = [
|
||||||
{
|
{
|
||||||
settings: { unarchiveChats: true },
|
settings: { unarchiveChats: true },
|
||||||
mutations: [
|
mutations: [
|
||||||
@@ -169,7 +168,7 @@ describe('App State Sync Tests', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
settings: { unarchiveChats: false },
|
settings: { unarchiveChats: false },
|
||||||
@@ -187,11 +186,11 @@ describe('App State Sync Tests', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
for(const { mutations, settings } of CASES) {
|
for (const { mutations, settings } of CASES) {
|
||||||
const ctx: InitialAppStateSyncOptions = {
|
const ctx: InitialAppStateSyncOptions = {
|
||||||
recvChats: {
|
recvChats: {
|
||||||
[jid]: { lastMsgRecvTimestamp: now }
|
[jid]: { lastMsgRecvTimestamp: now }
|
||||||
|
|||||||
@@ -5,15 +5,14 @@ import logger from '../Utils/logger'
|
|||||||
import { randomJid } from './utils'
|
import { randomJid } from './utils'
|
||||||
|
|
||||||
describe('Event Buffer Tests', () => {
|
describe('Event Buffer Tests', () => {
|
||||||
|
|
||||||
let ev: ReturnType<typeof makeEventBuffer>
|
let ev: ReturnType<typeof makeEventBuffer>
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
const _logger = logger.child({ })
|
const _logger = logger.child({})
|
||||||
_logger.level = 'trace'
|
_logger.level = 'trace'
|
||||||
ev = makeEventBuffer(_logger)
|
ev = makeEventBuffer(_logger)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should buffer a chat upsert & update event', async() => {
|
it('should buffer a chat upsert & update event', async () => {
|
||||||
const chatId = randomJid()
|
const chatId = randomJid()
|
||||||
|
|
||||||
const chats: Chat[] = []
|
const chats: Chat[] = []
|
||||||
@@ -23,14 +22,14 @@ describe('Event Buffer Tests', () => {
|
|||||||
|
|
||||||
ev.buffer()
|
ev.buffer()
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
(async() => {
|
(async () => {
|
||||||
ev.buffer()
|
ev.buffer()
|
||||||
await delay(100)
|
await delay(100)
|
||||||
ev.emit('chats.upsert', [{ id: chatId, conversationTimestamp: 123, unreadCount: 1 }])
|
ev.emit('chats.upsert', [{ id: chatId, conversationTimestamp: 123, unreadCount: 1 }])
|
||||||
const flushed = ev.flush()
|
const flushed = ev.flush()
|
||||||
expect(flushed).toBeFalsy()
|
expect(flushed).toBeFalsy()
|
||||||
})(),
|
})(),
|
||||||
(async() => {
|
(async () => {
|
||||||
ev.buffer()
|
ev.buffer()
|
||||||
await delay(200)
|
await delay(200)
|
||||||
ev.emit('chats.update', [{ id: chatId, conversationTimestamp: 124, unreadCount: 1 }])
|
ev.emit('chats.update', [{ id: chatId, conversationTimestamp: 124, unreadCount: 1 }])
|
||||||
@@ -47,7 +46,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(chats[0].unreadCount).toEqual(2)
|
expect(chats[0].unreadCount).toEqual(2)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should overwrite a chats.delete event', async() => {
|
it('should overwrite a chats.delete event', async () => {
|
||||||
const chatId = randomJid()
|
const chatId = randomJid()
|
||||||
const chats: Partial<Chat>[] = []
|
const chats: Partial<Chat>[] = []
|
||||||
|
|
||||||
@@ -65,7 +64,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(chats).toHaveLength(1)
|
expect(chats).toHaveLength(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should overwrite a chats.update event', async() => {
|
it('should overwrite a chats.update event', async () => {
|
||||||
const chatId = randomJid()
|
const chatId = randomJid()
|
||||||
const chatsDeleted: string[] = []
|
const chatsDeleted: string[] = []
|
||||||
|
|
||||||
@@ -82,7 +81,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(chatsDeleted).toHaveLength(1)
|
expect(chatsDeleted).toHaveLength(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should release a conditional update at the right time', async() => {
|
it('should release a conditional update at the right time', async () => {
|
||||||
const chatId = randomJid()
|
const chatId = randomJid()
|
||||||
const chatId2 = randomJid()
|
const chatId2 = randomJid()
|
||||||
const chatsUpserted: Chat[] = []
|
const chatsUpserted: Chat[] = []
|
||||||
@@ -93,41 +92,49 @@ describe('Event Buffer Tests', () => {
|
|||||||
ev.on('chats.update', () => fail('not should have emitted'))
|
ev.on('chats.update', () => fail('not should have emitted'))
|
||||||
|
|
||||||
ev.buffer()
|
ev.buffer()
|
||||||
ev.emit('chats.update', [{
|
ev.emit('chats.update', [
|
||||||
|
{
|
||||||
id: chatId,
|
id: chatId,
|
||||||
archived: true,
|
archived: true,
|
||||||
conditional(buff) {
|
conditional(buff) {
|
||||||
if(buff.chatUpserts[chatId]) {
|
if (buff.chatUpserts[chatId]) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}])
|
}
|
||||||
ev.emit('chats.update', [{
|
])
|
||||||
|
ev.emit('chats.update', [
|
||||||
|
{
|
||||||
id: chatId2,
|
id: chatId2,
|
||||||
archived: true,
|
archived: true,
|
||||||
conditional(buff) {
|
conditional(buff) {
|
||||||
if(buff.historySets.chats[chatId2]) {
|
if (buff.historySets.chats[chatId2]) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}])
|
}
|
||||||
|
])
|
||||||
|
|
||||||
ev.flush()
|
ev.flush()
|
||||||
|
|
||||||
ev.buffer()
|
ev.buffer()
|
||||||
ev.emit('chats.upsert', [{
|
ev.emit('chats.upsert', [
|
||||||
|
{
|
||||||
id: chatId,
|
id: chatId,
|
||||||
conversationTimestamp: 123,
|
conversationTimestamp: 123,
|
||||||
unreadCount: 1,
|
unreadCount: 1,
|
||||||
muteEndTime: 123
|
muteEndTime: 123
|
||||||
}])
|
}
|
||||||
|
])
|
||||||
ev.emit('messaging-history.set', {
|
ev.emit('messaging-history.set', {
|
||||||
chats: [{
|
chats: [
|
||||||
|
{
|
||||||
id: chatId2,
|
id: chatId2,
|
||||||
conversationTimestamp: 123,
|
conversationTimestamp: 123,
|
||||||
unreadCount: 1,
|
unreadCount: 1,
|
||||||
muteEndTime: 123
|
muteEndTime: 123
|
||||||
}],
|
}
|
||||||
|
],
|
||||||
contacts: [],
|
contacts: [],
|
||||||
messages: [],
|
messages: [],
|
||||||
isLatest: false
|
isLatest: false
|
||||||
@@ -144,7 +151,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(chatsSynced[0].archived).toEqual(true)
|
expect(chatsSynced[0].archived).toEqual(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should discard a conditional update', async() => {
|
it('should discard a conditional update', async () => {
|
||||||
const chatId = randomJid()
|
const chatId = randomJid()
|
||||||
const chatsUpserted: Chat[] = []
|
const chatsUpserted: Chat[] = []
|
||||||
|
|
||||||
@@ -152,21 +159,25 @@ describe('Event Buffer Tests', () => {
|
|||||||
ev.on('chats.update', () => fail('not should have emitted'))
|
ev.on('chats.update', () => fail('not should have emitted'))
|
||||||
|
|
||||||
ev.buffer()
|
ev.buffer()
|
||||||
ev.emit('chats.update', [{
|
ev.emit('chats.update', [
|
||||||
|
{
|
||||||
id: chatId,
|
id: chatId,
|
||||||
archived: true,
|
archived: true,
|
||||||
conditional(buff) {
|
conditional(buff) {
|
||||||
if(buff.chatUpserts[chatId]) {
|
if (buff.chatUpserts[chatId]) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}])
|
}
|
||||||
ev.emit('chats.upsert', [{
|
])
|
||||||
|
ev.emit('chats.upsert', [
|
||||||
|
{
|
||||||
id: chatId,
|
id: chatId,
|
||||||
conversationTimestamp: 123,
|
conversationTimestamp: 123,
|
||||||
unreadCount: 1,
|
unreadCount: 1,
|
||||||
muteEndTime: 123
|
muteEndTime: 123
|
||||||
}])
|
}
|
||||||
|
])
|
||||||
|
|
||||||
ev.flush()
|
ev.flush()
|
||||||
|
|
||||||
@@ -174,7 +185,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(chatsUpserted[0].archived).toBeUndefined()
|
expect(chatsUpserted[0].archived).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should overwrite a chats.update event with a history event', async() => {
|
it('should overwrite a chats.update event with a history event', async () => {
|
||||||
const chatId = randomJid()
|
const chatId = randomJid()
|
||||||
let chatRecv: Chat | undefined
|
let chatRecv: Chat | undefined
|
||||||
|
|
||||||
@@ -199,7 +210,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(chatRecv?.archived).toBeTruthy()
|
expect(chatRecv?.archived).toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should buffer message upsert events', async() => {
|
it('should buffer message upsert events', async () => {
|
||||||
const messageTimestamp = unixTimestampSeconds()
|
const messageTimestamp = unixTimestampSeconds()
|
||||||
const msg: proto.IWebMessageInfo = {
|
const msg: proto.IWebMessageInfo = {
|
||||||
key: {
|
key: {
|
||||||
@@ -235,7 +246,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(msgs[0].status).toEqual(WAMessageStatus.READ)
|
expect(msgs[0].status).toEqual(WAMessageStatus.READ)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should buffer a message receipt update', async() => {
|
it('should buffer a message receipt update', async () => {
|
||||||
const msg: proto.IWebMessageInfo = {
|
const msg: proto.IWebMessageInfo = {
|
||||||
key: {
|
key: {
|
||||||
remoteJid: randomJid(),
|
remoteJid: randomJid(),
|
||||||
@@ -269,7 +280,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(msgs[0].userReceipt).toHaveLength(1)
|
expect(msgs[0].userReceipt).toHaveLength(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should buffer multiple status updates', async() => {
|
it('should buffer multiple status updates', async () => {
|
||||||
const key: WAMessageKey = {
|
const key: WAMessageKey = {
|
||||||
remoteJid: randomJid(),
|
remoteJid: randomJid(),
|
||||||
id: generateMessageID(),
|
id: generateMessageID(),
|
||||||
@@ -290,7 +301,7 @@ describe('Event Buffer Tests', () => {
|
|||||||
expect(msgs[0].update.status).toEqual(WAMessageStatus.READ)
|
expect(msgs[0].update.status).toEqual(WAMessageStatus.READ)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should remove chat unread counter', async() => {
|
it('should remove chat unread counter', async () => {
|
||||||
const msg: proto.IWebMessageInfo = {
|
const msg: proto.IWebMessageInfo = {
|
||||||
key: {
|
key: {
|
||||||
remoteJid: '12345@s.whatsapp.net',
|
remoteJid: '12345@s.whatsapp.net',
|
||||||
|
|||||||
@@ -5,24 +5,18 @@ import { makeMockSignalKeyStore } from './utils'
|
|||||||
logger.level = 'trace'
|
logger.level = 'trace'
|
||||||
|
|
||||||
describe('Key Store w Transaction Tests', () => {
|
describe('Key Store w Transaction Tests', () => {
|
||||||
|
|
||||||
const rawStore = makeMockSignalKeyStore()
|
const rawStore = makeMockSignalKeyStore()
|
||||||
const store = addTransactionCapability(
|
const store = addTransactionCapability(rawStore, logger, {
|
||||||
rawStore,
|
|
||||||
logger,
|
|
||||||
{
|
|
||||||
maxCommitRetries: 1,
|
maxCommitRetries: 1,
|
||||||
delayBetweenTriesMs: 10
|
delayBetweenTriesMs: 10
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
it('should use transaction cache when mutated', async() => {
|
it('should use transaction cache when mutated', async () => {
|
||||||
const key = '123'
|
const key = '123'
|
||||||
const value = new Uint8Array(1)
|
const value = new Uint8Array(1)
|
||||||
const ogGet = rawStore.get
|
const ogGet = rawStore.get
|
||||||
await store.transaction(
|
await store.transaction(async () => {
|
||||||
async() => {
|
await store.set({ session: { [key]: value } })
|
||||||
await store.set({ 'session': { [key]: value } })
|
|
||||||
|
|
||||||
rawStore.get = () => {
|
rawStore.get = () => {
|
||||||
throw new Error('should not have been called')
|
throw new Error('should not have been called')
|
||||||
@@ -30,30 +24,25 @@ describe('Key Store w Transaction Tests', () => {
|
|||||||
|
|
||||||
const { [key]: stored } = await store.get('session', [key])
|
const { [key]: stored } = await store.get('session', [key])
|
||||||
expect(stored).toEqual(new Uint8Array(1))
|
expect(stored).toEqual(new Uint8Array(1))
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
rawStore.get = ogGet
|
rawStore.get = ogGet
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should not commit a failed transaction', async() => {
|
it('should not commit a failed transaction', async () => {
|
||||||
const key = 'abcd'
|
const key = 'abcd'
|
||||||
await expect(
|
await expect(
|
||||||
store.transaction(
|
store.transaction(async () => {
|
||||||
async() => {
|
await store.set({ session: { [key]: new Uint8Array(1) } })
|
||||||
await store.set({ 'session': { [key]: new Uint8Array(1) } })
|
|
||||||
throw new Error('fail')
|
throw new Error('fail')
|
||||||
}
|
})
|
||||||
)
|
).rejects.toThrowError('fail')
|
||||||
).rejects.toThrowError(
|
|
||||||
'fail'
|
|
||||||
)
|
|
||||||
|
|
||||||
const { [key]: stored } = await store.get('session', [key])
|
const { [key]: stored } = await store.get('session', [key])
|
||||||
expect(stored).toBeUndefined()
|
expect(stored).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should handle overlapping transactions', async() => {
|
it('should handle overlapping transactions', async () => {
|
||||||
// promise to let transaction 2
|
// promise to let transaction 2
|
||||||
// know that transaction 1 has started
|
// know that transaction 1 has started
|
||||||
let promiseResolve: () => void
|
let promiseResolve: () => void
|
||||||
@@ -61,10 +50,9 @@ describe('Key Store w Transaction Tests', () => {
|
|||||||
promiseResolve = resolve
|
promiseResolve = resolve
|
||||||
})
|
})
|
||||||
|
|
||||||
store.transaction(
|
store.transaction(async () => {
|
||||||
async() => {
|
|
||||||
await store.set({
|
await store.set({
|
||||||
'session': {
|
session: {
|
||||||
'1': new Uint8Array(1)
|
'1': new Uint8Array(1)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -72,17 +60,14 @@ describe('Key Store w Transaction Tests', () => {
|
|||||||
await delay(5)
|
await delay(5)
|
||||||
// reolve the promise to let the other transaction continue
|
// reolve the promise to let the other transaction continue
|
||||||
promiseResolve()
|
promiseResolve()
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
await store.transaction(
|
await store.transaction(async () => {
|
||||||
async() => {
|
|
||||||
await promise
|
await promise
|
||||||
await delay(5)
|
await delay(5)
|
||||||
|
|
||||||
expect(store.isInTransaction()).toBe(true)
|
expect(store.isInTransaction()).toBe(true)
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
expect(store.isInTransaction()).toBe(false)
|
expect(store.isInTransaction()).toBe(false)
|
||||||
// ensure that the transaction were committed
|
// ensure that the transaction were committed
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ import { SignalAuthState, SignalDataTypeMap } from '../Types'
|
|||||||
import { Curve, generateRegistrationId, generateSignalPubKey, signedKeyPair } from '../Utils'
|
import { Curve, generateRegistrationId, generateSignalPubKey, signedKeyPair } from '../Utils'
|
||||||
|
|
||||||
describe('Signal Tests', () => {
|
describe('Signal Tests', () => {
|
||||||
|
it('should correctly encrypt/decrypt 1 message', async () => {
|
||||||
it('should correctly encrypt/decrypt 1 message', async() => {
|
|
||||||
const user1 = makeUser()
|
const user1 = makeUser()
|
||||||
const user2 = makeUser()
|
const user2 = makeUser()
|
||||||
|
|
||||||
@@ -12,39 +11,31 @@ describe('Signal Tests', () => {
|
|||||||
|
|
||||||
await prepareForSendingMessage(user1, user2)
|
await prepareForSendingMessage(user1, user2)
|
||||||
|
|
||||||
const result = await user1.repository.encryptMessage(
|
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
|
||||||
{ jid: user2.jid, data: msg }
|
|
||||||
)
|
|
||||||
|
|
||||||
const dec = await user2.repository.decryptMessage(
|
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
|
||||||
{ jid: user1.jid, ...result }
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(dec).toEqual(msg)
|
expect(dec).toEqual(msg)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should correctly override a session', async() => {
|
it('should correctly override a session', async () => {
|
||||||
const user1 = makeUser()
|
const user1 = makeUser()
|
||||||
const user2 = makeUser()
|
const user2 = makeUser()
|
||||||
|
|
||||||
const msg = Buffer.from('hello there!')
|
const msg = Buffer.from('hello there!')
|
||||||
|
|
||||||
for(let preKeyId = 2; preKeyId <= 3;preKeyId++) {
|
for (let preKeyId = 2; preKeyId <= 3; preKeyId++) {
|
||||||
await prepareForSendingMessage(user1, user2, preKeyId)
|
await prepareForSendingMessage(user1, user2, preKeyId)
|
||||||
|
|
||||||
const result = await user1.repository.encryptMessage(
|
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
|
||||||
{ jid: user2.jid, data: msg }
|
|
||||||
)
|
|
||||||
|
|
||||||
const dec = await user2.repository.decryptMessage(
|
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
|
||||||
{ jid: user1.jid, ...result }
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(dec).toEqual(msg)
|
expect(dec).toEqual(msg)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should correctly encrypt/decrypt multiple messages', async() => {
|
it('should correctly encrypt/decrypt multiple messages', async () => {
|
||||||
const user1 = makeUser()
|
const user1 = makeUser()
|
||||||
const user2 = makeUser()
|
const user2 = makeUser()
|
||||||
|
|
||||||
@@ -52,56 +43,46 @@ describe('Signal Tests', () => {
|
|||||||
|
|
||||||
await prepareForSendingMessage(user1, user2)
|
await prepareForSendingMessage(user1, user2)
|
||||||
|
|
||||||
for(let i = 0;i < 10;i++) {
|
for (let i = 0; i < 10; i++) {
|
||||||
const result = await user1.repository.encryptMessage(
|
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
|
||||||
{ jid: user2.jid, data: msg }
|
|
||||||
)
|
|
||||||
|
|
||||||
const dec = await user2.repository.decryptMessage(
|
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
|
||||||
{ jid: user1.jid, ...result }
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(dec).toEqual(msg)
|
expect(dec).toEqual(msg)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should encrypt/decrypt messages from group', async() => {
|
it('should encrypt/decrypt messages from group', async () => {
|
||||||
const groupId = '123456@g.us'
|
const groupId = '123456@g.us'
|
||||||
const participants = [...Array(5)].map(makeUser)
|
const participants = [...Array(5)].map(makeUser)
|
||||||
|
|
||||||
const msg = Buffer.from('hello there!')
|
const msg = Buffer.from('hello there!')
|
||||||
|
|
||||||
const sender = participants[0]
|
const sender = participants[0]
|
||||||
const enc = await sender.repository.encryptGroupMessage(
|
const enc = await sender.repository.encryptGroupMessage({
|
||||||
{
|
|
||||||
group: groupId,
|
group: groupId,
|
||||||
meId: sender.jid,
|
meId: sender.jid,
|
||||||
data: msg
|
data: msg
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
for(const participant of participants) {
|
for (const participant of participants) {
|
||||||
if(participant === sender) {
|
if (participant === sender) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
await participant.repository.processSenderKeyDistributionMessage(
|
await participant.repository.processSenderKeyDistributionMessage({
|
||||||
{
|
|
||||||
item: {
|
item: {
|
||||||
groupId,
|
groupId,
|
||||||
axolotlSenderKeyDistributionMessage: enc.senderKeyDistributionMessage
|
axolotlSenderKeyDistributionMessage: enc.senderKeyDistributionMessage
|
||||||
},
|
},
|
||||||
authorJid: sender.jid
|
authorJid: sender.jid
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
const dec = await participant.repository.decryptGroupMessage(
|
const dec = await participant.repository.decryptGroupMessage({
|
||||||
{
|
|
||||||
group: groupId,
|
group: groupId,
|
||||||
authorJid: sender.jid,
|
authorJid: sender.jid,
|
||||||
msg: enc.ciphertext
|
msg: enc.ciphertext
|
||||||
}
|
})
|
||||||
)
|
|
||||||
expect(dec).toEqual(msg)
|
expect(dec).toEqual(msg)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -116,14 +97,9 @@ function makeUser() {
|
|||||||
return { store, jid, repository }
|
return { store, jid, repository }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function prepareForSendingMessage(
|
async function prepareForSendingMessage(sender: User, receiver: User, preKeyId = 2) {
|
||||||
sender: User,
|
|
||||||
receiver: User,
|
|
||||||
preKeyId = 2
|
|
||||||
) {
|
|
||||||
const preKey = Curve.generateKeyPair()
|
const preKey = Curve.generateKeyPair()
|
||||||
await sender.repository.injectE2ESession(
|
await sender.repository.injectE2ESession({
|
||||||
{
|
|
||||||
jid: receiver.jid,
|
jid: receiver.jid,
|
||||||
session: {
|
session: {
|
||||||
registrationId: receiver.store.creds.registrationId,
|
registrationId: receiver.store.creds.registrationId,
|
||||||
@@ -131,15 +107,14 @@ async function prepareForSendingMessage(
|
|||||||
signedPreKey: {
|
signedPreKey: {
|
||||||
keyId: receiver.store.creds.signedPreKey.keyId,
|
keyId: receiver.store.creds.signedPreKey.keyId,
|
||||||
publicKey: generateSignalPubKey(receiver.store.creds.signedPreKey.keyPair.public),
|
publicKey: generateSignalPubKey(receiver.store.creds.signedPreKey.keyPair.public),
|
||||||
signature: receiver.store.creds.signedPreKey.signature,
|
signature: receiver.store.creds.signedPreKey.signature
|
||||||
},
|
},
|
||||||
preKey: {
|
preKey: {
|
||||||
keyId: preKeyId,
|
keyId: preKeyId,
|
||||||
publicKey: generateSignalPubKey(preKey.public),
|
publicKey: generateSignalPubKey(preKey.public)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
await receiver.store.keys.set({
|
await receiver.store.keys.set({
|
||||||
'pre-key': {
|
'pre-key': {
|
||||||
@@ -156,14 +131,14 @@ function makeTestAuthState(): SignalAuthState {
|
|||||||
creds: {
|
creds: {
|
||||||
signedIdentityKey: identityKey,
|
signedIdentityKey: identityKey,
|
||||||
registrationId: generateRegistrationId(),
|
registrationId: generateRegistrationId(),
|
||||||
signedPreKey: signedKeyPair(identityKey, 1),
|
signedPreKey: signedKeyPair(identityKey, 1)
|
||||||
},
|
},
|
||||||
keys: {
|
keys: {
|
||||||
get(type, ids) {
|
get(type, ids) {
|
||||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||||
for(const id of ids) {
|
for (const id of ids) {
|
||||||
const item = store[getUniqueId(type, id)]
|
const item = store[getUniqueId(type, id)]
|
||||||
if(typeof item !== 'undefined') {
|
if (typeof item !== 'undefined') {
|
||||||
data[id] = item
|
data[id] = item
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -171,12 +146,12 @@ function makeTestAuthState(): SignalAuthState {
|
|||||||
return data
|
return data
|
||||||
},
|
},
|
||||||
set(data) {
|
set(data) {
|
||||||
for(const type in data) {
|
for (const type in data) {
|
||||||
for(const id in data[type]) {
|
for (const id in data[type]) {
|
||||||
store[getUniqueId(type, id)] = data[type][id]
|
store[getUniqueId(type, id)] = data[type][id]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,38 +31,37 @@ const TEST_VECTORS: TestVector[] = [
|
|||||||
)
|
)
|
||||||
),
|
),
|
||||||
plaintext: readFileSync('./Media/icon.png')
|
plaintext: readFileSync('./Media/icon.png')
|
||||||
},
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
describe('Media Download Tests', () => {
|
describe('Media Download Tests', () => {
|
||||||
|
it('should download a full encrypted media correctly', async () => {
|
||||||
it('should download a full encrypted media correctly', async() => {
|
for (const { type, message, plaintext } of TEST_VECTORS) {
|
||||||
for(const { type, message, plaintext } of TEST_VECTORS) {
|
|
||||||
const readPipe = await downloadContentFromMessage(message, type)
|
const readPipe = await downloadContentFromMessage(message, type)
|
||||||
|
|
||||||
let buffer = Buffer.alloc(0)
|
let buffer = Buffer.alloc(0)
|
||||||
for await (const read of readPipe) {
|
for await (const read of readPipe) {
|
||||||
buffer = Buffer.concat([ buffer, read ])
|
buffer = Buffer.concat([buffer, read])
|
||||||
}
|
}
|
||||||
|
|
||||||
expect(buffer).toEqual(plaintext)
|
expect(buffer).toEqual(plaintext)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should download an encrypted media correctly piece', async() => {
|
it('should download an encrypted media correctly piece', async () => {
|
||||||
for(const { type, message, plaintext } of TEST_VECTORS) {
|
for (const { type, message, plaintext } of TEST_VECTORS) {
|
||||||
// check all edge cases
|
// check all edge cases
|
||||||
const ranges = [
|
const ranges = [
|
||||||
{ startByte: 51, endByte: plaintext.length - 100 }, // random numbers
|
{ startByte: 51, endByte: plaintext.length - 100 }, // random numbers
|
||||||
{ startByte: 1024, endByte: 2038 }, // larger random multiples of 16
|
{ startByte: 1024, endByte: 2038 }, // larger random multiples of 16
|
||||||
{ startByte: 1, endByte: plaintext.length - 1 } // borders
|
{ startByte: 1, endByte: plaintext.length - 1 } // borders
|
||||||
]
|
]
|
||||||
for(const range of ranges) {
|
for (const range of ranges) {
|
||||||
const readPipe = await downloadContentFromMessage(message, type, range)
|
const readPipe = await downloadContentFromMessage(message, type, range)
|
||||||
|
|
||||||
let buffer = Buffer.alloc(0)
|
let buffer = Buffer.alloc(0)
|
||||||
for await (const read of readPipe) {
|
for await (const read of readPipe) {
|
||||||
buffer = Buffer.concat([ buffer, read ])
|
buffer = Buffer.concat([buffer, read])
|
||||||
}
|
}
|
||||||
|
|
||||||
const hex = buffer.toString('hex')
|
const hex = buffer.toString('hex')
|
||||||
|
|||||||
@@ -2,9 +2,8 @@ import { WAMessageContent } from '../Types'
|
|||||||
import { normalizeMessageContent } from '../Utils'
|
import { normalizeMessageContent } from '../Utils'
|
||||||
|
|
||||||
describe('Messages Tests', () => {
|
describe('Messages Tests', () => {
|
||||||
|
|
||||||
it('should correctly unwrap messages', () => {
|
it('should correctly unwrap messages', () => {
|
||||||
const CONTENT = { imageMessage: { } }
|
const CONTENT = { imageMessage: {} }
|
||||||
expectRightContent(CONTENT)
|
expectRightContent(CONTENT)
|
||||||
expectRightContent({
|
expectRightContent({
|
||||||
ephemeralMessage: { message: CONTENT }
|
ephemeralMessage: { message: CONTENT }
|
||||||
@@ -29,9 +28,7 @@ describe('Messages Tests', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
function expectRightContent(content: WAMessageContent) {
|
function expectRightContent(content: WAMessageContent) {
|
||||||
expect(
|
expect(normalizeMessageContent(content)).toHaveProperty('imageMessage')
|
||||||
normalizeMessageContent(content)
|
|
||||||
).toHaveProperty('imageMessage')
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -11,10 +11,10 @@ export function makeMockSignalKeyStore(): SignalKeyStore {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
get(type, ids) {
|
get(type, ids) {
|
||||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||||
for(const id of ids) {
|
for (const id of ids) {
|
||||||
const item = store[getUniqueId(type, id)]
|
const item = store[getUniqueId(type, id)]
|
||||||
if(typeof item !== 'undefined') {
|
if (typeof item !== 'undefined') {
|
||||||
data[id] = item
|
data[id] = item
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,12 +22,12 @@ export function makeMockSignalKeyStore(): SignalKeyStore {
|
|||||||
return data
|
return data
|
||||||
},
|
},
|
||||||
set(data) {
|
set(data) {
|
||||||
for(const type in data) {
|
for (const type in data) {
|
||||||
for(const id in data[type]) {
|
for (const id in data[type]) {
|
||||||
store[getUniqueId(type, id)] = data[type][id]
|
store[getUniqueId(type, id)] = data[type][id]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getUniqueId(type: string, id: string) {
|
function getUniqueId(type: string, id: string) {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { proto } from '../../WAProto'
|
|||||||
import type { Contact } from './Contact'
|
import type { Contact } from './Contact'
|
||||||
import type { MinimalMessage } from './Message'
|
import type { MinimalMessage } from './Message'
|
||||||
|
|
||||||
export type KeyPair = { public: Uint8Array, private: Uint8Array }
|
export type KeyPair = { public: Uint8Array; private: Uint8Array }
|
||||||
export type SignedKeyPair = {
|
export type SignedKeyPair = {
|
||||||
keyPair: KeyPair
|
keyPair: KeyPair
|
||||||
signature: Uint8Array
|
signature: Uint8Array
|
||||||
@@ -67,7 +67,7 @@ export type AuthenticationCreds = SignalCreds & {
|
|||||||
|
|
||||||
export type SignalDataTypeMap = {
|
export type SignalDataTypeMap = {
|
||||||
'pre-key': KeyPair
|
'pre-key': KeyPair
|
||||||
'session': Uint8Array
|
session: Uint8Array
|
||||||
'sender-key': Uint8Array
|
'sender-key': Uint8Array
|
||||||
'sender-key-memory': { [jid: string]: boolean }
|
'sender-key-memory': { [jid: string]: boolean }
|
||||||
'app-state-sync-key': proto.Message.IAppStateSyncKeyData
|
'app-state-sync-key': proto.Message.IAppStateSyncKeyData
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate'
|
export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate'
|
||||||
|
|
||||||
export type WACallEvent = {
|
export type WACallEvent = {
|
||||||
|
|||||||
@@ -22,9 +22,15 @@ export type WAPrivacyMessagesValue = 'all' | 'contacts'
|
|||||||
/** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
|
/** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
|
||||||
export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused'
|
export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused'
|
||||||
|
|
||||||
export const ALL_WA_PATCH_NAMES = ['critical_block', 'critical_unblock_low', 'regular_high', 'regular_low', 'regular'] as const
|
export const ALL_WA_PATCH_NAMES = [
|
||||||
|
'critical_block',
|
||||||
|
'critical_unblock_low',
|
||||||
|
'regular_high',
|
||||||
|
'regular_low',
|
||||||
|
'regular'
|
||||||
|
] as const
|
||||||
|
|
||||||
export type WAPatchName = typeof ALL_WA_PATCH_NAMES[number]
|
export type WAPatchName = (typeof ALL_WA_PATCH_NAMES)[number]
|
||||||
|
|
||||||
export interface PresenceData {
|
export interface PresenceData {
|
||||||
lastKnownPresence: WAPresence
|
lastKnownPresence: WAPresence
|
||||||
@@ -54,7 +60,8 @@ export type Chat = proto.IConversation & {
|
|||||||
lastMessageRecvTimestamp?: number
|
lastMessageRecvTimestamp?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ChatUpdate = Partial<Chat & {
|
export type ChatUpdate = Partial<
|
||||||
|
Chat & {
|
||||||
/**
|
/**
|
||||||
* if specified in the update,
|
* if specified in the update,
|
||||||
* the EV buffer will check if the condition gets fulfilled before applying the update
|
* the EV buffer will check if the condition gets fulfilled before applying the update
|
||||||
@@ -65,7 +72,8 @@ export type ChatUpdate = Partial<Chat & {
|
|||||||
* undefined if the condition is not yet fulfilled
|
* undefined if the condition is not yet fulfilled
|
||||||
* */
|
* */
|
||||||
conditional: (bufferedData: BufferedEventData) => boolean | undefined
|
conditional: (bufferedData: BufferedEventData) => boolean | undefined
|
||||||
}>
|
}
|
||||||
|
>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* the last messages in a chat, sorted reverse-chronologically. That is, the latest message should be first in the chat
|
* the last messages in a chat, sorted reverse-chronologically. That is, the latest message should be first in the chat
|
||||||
@@ -74,7 +82,7 @@ export type ChatUpdate = Partial<Chat & {
|
|||||||
export type LastMessageList = MinimalMessage[] | proto.SyncActionValue.ISyncActionMessageRange
|
export type LastMessageList = MinimalMessage[] | proto.SyncActionValue.ISyncActionMessageRange
|
||||||
|
|
||||||
export type ChatModification =
|
export type ChatModification =
|
||||||
{
|
| {
|
||||||
archive: boolean
|
archive: boolean
|
||||||
lastMessages: LastMessageList
|
lastMessages: LastMessageList
|
||||||
}
|
}
|
||||||
@@ -86,12 +94,13 @@ export type ChatModification =
|
|||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
clear: boolean
|
clear: boolean
|
||||||
} | {
|
}
|
||||||
deleteForMe: { deleteMedia: boolean, key: WAMessageKey, timestamp: number }
|
| {
|
||||||
|
deleteForMe: { deleteMedia: boolean; key: WAMessageKey; timestamp: number }
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
star: {
|
star: {
|
||||||
messages: { id: string, fromMe?: boolean }[]
|
messages: { id: string; fromMe?: boolean }[]
|
||||||
star: boolean
|
star: boolean
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -99,7 +108,7 @@ export type ChatModification =
|
|||||||
markRead: boolean
|
markRead: boolean
|
||||||
lastMessages: LastMessageList
|
lastMessages: LastMessageList
|
||||||
}
|
}
|
||||||
| { delete: true, lastMessages: LastMessageList }
|
| { delete: true; lastMessages: LastMessageList }
|
||||||
// Label
|
// Label
|
||||||
| { addLabel: LabelActionBody }
|
| { addLabel: LabelActionBody }
|
||||||
// Label assosiation
|
// Label assosiation
|
||||||
|
|||||||
@@ -29,42 +29,48 @@ export type BaileysEventMap = {
|
|||||||
'chats.upsert': Chat[]
|
'chats.upsert': Chat[]
|
||||||
/** update the given chats */
|
/** update the given chats */
|
||||||
'chats.update': ChatUpdate[]
|
'chats.update': ChatUpdate[]
|
||||||
'chats.phoneNumberShare': {lid: string, jid: string}
|
'chats.phoneNumberShare': { lid: string; jid: string }
|
||||||
/** delete chats with given ID */
|
/** delete chats with given ID */
|
||||||
'chats.delete': string[]
|
'chats.delete': string[]
|
||||||
/** presence of contact in a chat updated */
|
/** presence of contact in a chat updated */
|
||||||
'presence.update': { id: string, presences: { [participant: string]: PresenceData } }
|
'presence.update': { id: string; presences: { [participant: string]: PresenceData } }
|
||||||
|
|
||||||
'contacts.upsert': Contact[]
|
'contacts.upsert': Contact[]
|
||||||
'contacts.update': Partial<Contact>[]
|
'contacts.update': Partial<Contact>[]
|
||||||
|
|
||||||
'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
|
'messages.delete': { keys: WAMessageKey[] } | { jid: string; all: true }
|
||||||
'messages.update': WAMessageUpdate[]
|
'messages.update': WAMessageUpdate[]
|
||||||
'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
|
'messages.media-update': { key: WAMessageKey; media?: { ciphertext: Uint8Array; iv: Uint8Array }; error?: Boom }[]
|
||||||
/**
|
/**
|
||||||
* add/update the given messages. If they were received while the connection was online,
|
* add/update the given messages. If they were received while the connection was online,
|
||||||
* the update will have type: "notify"
|
* the update will have type: "notify"
|
||||||
* if requestId is provided, then the messages was received from the phone due to it being unavailable
|
* if requestId is provided, then the messages was received from the phone due to it being unavailable
|
||||||
* */
|
* */
|
||||||
'messages.upsert': { messages: WAMessage[], type: MessageUpsertType, requestId?: string }
|
'messages.upsert': { messages: WAMessage[]; type: MessageUpsertType; requestId?: string }
|
||||||
/** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
|
/** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
|
||||||
'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]
|
'messages.reaction': { key: WAMessageKey; reaction: proto.IReaction }[]
|
||||||
|
|
||||||
'message-receipt.update': MessageUserReceiptUpdate[]
|
'message-receipt.update': MessageUserReceiptUpdate[]
|
||||||
|
|
||||||
'groups.upsert': GroupMetadata[]
|
'groups.upsert': GroupMetadata[]
|
||||||
'groups.update': Partial<GroupMetadata>[]
|
'groups.update': Partial<GroupMetadata>[]
|
||||||
/** apply an action to participants in a group */
|
/** apply an action to participants in a group */
|
||||||
'group-participants.update': { id: string, author: string, participants: string[], action: ParticipantAction }
|
'group-participants.update': { id: string; author: string; participants: string[]; action: ParticipantAction }
|
||||||
'group.join-request': { id: string, author: string, participant: string, action: RequestJoinAction, method: RequestJoinMethod }
|
'group.join-request': {
|
||||||
|
id: string
|
||||||
|
author: string
|
||||||
|
participant: string
|
||||||
|
action: RequestJoinAction
|
||||||
|
method: RequestJoinMethod
|
||||||
|
}
|
||||||
|
|
||||||
'blocklist.set': { blocklist: string[] }
|
'blocklist.set': { blocklist: string[] }
|
||||||
'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
|
'blocklist.update': { blocklist: string[]; type: 'add' | 'remove' }
|
||||||
|
|
||||||
/** Receive an update on a call, including when the call was received, rejected, accepted */
|
/** Receive an update on a call, including when the call was received, rejected, accepted */
|
||||||
'call': WACallEvent[]
|
call: WACallEvent[]
|
||||||
'labels.edit': Label
|
'labels.edit': Label
|
||||||
'labels.association': { association: LabelAssociation, type: 'add' | 'remove' }
|
'labels.association': { association: LabelAssociation; type: 'add' | 'remove' }
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BufferedEventData = {
|
export type BufferedEventData = {
|
||||||
@@ -83,11 +89,11 @@ export type BufferedEventData = {
|
|||||||
chatDeletes: Set<string>
|
chatDeletes: Set<string>
|
||||||
contactUpserts: { [jid: string]: Contact }
|
contactUpserts: { [jid: string]: Contact }
|
||||||
contactUpdates: { [jid: string]: Partial<Contact> }
|
contactUpdates: { [jid: string]: Partial<Contact> }
|
||||||
messageUpserts: { [key: string]: { type: MessageUpsertType, message: WAMessage } }
|
messageUpserts: { [key: string]: { type: MessageUpsertType; message: WAMessage } }
|
||||||
messageUpdates: { [key: string]: WAMessageUpdate }
|
messageUpdates: { [key: string]: WAMessageUpdate }
|
||||||
messageDeletes: { [key: string]: WAMessageKey }
|
messageDeletes: { [key: string]: WAMessageKey }
|
||||||
messageReactions: { [key: string]: { key: WAMessageKey, reactions: proto.IReaction[] } }
|
messageReactions: { [key: string]: { key: WAMessageKey; reactions: proto.IReaction[] } }
|
||||||
messageReceipts: { [key: string]: { key: WAMessageKey, userReceipt: proto.IUserReceipt[] } }
|
messageReceipts: { [key: string]: { key: WAMessageKey; userReceipt: proto.IUserReceipt[] } }
|
||||||
groupUpdates: { [jid: string]: Partial<GroupMetadata> }
|
groupUpdates: { [jid: string]: Partial<GroupMetadata> }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { Contact } from './Contact'
|
import { Contact } from './Contact'
|
||||||
|
|
||||||
export type GroupParticipant = (Contact & { isAdmin?: boolean, isSuperAdmin?: boolean, admin?: 'admin' | 'superadmin' | null })
|
export type GroupParticipant = Contact & {
|
||||||
|
isAdmin?: boolean
|
||||||
|
isSuperAdmin?: boolean
|
||||||
|
admin?: 'admin' | 'superadmin' | null
|
||||||
|
}
|
||||||
|
|
||||||
export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote' | 'modify'
|
export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote' | 'modify'
|
||||||
|
|
||||||
@@ -46,7 +50,6 @@ export interface GroupMetadata {
|
|||||||
author?: string
|
author?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export interface WAGroupCreateResponse {
|
export interface WAGroupCreateResponse {
|
||||||
status: number
|
status: number
|
||||||
gid?: string
|
gid?: string
|
||||||
|
|||||||
@@ -44,5 +44,5 @@ export enum LabelColor {
|
|||||||
Color17,
|
Color17,
|
||||||
Color18,
|
Color18,
|
||||||
Color19,
|
Color19,
|
||||||
Color20,
|
Color20
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,12 @@ export type WAMessageKey = proto.IMessageKey
|
|||||||
export type WATextMessage = proto.Message.IExtendedTextMessage
|
export type WATextMessage = proto.Message.IExtendedTextMessage
|
||||||
export type WAContextInfo = proto.IContextInfo
|
export type WAContextInfo = proto.IContextInfo
|
||||||
export type WALocationMessage = proto.Message.ILocationMessage
|
export type WALocationMessage = proto.Message.ILocationMessage
|
||||||
export type WAGenericMediaMessage = proto.Message.IVideoMessage | proto.Message.IImageMessage | proto.Message.IAudioMessage | proto.Message.IDocumentMessage | proto.Message.IStickerMessage
|
export type WAGenericMediaMessage =
|
||||||
|
| proto.Message.IVideoMessage
|
||||||
|
| proto.Message.IImageMessage
|
||||||
|
| proto.Message.IAudioMessage
|
||||||
|
| proto.Message.IDocumentMessage
|
||||||
|
| proto.Message.IStickerMessage
|
||||||
export const WAMessageStubType = proto.WebMessageInfo.StubType
|
export const WAMessageStubType = proto.WebMessageInfo.StubType
|
||||||
export const WAMessageStatus = proto.WebMessageInfo.Status
|
export const WAMessageStatus = proto.WebMessageInfo.Status
|
||||||
import { ILogger } from '../Utils/logger'
|
import { ILogger } from '../Utils/logger'
|
||||||
@@ -27,14 +32,22 @@ export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL
|
|||||||
/** Set of message types that are supported by the library */
|
/** Set of message types that are supported by the library */
|
||||||
export type MessageType = keyof proto.Message
|
export type MessageType = keyof proto.Message
|
||||||
|
|
||||||
export type DownloadableMessage = { mediaKey?: Uint8Array | null, directPath?: string | null, url?: string | null }
|
export type DownloadableMessage = { mediaKey?: Uint8Array | null; directPath?: string | null; url?: string | null }
|
||||||
|
|
||||||
export type MessageReceiptType = 'read' | 'read-self' | 'hist_sync' | 'peer_msg' | 'sender' | 'inactive' | 'played' | undefined
|
export type MessageReceiptType =
|
||||||
|
| 'read'
|
||||||
|
| 'read-self'
|
||||||
|
| 'hist_sync'
|
||||||
|
| 'peer_msg'
|
||||||
|
| 'sender'
|
||||||
|
| 'inactive'
|
||||||
|
| 'played'
|
||||||
|
| undefined
|
||||||
|
|
||||||
export type MediaConnInfo = {
|
export type MediaConnInfo = {
|
||||||
auth: string
|
auth: string
|
||||||
ttl: number
|
ttl: number
|
||||||
hosts: { hostname: string, maxContentLengthBytes: number }[]
|
hosts: { hostname: string; maxContentLengthBytes: number }[]
|
||||||
fetchDate: Date
|
fetchDate: Date
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,11 +101,13 @@ type RequestPhoneNumber = {
|
|||||||
|
|
||||||
export type MediaType = keyof typeof MEDIA_HKDF_KEY_MAPPING
|
export type MediaType = keyof typeof MEDIA_HKDF_KEY_MAPPING
|
||||||
export type AnyMediaMessageContent = (
|
export type AnyMediaMessageContent = (
|
||||||
({
|
| ({
|
||||||
image: WAMediaUpload
|
image: WAMediaUpload
|
||||||
caption?: string
|
caption?: string
|
||||||
jpegThumbnail?: string
|
jpegThumbnail?: string
|
||||||
} & Mentionable & Contextable & WithDimensions)
|
} & Mentionable &
|
||||||
|
Contextable &
|
||||||
|
WithDimensions)
|
||||||
| ({
|
| ({
|
||||||
video: WAMediaUpload
|
video: WAMediaUpload
|
||||||
caption?: string
|
caption?: string
|
||||||
@@ -100,7 +115,9 @@ export type AnyMediaMessageContent = (
|
|||||||
jpegThumbnail?: string
|
jpegThumbnail?: string
|
||||||
/** if set to true, will send as a `video note` */
|
/** if set to true, will send as a `video note` */
|
||||||
ptv?: boolean
|
ptv?: boolean
|
||||||
} & Mentionable & Contextable & WithDimensions)
|
} & Mentionable &
|
||||||
|
Contextable &
|
||||||
|
WithDimensions)
|
||||||
| {
|
| {
|
||||||
audio: WAMediaUpload
|
audio: WAMediaUpload
|
||||||
/** if set to true, will send as a `voice note` */
|
/** if set to true, will send as a `voice note` */
|
||||||
@@ -111,13 +128,14 @@ export type AnyMediaMessageContent = (
|
|||||||
| ({
|
| ({
|
||||||
sticker: WAMediaUpload
|
sticker: WAMediaUpload
|
||||||
isAnimated?: boolean
|
isAnimated?: boolean
|
||||||
} & WithDimensions) | ({
|
} & WithDimensions)
|
||||||
|
| ({
|
||||||
document: WAMediaUpload
|
document: WAMediaUpload
|
||||||
mimetype: string
|
mimetype: string
|
||||||
fileName?: string
|
fileName?: string
|
||||||
caption?: string
|
caption?: string
|
||||||
} & Contextable))
|
} & Contextable)
|
||||||
& { mimetype?: string } & Editable
|
) & { mimetype?: string } & Editable
|
||||||
|
|
||||||
export type ButtonReplyInfo = {
|
export type ButtonReplyInfo = {
|
||||||
displayText: string
|
displayText: string
|
||||||
@@ -138,15 +156,18 @@ export type WASendableProduct = Omit<proto.Message.ProductMessage.IProductSnapsh
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type AnyRegularMessageContent = (
|
export type AnyRegularMessageContent = (
|
||||||
({
|
| ({
|
||||||
text: string
|
text: string
|
||||||
linkPreview?: WAUrlInfo | null
|
linkPreview?: WAUrlInfo | null
|
||||||
}
|
} & Mentionable &
|
||||||
& Mentionable & Contextable & Editable)
|
Contextable &
|
||||||
|
Editable)
|
||||||
| AnyMediaMessageContent
|
| AnyMediaMessageContent
|
||||||
| ({
|
| ({
|
||||||
poll: PollMessageOptions
|
poll: PollMessageOptions
|
||||||
} & Mentionable & Contextable & Editable)
|
} & Mentionable &
|
||||||
|
Contextable &
|
||||||
|
Editable)
|
||||||
| {
|
| {
|
||||||
contacts: {
|
contacts: {
|
||||||
displayName?: string
|
displayName?: string
|
||||||
@@ -180,18 +201,25 @@ export type AnyRegularMessageContent = (
|
|||||||
businessOwnerJid?: string
|
businessOwnerJid?: string
|
||||||
body?: string
|
body?: string
|
||||||
footer?: string
|
footer?: string
|
||||||
} | SharePhoneNumber | RequestPhoneNumber
|
}
|
||||||
) & ViewOnce
|
| SharePhoneNumber
|
||||||
|
| RequestPhoneNumber
|
||||||
|
) &
|
||||||
|
ViewOnce
|
||||||
|
|
||||||
export type AnyMessageContent = AnyRegularMessageContent | {
|
export type AnyMessageContent =
|
||||||
|
| AnyRegularMessageContent
|
||||||
|
| {
|
||||||
forward: WAMessage
|
forward: WAMessage
|
||||||
force?: boolean
|
force?: boolean
|
||||||
} | {
|
}
|
||||||
|
| {
|
||||||
/** Delete your message or anyone's message in a group (admin required) */
|
/** Delete your message or anyone's message in a group (admin required) */
|
||||||
delete: WAMessageKey
|
delete: WAMessageKey
|
||||||
} | {
|
}
|
||||||
|
| {
|
||||||
disappearingMessagesInChat: boolean | number
|
disappearingMessagesInChat: boolean | number
|
||||||
}
|
}
|
||||||
|
|
||||||
export type GroupMetadataParticipants = Pick<GroupMetadata, 'participants'>
|
export type GroupMetadataParticipants = Pick<GroupMetadata, 'participants'>
|
||||||
|
|
||||||
@@ -204,7 +232,7 @@ type MinimalRelayOptions = {
|
|||||||
|
|
||||||
export type MessageRelayOptions = MinimalRelayOptions & {
|
export type MessageRelayOptions = MinimalRelayOptions & {
|
||||||
/** only send to a specific participant; used when a message decryption fails for a single user */
|
/** only send to a specific participant; used when a message decryption fails for a single user */
|
||||||
participant?: { jid: string, count: number }
|
participant?: { jid: string; count: number }
|
||||||
/** additional attributes to add to the WA binary node */
|
/** additional attributes to add to the WA binary node */
|
||||||
additionalAttributes?: { [_: string]: string }
|
additionalAttributes?: { [_: string]: string }
|
||||||
additionalNodes?: BinaryNode[]
|
additionalNodes?: BinaryNode[]
|
||||||
@@ -236,7 +264,10 @@ export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions &
|
|||||||
userJid: string
|
userJid: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type WAMediaUploadFunction = (readStream: Readable, opts: { fileEncSha256B64: string, mediaType: MediaType, timeoutMs?: number }) => Promise<{ mediaUrl: string, directPath: string }>
|
export type WAMediaUploadFunction = (
|
||||||
|
readStream: Readable,
|
||||||
|
opts: { fileEncSha256B64: string; mediaType: MediaType; timeoutMs?: number }
|
||||||
|
) => Promise<{ mediaUrl: string; directPath: string }>
|
||||||
|
|
||||||
export type MediaGenerationOptions = {
|
export type MediaGenerationOptions = {
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
@@ -268,11 +299,11 @@ export type MessageUpsertType = 'append' | 'notify'
|
|||||||
|
|
||||||
export type MessageUserReceipt = proto.IUserReceipt
|
export type MessageUserReceipt = proto.IUserReceipt
|
||||||
|
|
||||||
export type WAMessageUpdate = { update: Partial<WAMessage>, key: proto.IMessageKey }
|
export type WAMessageUpdate = { update: Partial<WAMessage>; key: proto.IMessageKey }
|
||||||
|
|
||||||
export type WAMessageCursor = { before: WAMessageKey | undefined } | { after: WAMessageKey | undefined }
|
export type WAMessageCursor = { before: WAMessageKey | undefined } | { after: WAMessageKey | undefined }
|
||||||
|
|
||||||
export type MessageUserReceiptUpdate = { key: proto.IMessageKey, receipt: MessageUserReceipt }
|
export type MessageUserReceiptUpdate = { key: proto.IMessageKey; receipt: MessageUserReceipt }
|
||||||
|
|
||||||
export type MediaDecryptionKeyInfo = {
|
export type MediaDecryptionKeyInfo = {
|
||||||
iv: Buffer
|
iv: Buffer
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { WAMediaUpload } from './Message'
|
|||||||
|
|
||||||
export type CatalogResult = {
|
export type CatalogResult = {
|
||||||
data: {
|
data: {
|
||||||
paging: { cursors: { before: string, after: string } }
|
paging: { cursors: { before: string; after: string } }
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
data: any[]
|
data: any[]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,9 +51,7 @@ type E2ESessionOpts = {
|
|||||||
|
|
||||||
export type SignalRepository = {
|
export type SignalRepository = {
|
||||||
decryptGroupMessage(opts: DecryptGroupSignalOpts): Promise<Uint8Array>
|
decryptGroupMessage(opts: DecryptGroupSignalOpts): Promise<Uint8Array>
|
||||||
processSenderKeyDistributionMessage(
|
processSenderKeyDistributionMessage(opts: ProcessSenderKeyDistributionMessageOpts): Promise<void>
|
||||||
opts: ProcessSenderKeyDistributionMessageOpts
|
|
||||||
): Promise<void>
|
|
||||||
decryptMessage(opts: DecryptSignalProtoOpts): Promise<Uint8Array>
|
decryptMessage(opts: DecryptSignalProtoOpts): Promise<Uint8Array>
|
||||||
encryptMessage(opts: EncryptMessageOpts): Promise<{
|
encryptMessage(opts: EncryptMessageOpts): Promise<{
|
||||||
type: 'pkmsg' | 'msg'
|
type: 'pkmsg' | 'msg'
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
import { AxiosRequestConfig } from 'axios'
|
import { AxiosRequestConfig } from 'axios'
|
||||||
import type { Agent } from 'https'
|
import type { Agent } from 'https'
|
||||||
import type { URL } from 'url'
|
import type { URL } from 'url'
|
||||||
@@ -23,7 +22,7 @@ export type CacheStore = {
|
|||||||
flushAll(): void
|
flushAll(): void
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PatchedMessageWithRecipientJID = proto.IMessage & {recipientJid?: string}
|
export type PatchedMessageWithRecipientJID = proto.IMessage & { recipientJid?: string }
|
||||||
|
|
||||||
export type SocketConfig = {
|
export type SocketConfig = {
|
||||||
/** the WS url to connect to WA */
|
/** the WS url to connect to WA */
|
||||||
@@ -108,8 +107,11 @@ export type SocketConfig = {
|
|||||||
* */
|
* */
|
||||||
patchMessageBeforeSending: (
|
patchMessageBeforeSending: (
|
||||||
msg: proto.IMessage,
|
msg: proto.IMessage,
|
||||||
recipientJids?: string[],
|
recipientJids?: string[]
|
||||||
) => Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> | PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID
|
) =>
|
||||||
|
| Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID>
|
||||||
|
| PatchedMessageWithRecipientJID[]
|
||||||
|
| PatchedMessageWithRecipientJID
|
||||||
|
|
||||||
/** verify app state MACs */
|
/** verify app state MACs */
|
||||||
appStateMacVerification: {
|
appStateMacVerification: {
|
||||||
|
|||||||
@@ -63,4 +63,4 @@ export type WABusinessProfile = {
|
|||||||
address?: string
|
address?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CurveKeyPair = { private: Uint8Array, public: Uint8Array }
|
export type CurveKeyPair = { private: Uint8Array; public: Uint8Array }
|
||||||
|
|||||||
@@ -1,7 +1,15 @@
|
|||||||
import NodeCache from '@cacheable/node-cache'
|
import NodeCache from '@cacheable/node-cache'
|
||||||
import { randomBytes } from 'crypto'
|
import { randomBytes } from 'crypto'
|
||||||
import { DEFAULT_CACHE_TTLS } from '../Defaults'
|
import { DEFAULT_CACHE_TTLS } from '../Defaults'
|
||||||
import type { AuthenticationCreds, CacheStore, SignalDataSet, SignalDataTypeMap, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types'
|
import type {
|
||||||
|
AuthenticationCreds,
|
||||||
|
CacheStore,
|
||||||
|
SignalDataSet,
|
||||||
|
SignalDataTypeMap,
|
||||||
|
SignalKeyStore,
|
||||||
|
SignalKeyStoreWithTransaction,
|
||||||
|
TransactionCapabilityOptions
|
||||||
|
} from '../Types'
|
||||||
import { Curve, signedKeyPair } from './crypto'
|
import { Curve, signedKeyPair } from './crypto'
|
||||||
import { delay, generateRegistrationId } from './generics'
|
import { delay, generateRegistrationId } from './generics'
|
||||||
import { ILogger } from './logger'
|
import { ILogger } from './logger'
|
||||||
@@ -17,10 +25,12 @@ export function makeCacheableSignalKeyStore(
|
|||||||
logger?: ILogger,
|
logger?: ILogger,
|
||||||
_cache?: CacheStore
|
_cache?: CacheStore
|
||||||
): SignalKeyStore {
|
): SignalKeyStore {
|
||||||
const cache = _cache || new NodeCache({
|
const cache =
|
||||||
|
_cache ||
|
||||||
|
new NodeCache({
|
||||||
stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
|
stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
|
||||||
useClones: false,
|
useClones: false,
|
||||||
deleteOnExpire: true,
|
deleteOnExpire: true
|
||||||
})
|
})
|
||||||
|
|
||||||
function getUniqueId(type: string, id: string) {
|
function getUniqueId(type: string, id: string) {
|
||||||
@@ -29,23 +39,23 @@ export function makeCacheableSignalKeyStore(
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
async get(type, ids) {
|
async get(type, ids) {
|
||||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||||
const idsToFetch: string[] = []
|
const idsToFetch: string[] = []
|
||||||
for(const id of ids) {
|
for (const id of ids) {
|
||||||
const item = cache.get<SignalDataTypeMap[typeof type]>(getUniqueId(type, id))
|
const item = cache.get<SignalDataTypeMap[typeof type]>(getUniqueId(type, id))
|
||||||
if(typeof item !== 'undefined') {
|
if (typeof item !== 'undefined') {
|
||||||
data[id] = item
|
data[id] = item
|
||||||
} else {
|
} else {
|
||||||
idsToFetch.push(id)
|
idsToFetch.push(id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(idsToFetch.length) {
|
if (idsToFetch.length) {
|
||||||
logger?.trace({ items: idsToFetch.length }, 'loading from store')
|
logger?.trace({ items: idsToFetch.length }, 'loading from store')
|
||||||
const fetched = await store.get(type, idsToFetch)
|
const fetched = await store.get(type, idsToFetch)
|
||||||
for(const id of idsToFetch) {
|
for (const id of idsToFetch) {
|
||||||
const item = fetched[id]
|
const item = fetched[id]
|
||||||
if(item) {
|
if (item) {
|
||||||
data[id] = item
|
data[id] = item
|
||||||
cache.set(getUniqueId(type, id), item)
|
cache.set(getUniqueId(type, id), item)
|
||||||
}
|
}
|
||||||
@@ -56,8 +66,8 @@ export function makeCacheableSignalKeyStore(
|
|||||||
},
|
},
|
||||||
async set(data) {
|
async set(data) {
|
||||||
let keys = 0
|
let keys = 0
|
||||||
for(const type in data) {
|
for (const type in data) {
|
||||||
for(const id in data[type]) {
|
for (const id in data[type]) {
|
||||||
cache.set(getUniqueId(type, id), data[type][id])
|
cache.set(getUniqueId(type, id), data[type][id])
|
||||||
keys += 1
|
keys += 1
|
||||||
}
|
}
|
||||||
@@ -89,52 +99,45 @@ export const addTransactionCapability = (
|
|||||||
// number of queries made to the DB during the transaction
|
// number of queries made to the DB during the transaction
|
||||||
// only there for logging purposes
|
// only there for logging purposes
|
||||||
let dbQueriesInTransaction = 0
|
let dbQueriesInTransaction = 0
|
||||||
let transactionCache: SignalDataSet = { }
|
let transactionCache: SignalDataSet = {}
|
||||||
let mutations: SignalDataSet = { }
|
let mutations: SignalDataSet = {}
|
||||||
|
|
||||||
let transactionsInProgress = 0
|
let transactionsInProgress = 0
|
||||||
|
|
||||||
return {
|
return {
|
||||||
get: async(type, ids) => {
|
get: async (type, ids) => {
|
||||||
if(isInTransaction()) {
|
if (isInTransaction()) {
|
||||||
const dict = transactionCache[type]
|
const dict = transactionCache[type]
|
||||||
const idsRequiringFetch = dict
|
const idsRequiringFetch = dict ? ids.filter(item => typeof dict[item] === 'undefined') : ids
|
||||||
? ids.filter(item => typeof dict[item] === 'undefined')
|
|
||||||
: ids
|
|
||||||
// only fetch if there are any items to fetch
|
// only fetch if there are any items to fetch
|
||||||
if(idsRequiringFetch.length) {
|
if (idsRequiringFetch.length) {
|
||||||
dbQueriesInTransaction += 1
|
dbQueriesInTransaction += 1
|
||||||
const result = await state.get(type, idsRequiringFetch)
|
const result = await state.get(type, idsRequiringFetch)
|
||||||
|
|
||||||
transactionCache[type] ||= {}
|
transactionCache[type] ||= {}
|
||||||
Object.assign(
|
Object.assign(transactionCache[type]!, result)
|
||||||
transactionCache[type]!,
|
|
||||||
result
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return ids.reduce(
|
return ids.reduce((dict, id) => {
|
||||||
(dict, id) => {
|
|
||||||
const value = transactionCache[type]?.[id]
|
const value = transactionCache[type]?.[id]
|
||||||
if(value) {
|
if (value) {
|
||||||
dict[id] = value
|
dict[id] = value
|
||||||
}
|
}
|
||||||
|
|
||||||
return dict
|
return dict
|
||||||
}, { }
|
}, {})
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
return state.get(type, ids)
|
return state.get(type, ids)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
set: data => {
|
set: data => {
|
||||||
if(isInTransaction()) {
|
if (isInTransaction()) {
|
||||||
logger.trace({ types: Object.keys(data) }, 'caching in transaction')
|
logger.trace({ types: Object.keys(data) }, 'caching in transaction')
|
||||||
for(const key in data) {
|
for (const key in data) {
|
||||||
transactionCache[key] = transactionCache[key] || { }
|
transactionCache[key] = transactionCache[key] || {}
|
||||||
Object.assign(transactionCache[key], data[key])
|
Object.assign(transactionCache[key], data[key])
|
||||||
|
|
||||||
mutations[key] = mutations[key] || { }
|
mutations[key] = mutations[key] || {}
|
||||||
Object.assign(mutations[key], data[key])
|
Object.assign(mutations[key], data[key])
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -145,27 +148,27 @@ export const addTransactionCapability = (
|
|||||||
async transaction(work) {
|
async transaction(work) {
|
||||||
let result: Awaited<ReturnType<typeof work>>
|
let result: Awaited<ReturnType<typeof work>>
|
||||||
transactionsInProgress += 1
|
transactionsInProgress += 1
|
||||||
if(transactionsInProgress === 1) {
|
if (transactionsInProgress === 1) {
|
||||||
logger.trace('entering transaction')
|
logger.trace('entering transaction')
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
result = await work()
|
result = await work()
|
||||||
// commit if this is the outermost transaction
|
// commit if this is the outermost transaction
|
||||||
if(transactionsInProgress === 1) {
|
if (transactionsInProgress === 1) {
|
||||||
if(Object.keys(mutations).length) {
|
if (Object.keys(mutations).length) {
|
||||||
logger.trace('committing transaction')
|
logger.trace('committing transaction')
|
||||||
// retry mechanism to ensure we've some recovery
|
// retry mechanism to ensure we've some recovery
|
||||||
// in case a transaction fails in the first attempt
|
// in case a transaction fails in the first attempt
|
||||||
let tries = maxCommitRetries
|
let tries = maxCommitRetries
|
||||||
while(tries) {
|
while (tries) {
|
||||||
tries -= 1
|
tries -= 1
|
||||||
//eslint-disable-next-line max-depth
|
//eslint-disable-next-line max-depth
|
||||||
try {
|
try {
|
||||||
await state.set(mutations)
|
await state.set(mutations)
|
||||||
logger.trace({ dbQueriesInTransaction }, 'committed transaction')
|
logger.trace({ dbQueriesInTransaction }, 'committed transaction')
|
||||||
break
|
break
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`)
|
logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`)
|
||||||
await delay(delayBetweenTriesMs)
|
await delay(delayBetweenTriesMs)
|
||||||
}
|
}
|
||||||
@@ -176,9 +179,9 @@ export const addTransactionCapability = (
|
|||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
transactionsInProgress -= 1
|
transactionsInProgress -= 1
|
||||||
if(transactionsInProgress === 0) {
|
if (transactionsInProgress === 0) {
|
||||||
transactionCache = { }
|
transactionCache = {}
|
||||||
mutations = { }
|
mutations = {}
|
||||||
dbQueriesInTransaction = 0
|
dbQueriesInTransaction = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -211,6 +214,6 @@ export const initAuthCreds = (): AuthenticationCreds => {
|
|||||||
registered: false,
|
registered: false,
|
||||||
pairingCode: undefined,
|
pairingCode: undefined,
|
||||||
lastPropHash: undefined,
|
lastPropHash: undefined,
|
||||||
routingInfo: undefined,
|
routingInfo: undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,15 +16,13 @@ export const captureEventStream = (ev: BaileysEventEmitter, filename: string) =>
|
|||||||
// write mutex so data is appended in order
|
// write mutex so data is appended in order
|
||||||
const writeMutex = makeMutex()
|
const writeMutex = makeMutex()
|
||||||
// monkey patch eventemitter to capture all events
|
// monkey patch eventemitter to capture all events
|
||||||
ev.emit = function(...args: any[]) {
|
ev.emit = function (...args: any[]) {
|
||||||
const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n'
|
const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n'
|
||||||
const result = oldEmit.apply(ev, args)
|
const result = oldEmit.apply(ev, args)
|
||||||
|
|
||||||
writeMutex.mutex(
|
writeMutex.mutex(async () => {
|
||||||
async() => {
|
|
||||||
await writeFile(filename, content, { flag: 'a' })
|
await writeFile(filename, content, { flag: 'a' })
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
@@ -38,7 +36,7 @@ export const captureEventStream = (ev: BaileysEventEmitter, filename: string) =>
|
|||||||
export const readAndEmitEventStream = (filename: string, delayIntervalMs = 0) => {
|
export const readAndEmitEventStream = (filename: string, delayIntervalMs = 0) => {
|
||||||
const ev = new EventEmitter() as BaileysEventEmitter
|
const ev = new EventEmitter() as BaileysEventEmitter
|
||||||
|
|
||||||
const fireEvents = async() => {
|
const fireEvents = async () => {
|
||||||
// from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
|
// from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
|
||||||
const fileStream = createReadStream(filename)
|
const fileStream = createReadStream(filename)
|
||||||
|
|
||||||
@@ -49,10 +47,10 @@ export const readAndEmitEventStream = (filename: string, delayIntervalMs = 0) =>
|
|||||||
// Note: we use the crlfDelay option to recognize all instances of CR LF
|
// Note: we use the crlfDelay option to recognize all instances of CR LF
|
||||||
// ('\r\n') in input.txt as a single line break.
|
// ('\r\n') in input.txt as a single line break.
|
||||||
for await (const line of rl) {
|
for await (const line of rl) {
|
||||||
if(line) {
|
if (line) {
|
||||||
const { event, data } = JSON.parse(line)
|
const { event, data } = JSON.parse(line)
|
||||||
ev.emit(event, data)
|
ev.emit(event, data)
|
||||||
delayIntervalMs && await delay(delayIntervalMs)
|
delayIntervalMs && (await delay(delayIntervalMs))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,16 @@
|
|||||||
import { Boom } from '@hapi/boom'
|
import { Boom } from '@hapi/boom'
|
||||||
import { createHash } from 'crypto'
|
import { createHash } from 'crypto'
|
||||||
import { CatalogCollection, CatalogStatus, OrderDetails, OrderProduct, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types'
|
import {
|
||||||
|
CatalogCollection,
|
||||||
|
CatalogStatus,
|
||||||
|
OrderDetails,
|
||||||
|
OrderProduct,
|
||||||
|
Product,
|
||||||
|
ProductCreate,
|
||||||
|
ProductUpdate,
|
||||||
|
WAMediaUpload,
|
||||||
|
WAMediaUploadFunction
|
||||||
|
} from '../Types'
|
||||||
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../WABinary'
|
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../WABinary'
|
||||||
import { getStream, getUrlFromDirectPath, toReadable } from './messages-media'
|
import { getStream, getUrlFromDirectPath, toReadable } from './messages-media'
|
||||||
|
|
||||||
@@ -11,16 +21,13 @@ export const parseCatalogNode = (node: BinaryNode) => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
products,
|
products,
|
||||||
nextPageCursor: paging
|
nextPageCursor: paging ? getBinaryNodeChildString(paging, 'after') : undefined
|
||||||
? getBinaryNodeChildString(paging, 'after')
|
|
||||||
: undefined
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const parseCollectionsNode = (node: BinaryNode) => {
|
export const parseCollectionsNode = (node: BinaryNode) => {
|
||||||
const collectionsNode = getBinaryNodeChild(node, 'collections')
|
const collectionsNode = getBinaryNodeChild(node, 'collections')
|
||||||
const collections = getBinaryNodeChildren(collectionsNode, 'collection').map<CatalogCollection>(
|
const collections = getBinaryNodeChildren(collectionsNode, 'collection').map<CatalogCollection>(collectionNode => {
|
||||||
collectionNode => {
|
|
||||||
const id = getBinaryNodeChildString(collectionNode, 'id')!
|
const id = getBinaryNodeChildString(collectionNode, 'id')!
|
||||||
const name = getBinaryNodeChildString(collectionNode, 'name')!
|
const name = getBinaryNodeChildString(collectionNode, 'name')!
|
||||||
|
|
||||||
@@ -31,8 +38,7 @@ export const parseCollectionsNode = (node: BinaryNode) => {
|
|||||||
products,
|
products,
|
||||||
status: parseStatusInfo(collectionNode)
|
status: parseStatusInfo(collectionNode)
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
collections
|
collections
|
||||||
@@ -41,8 +47,7 @@ export const parseCollectionsNode = (node: BinaryNode) => {
|
|||||||
|
|
||||||
export const parseOrderDetailsNode = (node: BinaryNode) => {
|
export const parseOrderDetailsNode = (node: BinaryNode) => {
|
||||||
const orderNode = getBinaryNodeChild(node, 'order')
|
const orderNode = getBinaryNodeChild(node, 'order')
|
||||||
const products = getBinaryNodeChildren(orderNode, 'product').map<OrderProduct>(
|
const products = getBinaryNodeChildren(orderNode, 'product').map<OrderProduct>(productNode => {
|
||||||
productNode => {
|
|
||||||
const imageNode = getBinaryNodeChild(productNode, 'image')!
|
const imageNode = getBinaryNodeChild(productNode, 'image')!
|
||||||
return {
|
return {
|
||||||
id: getBinaryNodeChildString(productNode, 'id')!,
|
id: getBinaryNodeChildString(productNode, 'id')!,
|
||||||
@@ -52,15 +57,14 @@ export const parseOrderDetailsNode = (node: BinaryNode) => {
|
|||||||
currency: getBinaryNodeChildString(productNode, 'currency')!,
|
currency: getBinaryNodeChildString(productNode, 'currency')!,
|
||||||
quantity: +getBinaryNodeChildString(productNode, 'quantity')!
|
quantity: +getBinaryNodeChildString(productNode, 'quantity')!
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
const priceNode = getBinaryNodeChild(orderNode, 'price')
|
const priceNode = getBinaryNodeChild(orderNode, 'price')
|
||||||
|
|
||||||
const orderDetails: OrderDetails = {
|
const orderDetails: OrderDetails = {
|
||||||
price: {
|
price: {
|
||||||
total: +getBinaryNodeChildString(priceNode, 'total')!,
|
total: +getBinaryNodeChildString(priceNode, 'total')!,
|
||||||
currency: getBinaryNodeChildString(priceNode, 'currency')!,
|
currency: getBinaryNodeChildString(priceNode, 'currency')!
|
||||||
},
|
},
|
||||||
products
|
products
|
||||||
}
|
}
|
||||||
@@ -69,94 +73,92 @@ export const parseOrderDetailsNode = (node: BinaryNode) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const toProductNode = (productId: string | undefined, product: ProductCreate | ProductUpdate) => {
|
export const toProductNode = (productId: string | undefined, product: ProductCreate | ProductUpdate) => {
|
||||||
const attrs: BinaryNode['attrs'] = { }
|
const attrs: BinaryNode['attrs'] = {}
|
||||||
const content: BinaryNode[] = [ ]
|
const content: BinaryNode[] = []
|
||||||
|
|
||||||
if(typeof productId !== 'undefined') {
|
if (typeof productId !== 'undefined') {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'id',
|
tag: 'id',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(productId)
|
content: Buffer.from(productId)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof product.name !== 'undefined') {
|
if (typeof product.name !== 'undefined') {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'name',
|
tag: 'name',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(product.name)
|
content: Buffer.from(product.name)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof product.description !== 'undefined') {
|
if (typeof product.description !== 'undefined') {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'description',
|
tag: 'description',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(product.description)
|
content: Buffer.from(product.description)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof product.retailerId !== 'undefined') {
|
if (typeof product.retailerId !== 'undefined') {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'retailer_id',
|
tag: 'retailer_id',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(product.retailerId)
|
content: Buffer.from(product.retailerId)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if(product.images.length) {
|
if (product.images.length) {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'media',
|
tag: 'media',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: product.images.map(
|
content: product.images.map(img => {
|
||||||
img => {
|
if (!('url' in img)) {
|
||||||
if(!('url' in img)) {
|
|
||||||
throw new Boom('Expected img for product to already be uploaded', { statusCode: 400 })
|
throw new Boom('Expected img for product to already be uploaded', { statusCode: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tag: 'image',
|
tag: 'image',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'url',
|
tag: 'url',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(img.url.toString())
|
content: Buffer.from(img.url.toString())
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof product.price !== 'undefined') {
|
if (typeof product.price !== 'undefined') {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'price',
|
tag: 'price',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(product.price.toString())
|
content: Buffer.from(product.price.toString())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof product.currency !== 'undefined') {
|
if (typeof product.currency !== 'undefined') {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'currency',
|
tag: 'currency',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(product.currency)
|
content: Buffer.from(product.currency)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if('originCountryCode' in product) {
|
if ('originCountryCode' in product) {
|
||||||
if(typeof product.originCountryCode === 'undefined') {
|
if (typeof product.originCountryCode === 'undefined') {
|
||||||
attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT'
|
attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT'
|
||||||
} else {
|
} else {
|
||||||
content.push({
|
content.push({
|
||||||
tag: 'compliance_info',
|
tag: 'compliance_info',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'country_code_origin',
|
tag: 'country_code_origin',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: Buffer.from(product.originCountryCode)
|
content: Buffer.from(product.originCountryCode)
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -164,8 +166,7 @@ export const toProductNode = (productId: string | undefined, product: ProductCre
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (typeof product.isHidden !== 'undefined') {
|
||||||
if(typeof product.isHidden !== 'undefined') {
|
|
||||||
attrs['is_hidden'] = product.isHidden.toString()
|
attrs['is_hidden'] = product.isHidden.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,7 +189,7 @@ export const parseProductNode = (productNode: BinaryNode) => {
|
|||||||
id,
|
id,
|
||||||
imageUrls: parseImageUrls(mediaNode),
|
imageUrls: parseImageUrls(mediaNode),
|
||||||
reviewStatus: {
|
reviewStatus: {
|
||||||
whatsapp: getBinaryNodeChildString(statusInfoNode, 'status')!,
|
whatsapp: getBinaryNodeChildString(statusInfoNode, 'status')!
|
||||||
},
|
},
|
||||||
availability: 'in stock',
|
availability: 'in stock',
|
||||||
name: getBinaryNodeChildString(productNode, 'name')!,
|
name: getBinaryNodeChildString(productNode, 'name')!,
|
||||||
@@ -197,7 +198,7 @@ export const parseProductNode = (productNode: BinaryNode) => {
|
|||||||
description: getBinaryNodeChildString(productNode, 'description')!,
|
description: getBinaryNodeChildString(productNode, 'description')!,
|
||||||
price: +getBinaryNodeChildString(productNode, 'price')!,
|
price: +getBinaryNodeChildString(productNode, 'price')!,
|
||||||
currency: getBinaryNodeChildString(productNode, 'currency')!,
|
currency: getBinaryNodeChildString(productNode, 'currency')!,
|
||||||
isHidden,
|
isHidden
|
||||||
}
|
}
|
||||||
|
|
||||||
return product
|
return product
|
||||||
@@ -206,10 +207,16 @@ export const parseProductNode = (productNode: BinaryNode) => {
|
|||||||
/**
|
/**
|
||||||
* Uploads images not already uploaded to WA's servers
|
* Uploads images not already uploaded to WA's servers
|
||||||
*/
|
*/
|
||||||
export async function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(product: T, waUploadToServer: WAMediaUploadFunction, timeoutMs = 30_000) {
|
export async function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(
|
||||||
|
product: T,
|
||||||
|
waUploadToServer: WAMediaUploadFunction,
|
||||||
|
timeoutMs = 30_000
|
||||||
|
) {
|
||||||
product = {
|
product = {
|
||||||
...product,
|
...product,
|
||||||
images: product.images ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs) : product.images
|
images: product.images
|
||||||
|
? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs)
|
||||||
|
: product.images
|
||||||
}
|
}
|
||||||
return product
|
return product
|
||||||
}
|
}
|
||||||
@@ -217,18 +224,16 @@ export async function uploadingNecessaryImagesOfProduct<T extends ProductUpdate
|
|||||||
/**
|
/**
|
||||||
* Uploads images not already uploaded to WA's servers
|
* Uploads images not already uploaded to WA's servers
|
||||||
*/
|
*/
|
||||||
export const uploadingNecessaryImages = async(
|
export const uploadingNecessaryImages = async (
|
||||||
images: WAMediaUpload[],
|
images: WAMediaUpload[],
|
||||||
waUploadToServer: WAMediaUploadFunction,
|
waUploadToServer: WAMediaUploadFunction,
|
||||||
timeoutMs = 30_000
|
timeoutMs = 30_000
|
||||||
) => {
|
) => {
|
||||||
const results = await Promise.all(
|
const results = await Promise.all(
|
||||||
images.map<Promise<{ url: string }>>(
|
images.map<Promise<{ url: string }>>(async img => {
|
||||||
async img => {
|
if ('url' in img) {
|
||||||
|
|
||||||
if('url' in img) {
|
|
||||||
const url = img.url.toString()
|
const url = img.url.toString()
|
||||||
if(url.includes('.whatsapp.net')) {
|
if (url.includes('.whatsapp.net')) {
|
||||||
return { url }
|
return { url }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -243,17 +248,13 @@ export const uploadingNecessaryImages = async(
|
|||||||
|
|
||||||
const sha = hasher.digest('base64')
|
const sha = hasher.digest('base64')
|
||||||
|
|
||||||
const { directPath } = await waUploadToServer(
|
const { directPath } = await waUploadToServer(toReadable(Buffer.concat(contentBlocks)), {
|
||||||
toReadable(Buffer.concat(contentBlocks)),
|
|
||||||
{
|
|
||||||
mediaType: 'product-catalog-image',
|
mediaType: 'product-catalog-image',
|
||||||
fileEncSha256B64: sha,
|
fileEncSha256B64: sha,
|
||||||
timeoutMs
|
timeoutMs
|
||||||
}
|
})
|
||||||
)
|
|
||||||
return { url: getUrlFromDirectPath(directPath) }
|
return { url: getUrlFromDirectPath(directPath) }
|
||||||
}
|
})
|
||||||
)
|
|
||||||
)
|
)
|
||||||
return results
|
return results
|
||||||
}
|
}
|
||||||
@@ -270,6 +271,6 @@ const parseStatusInfo = (mediaNode: BinaryNode): CatalogStatus => {
|
|||||||
const node = getBinaryNodeChild(mediaNode, 'status_info')
|
const node = getBinaryNodeChild(mediaNode, 'status_info')
|
||||||
return {
|
return {
|
||||||
status: getBinaryNodeChildString(node, 'status')!,
|
status: getBinaryNodeChildString(node, 'status')!,
|
||||||
canAppeal: getBinaryNodeChildString(node, 'can_appeal') === 'true',
|
canAppeal: getBinaryNodeChildString(node, 'can_appeal') === 'true'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,20 +1,32 @@
|
|||||||
import { Boom } from '@hapi/boom'
|
import { Boom } from '@hapi/boom'
|
||||||
import { AxiosRequestConfig } from 'axios'
|
import { AxiosRequestConfig } from 'axios'
|
||||||
import { proto } from '../../WAProto'
|
import { proto } from '../../WAProto'
|
||||||
import { BaileysEventEmitter, Chat, ChatModification, ChatMutation, ChatUpdate, Contact, InitialAppStateSyncOptions, LastMessageList, LTHashState, WAPatchCreate, WAPatchName } from '../Types'
|
import {
|
||||||
|
BaileysEventEmitter,
|
||||||
|
Chat,
|
||||||
|
ChatModification,
|
||||||
|
ChatMutation,
|
||||||
|
ChatUpdate,
|
||||||
|
Contact,
|
||||||
|
InitialAppStateSyncOptions,
|
||||||
|
LastMessageList,
|
||||||
|
LTHashState,
|
||||||
|
WAPatchCreate,
|
||||||
|
WAPatchName
|
||||||
|
} from '../Types'
|
||||||
import { ChatLabelAssociation, LabelAssociationType, MessageLabelAssociation } from '../Types/LabelAssociation'
|
import { ChatLabelAssociation, LabelAssociationType, MessageLabelAssociation } from '../Types/LabelAssociation'
|
||||||
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary'
|
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary'
|
||||||
import { aesDecrypt, aesEncrypt, hkdf, hmacSign } from './crypto'
|
import { aesDecrypt, aesEncrypt, hkdf, hmacSign } from './crypto'
|
||||||
import { toNumber } from './generics'
|
import { toNumber } from './generics'
|
||||||
import { ILogger } from './logger'
|
import { ILogger } from './logger'
|
||||||
import { LT_HASH_ANTI_TAMPERING } from './lt-hash'
|
import { LT_HASH_ANTI_TAMPERING } from './lt-hash'
|
||||||
import { downloadContentFromMessage, } from './messages-media'
|
import { downloadContentFromMessage } from './messages-media'
|
||||||
|
|
||||||
type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>
|
type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>
|
||||||
|
|
||||||
export type ChatMutationMap = { [index: string]: ChatMutation }
|
export type ChatMutationMap = { [index: string]: ChatMutation }
|
||||||
|
|
||||||
const mutationKeys = async(keydata: Uint8Array) => {
|
const mutationKeys = async (keydata: Uint8Array) => {
|
||||||
const expanded = await hkdf(keydata, 160, { info: 'WhatsApp Mutation Keys' })
|
const expanded = await hkdf(keydata, 160, { info: 'WhatsApp Mutation Keys' })
|
||||||
return {
|
return {
|
||||||
indexKey: expanded.slice(0, 32),
|
indexKey: expanded.slice(0, 32),
|
||||||
@@ -25,7 +37,12 @@ const mutationKeys = async(keydata: Uint8Array) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const generateMac = (operation: proto.SyncdMutation.SyncdOperation, data: Buffer, keyId: Uint8Array | string, key: Buffer) => {
|
const generateMac = (
|
||||||
|
operation: proto.SyncdMutation.SyncdOperation,
|
||||||
|
data: Buffer,
|
||||||
|
keyId: Uint8Array | string,
|
||||||
|
key: Buffer
|
||||||
|
) => {
|
||||||
const getKeyData = () => {
|
const getKeyData = () => {
|
||||||
let r: number
|
let r: number
|
||||||
switch (operation) {
|
switch (operation) {
|
||||||
@@ -58,7 +75,7 @@ const to64BitNetworkOrder = (e: number) => {
|
|||||||
return buff
|
return buff
|
||||||
}
|
}
|
||||||
|
|
||||||
type Mac = { indexMac: Uint8Array, valueMac: Uint8Array, operation: proto.SyncdMutation.SyncdOperation }
|
type Mac = { indexMac: Uint8Array; valueMac: Uint8Array; operation: proto.SyncdMutation.SyncdOperation }
|
||||||
|
|
||||||
const makeLtHashGenerator = ({ indexValueMap, hash }: Pick<LTHashState, 'hash' | 'indexValueMap'>) => {
|
const makeLtHashGenerator = ({ indexValueMap, hash }: Pick<LTHashState, 'hash' | 'indexValueMap'>) => {
|
||||||
indexValueMap = { ...indexValueMap }
|
indexValueMap = { ...indexValueMap }
|
||||||
@@ -69,8 +86,8 @@ const makeLtHashGenerator = ({ indexValueMap, hash }: Pick<LTHashState, 'hash' |
|
|||||||
mix: ({ indexMac, valueMac, operation }: Mac) => {
|
mix: ({ indexMac, valueMac, operation }: Mac) => {
|
||||||
const indexMacBase64 = Buffer.from(indexMac).toString('base64')
|
const indexMacBase64 = Buffer.from(indexMac).toString('base64')
|
||||||
const prevOp = indexValueMap[indexMacBase64]
|
const prevOp = indexValueMap[indexMacBase64]
|
||||||
if(operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
|
if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
|
||||||
if(!prevOp) {
|
if (!prevOp) {
|
||||||
throw new Boom('tried remove, but no previous op', { data: { indexMac, valueMac } })
|
throw new Boom('tried remove, but no previous op', { data: { indexMac, valueMac } })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,11 +99,11 @@ const makeLtHashGenerator = ({ indexValueMap, hash }: Pick<LTHashState, 'hash' |
|
|||||||
indexValueMap[indexMacBase64] = { valueMac }
|
indexValueMap[indexMacBase64] = { valueMac }
|
||||||
}
|
}
|
||||||
|
|
||||||
if(prevOp) {
|
if (prevOp) {
|
||||||
subBuffs.push(new Uint8Array(prevOp.valueMac).buffer)
|
subBuffs.push(new Uint8Array(prevOp.valueMac).buffer)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
finish: async() => {
|
finish: async () => {
|
||||||
const hashArrayBuffer = new Uint8Array(hash).buffer
|
const hashArrayBuffer = new Uint8Array(hash).buffer
|
||||||
const result = await LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs)
|
const result = await LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs)
|
||||||
const buffer = Buffer.from(result)
|
const buffer = Buffer.from(result)
|
||||||
@@ -100,34 +117,31 @@ const makeLtHashGenerator = ({ indexValueMap, hash }: Pick<LTHashState, 'hash' |
|
|||||||
}
|
}
|
||||||
|
|
||||||
const generateSnapshotMac = (lthash: Uint8Array, version: number, name: WAPatchName, key: Buffer) => {
|
const generateSnapshotMac = (lthash: Uint8Array, version: number, name: WAPatchName, key: Buffer) => {
|
||||||
const total = Buffer.concat([
|
const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')])
|
||||||
lthash,
|
|
||||||
to64BitNetworkOrder(version),
|
|
||||||
Buffer.from(name, 'utf-8')
|
|
||||||
])
|
|
||||||
return hmacSign(total, key, 'sha256')
|
return hmacSign(total, key, 'sha256')
|
||||||
}
|
}
|
||||||
|
|
||||||
const generatePatchMac = (snapshotMac: Uint8Array, valueMacs: Uint8Array[], version: number, type: WAPatchName, key: Buffer) => {
|
const generatePatchMac = (
|
||||||
const total = Buffer.concat([
|
snapshotMac: Uint8Array,
|
||||||
snapshotMac,
|
valueMacs: Uint8Array[],
|
||||||
...valueMacs,
|
version: number,
|
||||||
to64BitNetworkOrder(version),
|
type: WAPatchName,
|
||||||
Buffer.from(type, 'utf-8')
|
key: Buffer
|
||||||
])
|
) => {
|
||||||
|
const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')])
|
||||||
return hmacSign(total, key)
|
return hmacSign(total, key)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const newLTHashState = (): LTHashState => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} })
|
export const newLTHashState = (): LTHashState => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} })
|
||||||
|
|
||||||
export const encodeSyncdPatch = async(
|
export const encodeSyncdPatch = async (
|
||||||
{ type, index, syncAction, apiVersion, operation }: WAPatchCreate,
|
{ type, index, syncAction, apiVersion, operation }: WAPatchCreate,
|
||||||
myAppStateKeyId: string,
|
myAppStateKeyId: string,
|
||||||
state: LTHashState,
|
state: LTHashState,
|
||||||
getAppStateSyncKey: FetchAppStateSyncKey
|
getAppStateSyncKey: FetchAppStateSyncKey
|
||||||
) => {
|
) => {
|
||||||
const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined
|
const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined
|
||||||
if(!key) {
|
if (!key) {
|
||||||
throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 })
|
throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,7 +199,7 @@ export const encodeSyncdPatch = async(
|
|||||||
return { patch, state }
|
return { patch, state }
|
||||||
}
|
}
|
||||||
|
|
||||||
export const decodeSyncdMutations = async(
|
export const decodeSyncdMutations = async (
|
||||||
msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[],
|
msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[],
|
||||||
initialState: LTHashState,
|
initialState: LTHashState,
|
||||||
getAppStateSyncKey: FetchAppStateSyncKey,
|
getAppStateSyncKey: FetchAppStateSyncKey,
|
||||||
@@ -196,19 +210,20 @@ export const decodeSyncdMutations = async(
|
|||||||
// indexKey used to HMAC sign record.index.blob
|
// indexKey used to HMAC sign record.index.blob
|
||||||
// valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
|
// valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
|
||||||
// the remaining record.value.blob[0:-32] is the mac, it the HMAC sign of key.keyId + decoded proto data + length of bytes in keyId
|
// the remaining record.value.blob[0:-32] is the mac, it the HMAC sign of key.keyId + decoded proto data + length of bytes in keyId
|
||||||
for(const msgMutation of msgMutations) {
|
for (const msgMutation of msgMutations) {
|
||||||
// if it's a syncdmutation, get the operation property
|
// if it's a syncdmutation, get the operation property
|
||||||
// otherwise, if it's only a record -- it'll be a SET mutation
|
// otherwise, if it's only a record -- it'll be a SET mutation
|
||||||
const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET
|
const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET
|
||||||
const record = ('record' in msgMutation && !!msgMutation.record) ? msgMutation.record : msgMutation as proto.ISyncdRecord
|
const record =
|
||||||
|
'record' in msgMutation && !!msgMutation.record ? msgMutation.record : (msgMutation as proto.ISyncdRecord)
|
||||||
|
|
||||||
const key = await getKey(record.keyId!.id!)
|
const key = await getKey(record.keyId!.id!)
|
||||||
const content = Buffer.from(record.value!.blob!)
|
const content = Buffer.from(record.value!.blob!)
|
||||||
const encContent = content.slice(0, -32)
|
const encContent = content.slice(0, -32)
|
||||||
const ogValueMac = content.slice(-32)
|
const ogValueMac = content.slice(-32)
|
||||||
if(validateMacs) {
|
if (validateMacs) {
|
||||||
const contentHmac = generateMac(operation!, encContent, record.keyId!.id!, key.valueMacKey)
|
const contentHmac = generateMac(operation!, encContent, record.keyId!.id!, key.valueMacKey)
|
||||||
if(Buffer.compare(contentHmac, ogValueMac) !== 0) {
|
if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
|
||||||
throw new Boom('HMAC content verification failed')
|
throw new Boom('HMAC content verification failed')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -216,9 +231,9 @@ export const decodeSyncdMutations = async(
|
|||||||
const result = aesDecrypt(encContent, key.valueEncryptionKey)
|
const result = aesDecrypt(encContent, key.valueEncryptionKey)
|
||||||
const syncAction = proto.SyncActionData.decode(result)
|
const syncAction = proto.SyncActionData.decode(result)
|
||||||
|
|
||||||
if(validateMacs) {
|
if (validateMacs) {
|
||||||
const hmac = hmacSign(syncAction.index!, key.indexKey)
|
const hmac = hmacSign(syncAction.index!, key.indexKey)
|
||||||
if(Buffer.compare(hmac, record.index!.blob!) !== 0) {
|
if (Buffer.compare(hmac, record.index!.blob!) !== 0) {
|
||||||
throw new Boom('HMAC index verification failed')
|
throw new Boom('HMAC index verification failed')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,15 +253,18 @@ export const decodeSyncdMutations = async(
|
|||||||
async function getKey(keyId: Uint8Array) {
|
async function getKey(keyId: Uint8Array) {
|
||||||
const base64Key = Buffer.from(keyId).toString('base64')
|
const base64Key = Buffer.from(keyId).toString('base64')
|
||||||
const keyEnc = await getAppStateSyncKey(base64Key)
|
const keyEnc = await getAppStateSyncKey(base64Key)
|
||||||
if(!keyEnc) {
|
if (!keyEnc) {
|
||||||
throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { statusCode: 404, data: { msgMutations } })
|
throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
|
||||||
|
statusCode: 404,
|
||||||
|
data: { msgMutations }
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return mutationKeys(keyEnc.keyData!)
|
return mutationKeys(keyEnc.keyData!)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const decodeSyncdPatch = async(
|
export const decodeSyncdPatch = async (
|
||||||
msg: proto.ISyncdPatch,
|
msg: proto.ISyncdPatch,
|
||||||
name: WAPatchName,
|
name: WAPatchName,
|
||||||
initialState: LTHashState,
|
initialState: LTHashState,
|
||||||
@@ -254,18 +272,24 @@ export const decodeSyncdPatch = async(
|
|||||||
onMutation: (mutation: ChatMutation) => void,
|
onMutation: (mutation: ChatMutation) => void,
|
||||||
validateMacs: boolean
|
validateMacs: boolean
|
||||||
) => {
|
) => {
|
||||||
if(validateMacs) {
|
if (validateMacs) {
|
||||||
const base64Key = Buffer.from(msg.keyId!.id!).toString('base64')
|
const base64Key = Buffer.from(msg.keyId!.id!).toString('base64')
|
||||||
const mainKeyObj = await getAppStateSyncKey(base64Key)
|
const mainKeyObj = await getAppStateSyncKey(base64Key)
|
||||||
if(!mainKeyObj) {
|
if (!mainKeyObj) {
|
||||||
throw new Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } })
|
throw new Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } })
|
||||||
}
|
}
|
||||||
|
|
||||||
const mainKey = await mutationKeys(mainKeyObj.keyData!)
|
const mainKey = await mutationKeys(mainKeyObj.keyData!)
|
||||||
const mutationmacs = msg.mutations!.map(mutation => mutation.record!.value!.blob!.slice(-32))
|
const mutationmacs = msg.mutations!.map(mutation => mutation.record!.value!.blob!.slice(-32))
|
||||||
|
|
||||||
const patchMac = generatePatchMac(msg.snapshotMac!, mutationmacs, toNumber(msg.version!.version), name, mainKey.patchMacKey)
|
const patchMac = generatePatchMac(
|
||||||
if(Buffer.compare(patchMac, msg.patchMac!) !== 0) {
|
msg.snapshotMac!,
|
||||||
|
mutationmacs,
|
||||||
|
toNumber(msg.version!.version),
|
||||||
|
name,
|
||||||
|
mainKey.patchMacKey
|
||||||
|
)
|
||||||
|
if (Buffer.compare(patchMac, msg.patchMac!) !== 0) {
|
||||||
throw new Boom('Invalid patch mac')
|
throw new Boom('Invalid patch mac')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,17 +298,15 @@ export const decodeSyncdPatch = async(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
export const extractSyncdPatches = async(
|
export const extractSyncdPatches = async (result: BinaryNode, options: AxiosRequestConfig<{}>) => {
|
||||||
result: BinaryNode,
|
|
||||||
options: AxiosRequestConfig<{}>
|
|
||||||
) => {
|
|
||||||
const syncNode = getBinaryNodeChild(result, 'sync')
|
const syncNode = getBinaryNodeChild(result, 'sync')
|
||||||
const collectionNodes = getBinaryNodeChildren(syncNode, 'collection')
|
const collectionNodes = getBinaryNodeChildren(syncNode, 'collection')
|
||||||
|
|
||||||
const final = {} as { [T in WAPatchName]: { patches: proto.ISyncdPatch[], hasMorePatches: boolean, snapshot?: proto.ISyncdSnapshot } }
|
const final = {} as {
|
||||||
|
[T in WAPatchName]: { patches: proto.ISyncdPatch[]; hasMorePatches: boolean; snapshot?: proto.ISyncdSnapshot }
|
||||||
|
}
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
collectionNodes.map(
|
collectionNodes.map(async collectionNode => {
|
||||||
async collectionNode => {
|
|
||||||
const patchesNode = getBinaryNodeChild(collectionNode, 'patches')
|
const patchesNode = getBinaryNodeChild(collectionNode, 'patches')
|
||||||
|
|
||||||
const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch')
|
const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch')
|
||||||
@@ -296,26 +318,24 @@ export const extractSyncdPatches = async(
|
|||||||
const hasMorePatches = collectionNode.attrs.has_more_patches === 'true'
|
const hasMorePatches = collectionNode.attrs.has_more_patches === 'true'
|
||||||
|
|
||||||
let snapshot: proto.ISyncdSnapshot | undefined = undefined
|
let snapshot: proto.ISyncdSnapshot | undefined = undefined
|
||||||
if(snapshotNode && !!snapshotNode.content) {
|
if (snapshotNode && !!snapshotNode.content) {
|
||||||
if(!Buffer.isBuffer(snapshotNode)) {
|
if (!Buffer.isBuffer(snapshotNode)) {
|
||||||
snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
|
snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
|
||||||
}
|
}
|
||||||
|
|
||||||
const blobRef = proto.ExternalBlobReference.decode(
|
const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content as Buffer)
|
||||||
snapshotNode.content as Buffer
|
|
||||||
)
|
|
||||||
const data = await downloadExternalBlob(blobRef, options)
|
const data = await downloadExternalBlob(blobRef, options)
|
||||||
snapshot = proto.SyncdSnapshot.decode(data)
|
snapshot = proto.SyncdSnapshot.decode(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
for(let { content } of patches) {
|
for (let { content } of patches) {
|
||||||
if(content) {
|
if (content) {
|
||||||
if(!Buffer.isBuffer(content)) {
|
if (!Buffer.isBuffer(content)) {
|
||||||
content = Buffer.from(Object.values(content))
|
content = Buffer.from(Object.values(content))
|
||||||
}
|
}
|
||||||
|
|
||||||
const syncd = proto.SyncdPatch.decode(content as Uint8Array)
|
const syncd = proto.SyncdPatch.decode(content as Uint8Array)
|
||||||
if(!syncd.version) {
|
if (!syncd.version) {
|
||||||
syncd.version = { version: +collectionNode.attrs.version + 1 }
|
syncd.version = { version: +collectionNode.attrs.version + 1 }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -324,18 +344,13 @@ export const extractSyncdPatches = async(
|
|||||||
}
|
}
|
||||||
|
|
||||||
final[name] = { patches: syncds, hasMorePatches, snapshot }
|
final[name] = { patches: syncds, hasMorePatches, snapshot }
|
||||||
}
|
})
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return final
|
return final
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const downloadExternalBlob = async (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => {
|
||||||
export const downloadExternalBlob = async(
|
|
||||||
blob: proto.IExternalBlobReference,
|
|
||||||
options: AxiosRequestConfig<{}>
|
|
||||||
) => {
|
|
||||||
const stream = await downloadContentFromMessage(blob, 'md-app-state', { options })
|
const stream = await downloadContentFromMessage(blob, 'md-app-state', { options })
|
||||||
const bufferArray: Buffer[] = []
|
const bufferArray: Buffer[] = []
|
||||||
for await (const chunk of stream) {
|
for await (const chunk of stream) {
|
||||||
@@ -345,16 +360,13 @@ export const downloadExternalBlob = async(
|
|||||||
return Buffer.concat(bufferArray)
|
return Buffer.concat(bufferArray)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const downloadExternalPatch = async(
|
export const downloadExternalPatch = async (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => {
|
||||||
blob: proto.IExternalBlobReference,
|
|
||||||
options: AxiosRequestConfig<{}>
|
|
||||||
) => {
|
|
||||||
const buffer = await downloadExternalBlob(blob, options)
|
const buffer = await downloadExternalBlob(blob, options)
|
||||||
const syncData = proto.SyncdMutations.decode(buffer)
|
const syncData = proto.SyncdMutations.decode(buffer)
|
||||||
return syncData
|
return syncData
|
||||||
}
|
}
|
||||||
|
|
||||||
export const decodeSyncdSnapshot = async(
|
export const decodeSyncdSnapshot = async (
|
||||||
name: WAPatchName,
|
name: WAPatchName,
|
||||||
snapshot: proto.ISyncdSnapshot,
|
snapshot: proto.ISyncdSnapshot,
|
||||||
getAppStateSyncKey: FetchAppStateSyncKey,
|
getAppStateSyncKey: FetchAppStateSyncKey,
|
||||||
@@ -365,34 +377,33 @@ export const decodeSyncdSnapshot = async(
|
|||||||
newState.version = toNumber(snapshot.version!.version)
|
newState.version = toNumber(snapshot.version!.version)
|
||||||
|
|
||||||
const mutationMap: ChatMutationMap = {}
|
const mutationMap: ChatMutationMap = {}
|
||||||
const areMutationsRequired = typeof minimumVersionNumber === 'undefined'
|
const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber
|
||||||
|| newState.version > minimumVersionNumber
|
|
||||||
|
|
||||||
const { hash, indexValueMap } = await decodeSyncdMutations(
|
const { hash, indexValueMap } = await decodeSyncdMutations(
|
||||||
snapshot.records!,
|
snapshot.records!,
|
||||||
newState,
|
newState,
|
||||||
getAppStateSyncKey,
|
getAppStateSyncKey,
|
||||||
areMutationsRequired
|
areMutationsRequired
|
||||||
? (mutation) => {
|
? mutation => {
|
||||||
const index = mutation.syncAction.index?.toString()
|
const index = mutation.syncAction.index?.toString()
|
||||||
mutationMap[index!] = mutation
|
mutationMap[index!] = mutation
|
||||||
}
|
}
|
||||||
: () => { },
|
: () => {},
|
||||||
validateMacs
|
validateMacs
|
||||||
)
|
)
|
||||||
newState.hash = hash
|
newState.hash = hash
|
||||||
newState.indexValueMap = indexValueMap
|
newState.indexValueMap = indexValueMap
|
||||||
|
|
||||||
if(validateMacs) {
|
if (validateMacs) {
|
||||||
const base64Key = Buffer.from(snapshot.keyId!.id!).toString('base64')
|
const base64Key = Buffer.from(snapshot.keyId!.id!).toString('base64')
|
||||||
const keyEnc = await getAppStateSyncKey(base64Key)
|
const keyEnc = await getAppStateSyncKey(base64Key)
|
||||||
if(!keyEnc) {
|
if (!keyEnc) {
|
||||||
throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
|
throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await mutationKeys(keyEnc.keyData!)
|
const result = await mutationKeys(keyEnc.keyData!)
|
||||||
const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
|
const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
|
||||||
if(Buffer.compare(snapshot.mac!, computedSnapshotMac) !== 0) {
|
if (Buffer.compare(snapshot.mac!, computedSnapshotMac) !== 0) {
|
||||||
throw new Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`)
|
throw new Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -403,7 +414,7 @@ export const decodeSyncdSnapshot = async(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const decodePatches = async(
|
export const decodePatches = async (
|
||||||
name: WAPatchName,
|
name: WAPatchName,
|
||||||
syncds: proto.ISyncdPatch[],
|
syncds: proto.ISyncdPatch[],
|
||||||
initial: LTHashState,
|
initial: LTHashState,
|
||||||
@@ -420,9 +431,9 @@ export const decodePatches = async(
|
|||||||
|
|
||||||
const mutationMap: ChatMutationMap = {}
|
const mutationMap: ChatMutationMap = {}
|
||||||
|
|
||||||
for(const syncd of syncds) {
|
for (const syncd of syncds) {
|
||||||
const { version, keyId, snapshotMac } = syncd
|
const { version, keyId, snapshotMac } = syncd
|
||||||
if(syncd.externalMutations) {
|
if (syncd.externalMutations) {
|
||||||
logger?.trace({ name, version }, 'downloading external patch')
|
logger?.trace({ name, version }, 'downloading external patch')
|
||||||
const ref = await downloadExternalPatch(syncd.externalMutations, options)
|
const ref = await downloadExternalPatch(syncd.externalMutations, options)
|
||||||
logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch')
|
logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch')
|
||||||
@@ -444,23 +455,23 @@ export const decodePatches = async(
|
|||||||
const index = mutation.syncAction.index?.toString()
|
const index = mutation.syncAction.index?.toString()
|
||||||
mutationMap[index!] = mutation
|
mutationMap[index!] = mutation
|
||||||
}
|
}
|
||||||
: (() => { }),
|
: () => {},
|
||||||
true
|
true
|
||||||
)
|
)
|
||||||
|
|
||||||
newState.hash = decodeResult.hash
|
newState.hash = decodeResult.hash
|
||||||
newState.indexValueMap = decodeResult.indexValueMap
|
newState.indexValueMap = decodeResult.indexValueMap
|
||||||
|
|
||||||
if(validateMacs) {
|
if (validateMacs) {
|
||||||
const base64Key = Buffer.from(keyId!.id!).toString('base64')
|
const base64Key = Buffer.from(keyId!.id!).toString('base64')
|
||||||
const keyEnc = await getAppStateSyncKey(base64Key)
|
const keyEnc = await getAppStateSyncKey(base64Key)
|
||||||
if(!keyEnc) {
|
if (!keyEnc) {
|
||||||
throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
|
throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await mutationKeys(keyEnc.keyData!)
|
const result = await mutationKeys(keyEnc.keyData!)
|
||||||
const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
|
const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
|
||||||
if(Buffer.compare(snapshotMac!, computedSnapshotMac) !== 0) {
|
if (Buffer.compare(snapshotMac!, computedSnapshotMac) !== 0) {
|
||||||
throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`)
|
throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -472,38 +483,35 @@ export const decodePatches = async(
|
|||||||
return { state: newState, mutationMap }
|
return { state: newState, mutationMap }
|
||||||
}
|
}
|
||||||
|
|
||||||
export const chatModificationToAppPatch = (
|
export const chatModificationToAppPatch = (mod: ChatModification, jid: string) => {
|
||||||
mod: ChatModification,
|
|
||||||
jid: string
|
|
||||||
) => {
|
|
||||||
const OP = proto.SyncdMutation.SyncdOperation
|
const OP = proto.SyncdMutation.SyncdOperation
|
||||||
const getMessageRange = (lastMessages: LastMessageList) => {
|
const getMessageRange = (lastMessages: LastMessageList) => {
|
||||||
let messageRange: proto.SyncActionValue.ISyncActionMessageRange
|
let messageRange: proto.SyncActionValue.ISyncActionMessageRange
|
||||||
if(Array.isArray(lastMessages)) {
|
if (Array.isArray(lastMessages)) {
|
||||||
const lastMsg = lastMessages[lastMessages.length - 1]
|
const lastMsg = lastMessages[lastMessages.length - 1]
|
||||||
messageRange = {
|
messageRange = {
|
||||||
lastMessageTimestamp: lastMsg?.messageTimestamp,
|
lastMessageTimestamp: lastMsg?.messageTimestamp,
|
||||||
messages: lastMessages?.length ? lastMessages.map(
|
messages: lastMessages?.length
|
||||||
m => {
|
? lastMessages.map(m => {
|
||||||
if(!m.key?.id || !m.key?.remoteJid) {
|
if (!m.key?.id || !m.key?.remoteJid) {
|
||||||
throw new Boom('Incomplete key', { statusCode: 400, data: m })
|
throw new Boom('Incomplete key', { statusCode: 400, data: m })
|
||||||
}
|
}
|
||||||
|
|
||||||
if(isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
|
if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
|
||||||
throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m })
|
throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m })
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
|
if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
|
||||||
throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m })
|
throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m })
|
||||||
}
|
}
|
||||||
|
|
||||||
if(m.key.participant) {
|
if (m.key.participant) {
|
||||||
m.key.participant = jidNormalizedUser(m.key.participant)
|
m.key.participant = jidNormalizedUser(m.key.participant)
|
||||||
}
|
}
|
||||||
|
|
||||||
return m
|
return m
|
||||||
}
|
})
|
||||||
) : undefined
|
: undefined
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
messageRange = lastMessages
|
messageRange = lastMessages
|
||||||
@@ -513,7 +521,7 @@ export const chatModificationToAppPatch = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
let patch: WAPatchCreate
|
let patch: WAPatchCreate
|
||||||
if('mute' in mod) {
|
if ('mute' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
muteAction: {
|
muteAction: {
|
||||||
@@ -526,7 +534,7 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 2,
|
apiVersion: 2,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('archive' in mod) {
|
} else if ('archive' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
archiveChatAction: {
|
archiveChatAction: {
|
||||||
@@ -539,7 +547,7 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('markRead' in mod) {
|
} else if ('markRead' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
markChatAsReadAction: {
|
markChatAsReadAction: {
|
||||||
@@ -552,7 +560,7 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('deleteForMe' in mod) {
|
} else if ('deleteForMe' in mod) {
|
||||||
const { timestamp, key, deleteMedia } = mod.deleteForMe
|
const { timestamp, key, deleteMedia } = mod.deleteForMe
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
@@ -566,7 +574,7 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('clear' in mod) {
|
} else if ('clear' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
clearChatAction: {} // add message range later
|
clearChatAction: {} // add message range later
|
||||||
@@ -576,7 +584,7 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 6,
|
apiVersion: 6,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('pin' in mod) {
|
} else if ('pin' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
pinAction: {
|
pinAction: {
|
||||||
@@ -588,7 +596,7 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 5,
|
apiVersion: 5,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('star' in mod) {
|
} else if ('star' in mod) {
|
||||||
const key = mod.star.messages[0]
|
const key = mod.star.messages[0]
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
@@ -601,11 +609,11 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 2,
|
apiVersion: 2,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('delete' in mod) {
|
} else if ('delete' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
deleteChatAction: {
|
deleteChatAction: {
|
||||||
messageRange: getMessageRange(mod.lastMessages),
|
messageRange: getMessageRange(mod.lastMessages)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
index: ['deleteChat', jid, '1'],
|
index: ['deleteChat', jid, '1'],
|
||||||
@@ -613,7 +621,7 @@ export const chatModificationToAppPatch = (
|
|||||||
apiVersion: 6,
|
apiVersion: 6,
|
||||||
operation: OP.SET
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('pushNameSetting' in mod) {
|
} else if ('pushNameSetting' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
pushNameSetting: {
|
pushNameSetting: {
|
||||||
@@ -623,71 +631,64 @@ export const chatModificationToAppPatch = (
|
|||||||
index: ['setting_pushName'],
|
index: ['setting_pushName'],
|
||||||
type: 'critical_block',
|
type: 'critical_block',
|
||||||
apiVersion: 1,
|
apiVersion: 1,
|
||||||
operation: OP.SET,
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('addLabel' in mod) {
|
} else if ('addLabel' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
labelEditAction: {
|
labelEditAction: {
|
||||||
name: mod.addLabel.name,
|
name: mod.addLabel.name,
|
||||||
color: mod.addLabel.color,
|
color: mod.addLabel.color,
|
||||||
predefinedId : mod.addLabel.predefinedId,
|
predefinedId: mod.addLabel.predefinedId,
|
||||||
deleted: mod.addLabel.deleted
|
deleted: mod.addLabel.deleted
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
index: ['label_edit', mod.addLabel.id],
|
index: ['label_edit', mod.addLabel.id],
|
||||||
type: 'regular',
|
type: 'regular',
|
||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET,
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('addChatLabel' in mod) {
|
} else if ('addChatLabel' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
labelAssociationAction: {
|
labelAssociationAction: {
|
||||||
labeled: true,
|
labeled: true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
|
index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
|
||||||
type: 'regular',
|
type: 'regular',
|
||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET,
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('removeChatLabel' in mod) {
|
} else if ('removeChatLabel' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
labelAssociationAction: {
|
labelAssociationAction: {
|
||||||
labeled: false,
|
labeled: false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
|
index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
|
||||||
type: 'regular',
|
type: 'regular',
|
||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET,
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('addMessageLabel' in mod) {
|
} else if ('addMessageLabel' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
labelAssociationAction: {
|
labelAssociationAction: {
|
||||||
labeled: true,
|
labeled: true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
index: [
|
index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
|
||||||
LabelAssociationType.Message,
|
|
||||||
mod.addMessageLabel.labelId,
|
|
||||||
jid,
|
|
||||||
mod.addMessageLabel.messageId,
|
|
||||||
'0',
|
|
||||||
'0'
|
|
||||||
],
|
|
||||||
type: 'regular',
|
type: 'regular',
|
||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET,
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else if('removeMessageLabel' in mod) {
|
} else if ('removeMessageLabel' in mod) {
|
||||||
patch = {
|
patch = {
|
||||||
syncAction: {
|
syncAction: {
|
||||||
labelAssociationAction: {
|
labelAssociationAction: {
|
||||||
labeled: false,
|
labeled: false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
index: [
|
index: [
|
||||||
@@ -700,7 +701,7 @@ export const chatModificationToAppPatch = (
|
|||||||
],
|
],
|
||||||
type: 'regular',
|
type: 'regular',
|
||||||
apiVersion: 3,
|
apiVersion: 3,
|
||||||
operation: OP.SET,
|
operation: OP.SET
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new Boom('not supported')
|
throw new Boom('not supported')
|
||||||
@@ -716,7 +717,7 @@ export const processSyncAction = (
|
|||||||
ev: BaileysEventEmitter,
|
ev: BaileysEventEmitter,
|
||||||
me: Contact,
|
me: Contact,
|
||||||
initialSyncOpts?: InitialAppStateSyncOptions,
|
initialSyncOpts?: InitialAppStateSyncOptions,
|
||||||
logger?: ILogger,
|
logger?: ILogger
|
||||||
) => {
|
) => {
|
||||||
const isInitialSync = !!initialSyncOpts
|
const isInitialSync = !!initialSyncOpts
|
||||||
const accountSettings = initialSyncOpts?.accountSettings
|
const accountSettings = initialSyncOpts?.accountSettings
|
||||||
@@ -728,20 +729,15 @@ export const processSyncAction = (
|
|||||||
index: [type, id, msgId, fromMe]
|
index: [type, id, msgId, fromMe]
|
||||||
} = syncAction
|
} = syncAction
|
||||||
|
|
||||||
if(action?.muteAction) {
|
if (action?.muteAction) {
|
||||||
ev.emit(
|
ev.emit('chats.update', [
|
||||||
'chats.update',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
id,
|
id,
|
||||||
muteEndTime: action.muteAction?.muted
|
muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
|
||||||
? toNumber(action.muteAction.muteEndTimestamp)
|
|
||||||
: null,
|
|
||||||
conditional: getChatUpdateConditional(id, undefined)
|
conditional: getChatUpdateConditional(id, undefined)
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
} else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
|
||||||
} else if(action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
|
|
||||||
// okay so we've to do some annoying computation here
|
// okay so we've to do some annoying computation here
|
||||||
// when we're initially syncing the app state
|
// when we're initially syncing the app state
|
||||||
// there are a few cases we need to handle
|
// there are a few cases we need to handle
|
||||||
@@ -753,9 +749,7 @@ export const processSyncAction = (
|
|||||||
// 2. if the account unarchiveChats setting is false -- then it doesn't matter,
|
// 2. if the account unarchiveChats setting is false -- then it doesn't matter,
|
||||||
// it'll always take an app state action to mark in unarchived -- which we'll get anyway
|
// it'll always take an app state action to mark in unarchived -- which we'll get anyway
|
||||||
const archiveAction = action?.archiveChatAction
|
const archiveAction = action?.archiveChatAction
|
||||||
const isArchived = archiveAction
|
const isArchived = archiveAction ? archiveAction.archived : type === 'archive'
|
||||||
? archiveAction.archived
|
|
||||||
: type === 'archive'
|
|
||||||
// // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
|
// // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
|
||||||
// // this only applies for the initial sync
|
// // this only applies for the initial sync
|
||||||
// if(isInitialSync && !isArchived) {
|
// if(isInitialSync && !isArchived) {
|
||||||
@@ -765,24 +759,28 @@ export const processSyncAction = (
|
|||||||
const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange
|
const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange
|
||||||
// logger?.debug({ chat: id, syncAction }, 'message range archive')
|
// logger?.debug({ chat: id, syncAction }, 'message range archive')
|
||||||
|
|
||||||
ev.emit('chats.update', [{
|
ev.emit('chats.update', [
|
||||||
|
{
|
||||||
id,
|
id,
|
||||||
archived: isArchived,
|
archived: isArchived,
|
||||||
conditional: getChatUpdateConditional(id, msgRange)
|
conditional: getChatUpdateConditional(id, msgRange)
|
||||||
}])
|
}
|
||||||
} else if(action?.markChatAsReadAction) {
|
])
|
||||||
|
} else if (action?.markChatAsReadAction) {
|
||||||
const markReadAction = action.markChatAsReadAction
|
const markReadAction = action.markChatAsReadAction
|
||||||
// basically we don't need to fire an "read" update if the chat is being marked as read
|
// basically we don't need to fire an "read" update if the chat is being marked as read
|
||||||
// because the chat is read by default
|
// because the chat is read by default
|
||||||
// this only applies for the initial sync
|
// this only applies for the initial sync
|
||||||
const isNullUpdate = isInitialSync && markReadAction.read
|
const isNullUpdate = isInitialSync && markReadAction.read
|
||||||
|
|
||||||
ev.emit('chats.update', [{
|
ev.emit('chats.update', [
|
||||||
|
{
|
||||||
id,
|
id,
|
||||||
unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
|
unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
|
||||||
conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
|
conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
|
||||||
}])
|
}
|
||||||
} else if(action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
|
])
|
||||||
|
} else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
|
||||||
ev.emit('messages.delete', {
|
ev.emit('messages.delete', {
|
||||||
keys: [
|
keys: [
|
||||||
{
|
{
|
||||||
@@ -792,30 +790,32 @@ export const processSyncAction = (
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
} else if(action?.contactAction) {
|
} else if (action?.contactAction) {
|
||||||
ev.emit('contacts.upsert', [{ id, name: action.contactAction.fullName! }])
|
ev.emit('contacts.upsert', [{ id, name: action.contactAction.fullName! }])
|
||||||
} else if(action?.pushNameSetting) {
|
} else if (action?.pushNameSetting) {
|
||||||
const name = action?.pushNameSetting?.name
|
const name = action?.pushNameSetting?.name
|
||||||
if(name && me?.name !== name) {
|
if (name && me?.name !== name) {
|
||||||
ev.emit('creds.update', { me: { ...me, name } })
|
ev.emit('creds.update', { me: { ...me, name } })
|
||||||
}
|
}
|
||||||
} else if(action?.pinAction) {
|
} else if (action?.pinAction) {
|
||||||
ev.emit('chats.update', [{
|
ev.emit('chats.update', [
|
||||||
|
{
|
||||||
id,
|
id,
|
||||||
pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
|
pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
|
||||||
conditional: getChatUpdateConditional(id, undefined)
|
conditional: getChatUpdateConditional(id, undefined)
|
||||||
}])
|
}
|
||||||
} else if(action?.unarchiveChatsSetting) {
|
])
|
||||||
|
} else if (action?.unarchiveChatsSetting) {
|
||||||
const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats
|
const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats
|
||||||
ev.emit('creds.update', { accountSettings: { unarchiveChats } })
|
ev.emit('creds.update', { accountSettings: { unarchiveChats } })
|
||||||
|
|
||||||
logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`)
|
logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`)
|
||||||
if(accountSettings) {
|
if (accountSettings) {
|
||||||
accountSettings.unarchiveChats = unarchiveChats
|
accountSettings.unarchiveChats = unarchiveChats
|
||||||
}
|
}
|
||||||
} else if(action?.starAction || type === 'star') {
|
} else if (action?.starAction || type === 'star') {
|
||||||
let starred = action?.starAction?.starred
|
let starred = action?.starAction?.starred
|
||||||
if(typeof starred !== 'boolean') {
|
if (typeof starred !== 'boolean') {
|
||||||
starred = syncAction.index[syncAction.index.length - 1] === '1'
|
starred = syncAction.index[syncAction.index.length - 1] === '1'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -825,11 +825,11 @@ export const processSyncAction = (
|
|||||||
update: { starred }
|
update: { starred }
|
||||||
}
|
}
|
||||||
])
|
])
|
||||||
} else if(action?.deleteChatAction || type === 'deleteChat') {
|
} else if (action?.deleteChatAction || type === 'deleteChat') {
|
||||||
if(!isInitialSync) {
|
if (!isInitialSync) {
|
||||||
ev.emit('chats.delete', [id])
|
ev.emit('chats.delete', [id])
|
||||||
}
|
}
|
||||||
} else if(action?.labelEditAction) {
|
} else if (action?.labelEditAction) {
|
||||||
const { name, color, deleted, predefinedId } = action.labelEditAction
|
const { name, color, deleted, predefinedId } = action.labelEditAction
|
||||||
|
|
||||||
ev.emit('labels.edit', {
|
ev.emit('labels.edit', {
|
||||||
@@ -839,40 +839,45 @@ export const processSyncAction = (
|
|||||||
deleted: deleted!,
|
deleted: deleted!,
|
||||||
predefinedId: predefinedId ? String(predefinedId) : undefined
|
predefinedId: predefinedId ? String(predefinedId) : undefined
|
||||||
})
|
})
|
||||||
} else if(action?.labelAssociationAction) {
|
} else if (action?.labelAssociationAction) {
|
||||||
ev.emit('labels.association', {
|
ev.emit('labels.association', {
|
||||||
type: action.labelAssociationAction.labeled
|
type: action.labelAssociationAction.labeled ? 'add' : 'remove',
|
||||||
? 'add'
|
association:
|
||||||
: 'remove',
|
type === LabelAssociationType.Chat
|
||||||
association: type === LabelAssociationType.Chat
|
? ({
|
||||||
? {
|
|
||||||
type: LabelAssociationType.Chat,
|
type: LabelAssociationType.Chat,
|
||||||
chatId: syncAction.index[2],
|
chatId: syncAction.index[2],
|
||||||
labelId: syncAction.index[1]
|
labelId: syncAction.index[1]
|
||||||
} as ChatLabelAssociation
|
} as ChatLabelAssociation)
|
||||||
: {
|
: ({
|
||||||
type: LabelAssociationType.Message,
|
type: LabelAssociationType.Message,
|
||||||
chatId: syncAction.index[2],
|
chatId: syncAction.index[2],
|
||||||
messageId: syncAction.index[3],
|
messageId: syncAction.index[3],
|
||||||
labelId: syncAction.index[1]
|
labelId: syncAction.index[1]
|
||||||
} as MessageLabelAssociation
|
} as MessageLabelAssociation)
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
logger?.debug({ syncAction, id }, 'unprocessable update')
|
logger?.debug({ syncAction, id }, 'unprocessable update')
|
||||||
}
|
}
|
||||||
|
|
||||||
function getChatUpdateConditional(id: string, msgRange: proto.SyncActionValue.ISyncActionMessageRange | null | undefined): ChatUpdate['conditional'] {
|
function getChatUpdateConditional(
|
||||||
|
id: string,
|
||||||
|
msgRange: proto.SyncActionValue.ISyncActionMessageRange | null | undefined
|
||||||
|
): ChatUpdate['conditional'] {
|
||||||
return isInitialSync
|
return isInitialSync
|
||||||
? (data) => {
|
? data => {
|
||||||
const chat = data.historySets.chats[id] || data.chatUpserts[id]
|
const chat = data.historySets.chats[id] || data.chatUpserts[id]
|
||||||
if(chat) {
|
if (chat) {
|
||||||
return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true
|
return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
function isValidPatchBasedOnMessageRange(chat: Chat, msgRange: proto.SyncActionValue.ISyncActionMessageRange | null | undefined) {
|
function isValidPatchBasedOnMessageRange(
|
||||||
|
chat: Chat,
|
||||||
|
msgRange: proto.SyncActionValue.ISyncActionMessageRange | null | undefined
|
||||||
|
) {
|
||||||
const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
|
const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
|
||||||
const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0)
|
const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0)
|
||||||
return lastMsgTimestamp >= chatLastMsgTimestamp
|
return lastMsgTimestamp >= chatLastMsgTimestamp
|
||||||
|
|||||||
@@ -7,11 +7,8 @@ import { KeyPair } from '../Types'
|
|||||||
const { subtle } = globalThis.crypto
|
const { subtle } = globalThis.crypto
|
||||||
|
|
||||||
/** prefix version byte to the pub keys, required for some curve crypto functions */
|
/** prefix version byte to the pub keys, required for some curve crypto functions */
|
||||||
export const generateSignalPubKey = (pubKey: Uint8Array | Buffer) => (
|
export const generateSignalPubKey = (pubKey: Uint8Array | Buffer) =>
|
||||||
pubKey.length === 33
|
pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey])
|
||||||
? pubKey
|
|
||||||
: Buffer.concat([ KEY_BUNDLE_TYPE, pubKey ])
|
|
||||||
)
|
|
||||||
|
|
||||||
export const Curve = {
|
export const Curve = {
|
||||||
generateKeyPair: (): KeyPair => {
|
generateKeyPair: (): KeyPair => {
|
||||||
@@ -26,14 +23,12 @@ export const Curve = {
|
|||||||
const shared = libsignal.curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey)
|
const shared = libsignal.curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey)
|
||||||
return Buffer.from(shared)
|
return Buffer.from(shared)
|
||||||
},
|
},
|
||||||
sign: (privateKey: Uint8Array, buf: Uint8Array) => (
|
sign: (privateKey: Uint8Array, buf: Uint8Array) => libsignal.curve.calculateSignature(privateKey, buf),
|
||||||
libsignal.curve.calculateSignature(privateKey, buf)
|
|
||||||
),
|
|
||||||
verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => {
|
verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => {
|
||||||
try {
|
try {
|
||||||
libsignal.curve.verifySignature(generateSignalPubKey(pubKey), message, signature)
|
libsignal.curve.verifySignature(generateSignalPubKey(pubKey), message, signature)
|
||||||
return true
|
return true
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,7 +68,7 @@ export function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8
|
|||||||
decipher.setAAD(additionalData)
|
decipher.setAAD(additionalData)
|
||||||
decipher.setAuthTag(tag)
|
decipher.setAuthTag(tag)
|
||||||
|
|
||||||
return Buffer.concat([ decipher.update(enc), decipher.final() ])
|
return Buffer.concat([decipher.update(enc), decipher.final()])
|
||||||
}
|
}
|
||||||
|
|
||||||
export function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array) {
|
export function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array) {
|
||||||
@@ -111,7 +106,11 @@ export function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// sign HMAC using SHA 256
|
// sign HMAC using SHA 256
|
||||||
export function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant: 'sha256' | 'sha512' = 'sha256') {
|
export function hmacSign(
|
||||||
|
buffer: Buffer | Uint8Array,
|
||||||
|
key: Buffer | Uint8Array,
|
||||||
|
variant: 'sha256' | 'sha512' = 'sha256'
|
||||||
|
) {
|
||||||
return createHmac(variant, key).update(buffer).digest()
|
return createHmac(variant, key).update(buffer).digest()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,27 +126,17 @@ export function md5(buffer: Buffer) {
|
|||||||
export async function hkdf(
|
export async function hkdf(
|
||||||
buffer: Uint8Array | Buffer,
|
buffer: Uint8Array | Buffer,
|
||||||
expandedLength: number,
|
expandedLength: number,
|
||||||
info: { salt?: Buffer, info?: string }
|
info: { salt?: Buffer; info?: string }
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
// Ensure we have a Uint8Array for the key material
|
// Ensure we have a Uint8Array for the key material
|
||||||
const inputKeyMaterial = buffer instanceof Uint8Array
|
const inputKeyMaterial = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)
|
||||||
? buffer
|
|
||||||
: new Uint8Array(buffer)
|
|
||||||
|
|
||||||
// Set default values if not provided
|
// Set default values if not provided
|
||||||
const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0)
|
const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0)
|
||||||
const infoBytes = info.info
|
const infoBytes = info.info ? new TextEncoder().encode(info.info) : new Uint8Array(0)
|
||||||
? new TextEncoder().encode(info.info)
|
|
||||||
: new Uint8Array(0)
|
|
||||||
|
|
||||||
// Import the input key material
|
// Import the input key material
|
||||||
const importedKey = await subtle.importKey(
|
const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits'])
|
||||||
'raw',
|
|
||||||
inputKeyMaterial,
|
|
||||||
{ name: 'HKDF' },
|
|
||||||
false,
|
|
||||||
['deriveBits']
|
|
||||||
)
|
|
||||||
|
|
||||||
// Derive bits using HKDF
|
// Derive bits using HKDF
|
||||||
const derivedBits = await subtle.deriveBits(
|
const derivedBits = await subtle.deriveBits(
|
||||||
@@ -164,7 +153,6 @@ export async function hkdf(
|
|||||||
return Buffer.from(derivedBits)
|
return Buffer.from(derivedBits)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export async function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer> {
|
export async function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer> {
|
||||||
// Convert inputs to formats Web Crypto API can work with
|
// Convert inputs to formats Web Crypto API can work with
|
||||||
const encoder = new TextEncoder()
|
const encoder = new TextEncoder()
|
||||||
@@ -172,13 +160,7 @@ export async function derivePairingCodeKey(pairingCode: string, salt: Buffer): P
|
|||||||
const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt)
|
const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt)
|
||||||
|
|
||||||
// Import the pairing code as key material
|
// Import the pairing code as key material
|
||||||
const keyMaterial = await subtle.importKey(
|
const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits'])
|
||||||
'raw',
|
|
||||||
pairingCodeBuffer,
|
|
||||||
{ name: 'PBKDF2' },
|
|
||||||
false,
|
|
||||||
['deriveBits']
|
|
||||||
)
|
|
||||||
|
|
||||||
// Derive bits using PBKDF2 with the same parameters
|
// Derive bits using PBKDF2 with the same parameters
|
||||||
// 2 << 16 = 131,072 iterations
|
// 2 << 16 = 131,072 iterations
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
import { Boom } from '@hapi/boom'
|
import { Boom } from '@hapi/boom'
|
||||||
import { proto } from '../../WAProto'
|
import { proto } from '../../WAProto'
|
||||||
import { SignalRepository, WAMessageKey } from '../Types'
|
import { SignalRepository, WAMessageKey } from '../Types'
|
||||||
import { areJidsSameUser, BinaryNode, isJidBroadcast, isJidGroup, isJidMetaIa, isJidNewsletter, isJidStatusBroadcast, isJidUser, isLidUser } from '../WABinary'
|
import {
|
||||||
|
areJidsSameUser,
|
||||||
|
BinaryNode,
|
||||||
|
isJidBroadcast,
|
||||||
|
isJidGroup,
|
||||||
|
isJidMetaIa,
|
||||||
|
isJidNewsletter,
|
||||||
|
isJidStatusBroadcast,
|
||||||
|
isJidUser,
|
||||||
|
isLidUser
|
||||||
|
} from '../WABinary'
|
||||||
import { unpadRandomMax16 } from './generics'
|
import { unpadRandomMax16 } from './generics'
|
||||||
import { ILogger } from './logger'
|
import { ILogger } from './logger'
|
||||||
|
|
||||||
@@ -24,17 +34,20 @@ export const NACK_REASONS = {
|
|||||||
DBOperationFailed: 552
|
DBOperationFailed: 552
|
||||||
}
|
}
|
||||||
|
|
||||||
type MessageType = 'chat' | 'peer_broadcast' | 'other_broadcast' | 'group' | 'direct_peer_status' | 'other_status' | 'newsletter'
|
type MessageType =
|
||||||
|
| 'chat'
|
||||||
|
| 'peer_broadcast'
|
||||||
|
| 'other_broadcast'
|
||||||
|
| 'group'
|
||||||
|
| 'direct_peer_status'
|
||||||
|
| 'other_status'
|
||||||
|
| 'newsletter'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decode the received node as a message.
|
* Decode the received node as a message.
|
||||||
* @note this will only parse the message, not decrypt it
|
* @note this will only parse the message, not decrypt it
|
||||||
*/
|
*/
|
||||||
export function decodeMessageNode(
|
export function decodeMessageNode(stanza: BinaryNode, meId: string, meLid: string) {
|
||||||
stanza: BinaryNode,
|
|
||||||
meId: string,
|
|
||||||
meLid: string
|
|
||||||
) {
|
|
||||||
let msgType: MessageType
|
let msgType: MessageType
|
||||||
let chatId: string
|
let chatId: string
|
||||||
let author: string
|
let author: string
|
||||||
@@ -47,9 +60,9 @@ export function decodeMessageNode(
|
|||||||
const isMe = (jid: string) => areJidsSameUser(jid, meId)
|
const isMe = (jid: string) => areJidsSameUser(jid, meId)
|
||||||
const isMeLid = (jid: string) => areJidsSameUser(jid, meLid)
|
const isMeLid = (jid: string) => areJidsSameUser(jid, meLid)
|
||||||
|
|
||||||
if(isJidUser(from) || isLidUser(from)) {
|
if (isJidUser(from) || isLidUser(from)) {
|
||||||
if(recipient && !isJidMetaIa(recipient)) {
|
if (recipient && !isJidMetaIa(recipient)) {
|
||||||
if(!isMe(from) && !isMeLid(from)) {
|
if (!isMe(from) && !isMeLid(from)) {
|
||||||
throw new Boom('receipient present, but msg not from me', { data: stanza })
|
throw new Boom('receipient present, but msg not from me', { data: stanza })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,21 +73,21 @@ export function decodeMessageNode(
|
|||||||
|
|
||||||
msgType = 'chat'
|
msgType = 'chat'
|
||||||
author = from
|
author = from
|
||||||
} else if(isJidGroup(from)) {
|
} else if (isJidGroup(from)) {
|
||||||
if(!participant) {
|
if (!participant) {
|
||||||
throw new Boom('No participant in group message')
|
throw new Boom('No participant in group message')
|
||||||
}
|
}
|
||||||
|
|
||||||
msgType = 'group'
|
msgType = 'group'
|
||||||
author = participant
|
author = participant
|
||||||
chatId = from
|
chatId = from
|
||||||
} else if(isJidBroadcast(from)) {
|
} else if (isJidBroadcast(from)) {
|
||||||
if(!participant) {
|
if (!participant) {
|
||||||
throw new Boom('No participant in group message')
|
throw new Boom('No participant in group message')
|
||||||
}
|
}
|
||||||
|
|
||||||
const isParticipantMe = isMe(participant)
|
const isParticipantMe = isMe(participant)
|
||||||
if(isJidStatusBroadcast(from)) {
|
if (isJidStatusBroadcast(from)) {
|
||||||
msgType = isParticipantMe ? 'direct_peer_status' : 'other_status'
|
msgType = isParticipantMe ? 'direct_peer_status' : 'other_status'
|
||||||
} else {
|
} else {
|
||||||
msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast'
|
msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast'
|
||||||
@@ -82,7 +95,7 @@ export function decodeMessageNode(
|
|||||||
|
|
||||||
chatId = from
|
chatId = from
|
||||||
author = participant
|
author = participant
|
||||||
} else if(isJidNewsletter(from)) {
|
} else if (isJidNewsletter(from)) {
|
||||||
msgType = 'newsletter'
|
msgType = 'newsletter'
|
||||||
chatId = from
|
chatId = from
|
||||||
author = from
|
author = from
|
||||||
@@ -107,7 +120,7 @@ export function decodeMessageNode(
|
|||||||
broadcast: isJidBroadcast(from)
|
broadcast: isJidBroadcast(from)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(key.fromMe) {
|
if (key.fromMe) {
|
||||||
fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK
|
fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,19 +145,19 @@ export const decryptMessageNode = (
|
|||||||
author,
|
author,
|
||||||
async decrypt() {
|
async decrypt() {
|
||||||
let decryptables = 0
|
let decryptables = 0
|
||||||
if(Array.isArray(stanza.content)) {
|
if (Array.isArray(stanza.content)) {
|
||||||
for(const { tag, attrs, content } of stanza.content) {
|
for (const { tag, attrs, content } of stanza.content) {
|
||||||
if(tag === 'verified_name' && content instanceof Uint8Array) {
|
if (tag === 'verified_name' && content instanceof Uint8Array) {
|
||||||
const cert = proto.VerifiedNameCertificate.decode(content)
|
const cert = proto.VerifiedNameCertificate.decode(content)
|
||||||
const details = proto.VerifiedNameCertificate.Details.decode(cert.details!)
|
const details = proto.VerifiedNameCertificate.Details.decode(cert.details!)
|
||||||
fullMessage.verifiedBizName = details.verifiedName
|
fullMessage.verifiedBizName = details.verifiedName
|
||||||
}
|
}
|
||||||
|
|
||||||
if(tag !== 'enc' && tag !== 'plaintext') {
|
if (tag !== 'enc' && tag !== 'plaintext') {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!(content instanceof Uint8Array)) {
|
if (!(content instanceof Uint8Array)) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,30 +191,29 @@ export const decryptMessageNode = (
|
|||||||
throw new Error(`Unknown e2e type: ${e2eType}`)
|
throw new Error(`Unknown e2e type: ${e2eType}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
let msg: proto.IMessage = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer)
|
let msg: proto.IMessage = proto.Message.decode(
|
||||||
|
e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer
|
||||||
|
)
|
||||||
msg = msg.deviceSentMessage?.message || msg
|
msg = msg.deviceSentMessage?.message || msg
|
||||||
if(msg.senderKeyDistributionMessage) {
|
if (msg.senderKeyDistributionMessage) {
|
||||||
//eslint-disable-next-line max-depth
|
//eslint-disable-next-line max-depth
|
||||||
try {
|
try {
|
||||||
await repository.processSenderKeyDistributionMessage({
|
await repository.processSenderKeyDistributionMessage({
|
||||||
authorJid: author,
|
authorJid: author,
|
||||||
item: msg.senderKeyDistributionMessage
|
item: msg.senderKeyDistributionMessage
|
||||||
})
|
})
|
||||||
} catch(err) {
|
} catch (err) {
|
||||||
logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
|
logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(fullMessage.message) {
|
if (fullMessage.message) {
|
||||||
Object.assign(fullMessage.message, msg)
|
Object.assign(fullMessage.message, msg)
|
||||||
} else {
|
} else {
|
||||||
fullMessage.message = msg
|
fullMessage.message = msg
|
||||||
}
|
}
|
||||||
} catch(err) {
|
} catch (err) {
|
||||||
logger.error(
|
logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
|
||||||
{ key: fullMessage.key, err },
|
|
||||||
'failed to decrypt message'
|
|
||||||
)
|
|
||||||
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
||||||
fullMessage.messageStubParameters = [err.message]
|
fullMessage.messageStubParameters = [err.message]
|
||||||
}
|
}
|
||||||
@@ -209,7 +221,7 @@ export const decryptMessageNode = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// if nothing was found to decrypt
|
// if nothing was found to decrypt
|
||||||
if(!decryptables) {
|
if (!decryptables) {
|
||||||
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
||||||
fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT]
|
fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,16 @@
|
|||||||
import EventEmitter from 'events'
|
import EventEmitter from 'events'
|
||||||
import { proto } from '../../WAProto'
|
import { proto } from '../../WAProto'
|
||||||
import { BaileysEvent, BaileysEventEmitter, BaileysEventMap, BufferedEventData, Chat, ChatUpdate, Contact, WAMessage, WAMessageStatus } from '../Types'
|
import {
|
||||||
|
BaileysEvent,
|
||||||
|
BaileysEventEmitter,
|
||||||
|
BaileysEventMap,
|
||||||
|
BufferedEventData,
|
||||||
|
Chat,
|
||||||
|
ChatUpdate,
|
||||||
|
Contact,
|
||||||
|
WAMessage,
|
||||||
|
WAMessageStatus
|
||||||
|
} from '../Types'
|
||||||
import { trimUndefined } from './generics'
|
import { trimUndefined } from './generics'
|
||||||
import { ILogger } from './logger'
|
import { ILogger } from './logger'
|
||||||
import { updateMessageWithReaction, updateMessageWithReceipt } from './messages'
|
import { updateMessageWithReaction, updateMessageWithReceipt } from './messages'
|
||||||
@@ -18,10 +28,10 @@ const BUFFERABLE_EVENT = [
|
|||||||
'messages.delete',
|
'messages.delete',
|
||||||
'messages.reaction',
|
'messages.reaction',
|
||||||
'message-receipt.update',
|
'message-receipt.update',
|
||||||
'groups.update',
|
'groups.update'
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
type BufferableEvent = typeof BUFFERABLE_EVENT[number]
|
type BufferableEvent = (typeof BUFFERABLE_EVENT)[number]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A map that contains a list of all events that have been triggered
|
* A map that contains a list of all events that have been triggered
|
||||||
@@ -36,14 +46,14 @@ const BUFFERABLE_EVENT_SET = new Set<BaileysEvent>(BUFFERABLE_EVENT)
|
|||||||
|
|
||||||
type BaileysBufferableEventEmitter = BaileysEventEmitter & {
|
type BaileysBufferableEventEmitter = BaileysEventEmitter & {
|
||||||
/** Use to process events in a batch */
|
/** Use to process events in a batch */
|
||||||
process(handler: (events: BaileysEventData) => void | Promise<void>): (() => void)
|
process(handler: (events: BaileysEventData) => void | Promise<void>): () => void
|
||||||
/**
|
/**
|
||||||
* starts buffering events, call flush() to release them
|
* starts buffering events, call flush() to release them
|
||||||
* */
|
* */
|
||||||
buffer(): void
|
buffer(): void
|
||||||
/** buffers all events till the promise completes */
|
/** buffers all events till the promise completes */
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>)
|
createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>
|
||||||
/**
|
/**
|
||||||
* flushes all buffered events
|
* flushes all buffered events
|
||||||
* @param force if true, will flush all data regardless of any pending buffers
|
* @param force if true, will flush all data regardless of any pending buffers
|
||||||
@@ -68,7 +78,7 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
|||||||
|
|
||||||
// take the generic event and fire it as a baileys event
|
// take the generic event and fire it as a baileys event
|
||||||
ev.on('event', (map: BaileysEventData) => {
|
ev.on('event', (map: BaileysEventData) => {
|
||||||
for(const event in map) {
|
for (const event in map) {
|
||||||
ev.emit(event, map[event])
|
ev.emit(event, map[event])
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -79,16 +89,16 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
|||||||
|
|
||||||
function flush(force = false) {
|
function flush(force = false) {
|
||||||
// no buffer going on
|
// no buffer going on
|
||||||
if(!buffersInProgress) {
|
if (!buffersInProgress) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!force) {
|
if (!force) {
|
||||||
// reduce the number of buffers in progress
|
// reduce the number of buffers in progress
|
||||||
buffersInProgress -= 1
|
buffersInProgress -= 1
|
||||||
// if there are still some buffers going on
|
// if there are still some buffers going on
|
||||||
// then we don't flush now
|
// then we don't flush now
|
||||||
if(buffersInProgress) {
|
if (buffersInProgress) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,8 +107,8 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
|||||||
const chatUpdates = Object.values(data.chatUpdates)
|
const chatUpdates = Object.values(data.chatUpdates)
|
||||||
// gather the remaining conditional events so we re-queue them
|
// gather the remaining conditional events so we re-queue them
|
||||||
let conditionalChatUpdatesLeft = 0
|
let conditionalChatUpdatesLeft = 0
|
||||||
for(const update of chatUpdates) {
|
for (const update of chatUpdates) {
|
||||||
if(update.conditional) {
|
if (update.conditional) {
|
||||||
conditionalChatUpdatesLeft += 1
|
conditionalChatUpdatesLeft += 1
|
||||||
newData.chatUpdates[update.id!] = update
|
newData.chatUpdates[update.id!] = update
|
||||||
delete data.chatUpdates[update.id!]
|
delete data.chatUpdates[update.id!]
|
||||||
@@ -106,16 +116,13 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
|||||||
}
|
}
|
||||||
|
|
||||||
const consolidatedData = consolidateEvents(data)
|
const consolidatedData = consolidateEvents(data)
|
||||||
if(Object.keys(consolidatedData).length) {
|
if (Object.keys(consolidatedData).length) {
|
||||||
ev.emit('event', consolidatedData)
|
ev.emit('event', consolidatedData)
|
||||||
}
|
}
|
||||||
|
|
||||||
data = newData
|
data = newData
|
||||||
|
|
||||||
logger.trace(
|
logger.trace({ conditionalChatUpdatesLeft }, 'released buffered events')
|
||||||
{ conditionalChatUpdatesLeft },
|
|
||||||
'released buffered events'
|
|
||||||
)
|
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -132,7 +139,7 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
emit<T extends BaileysEvent>(event: BaileysEvent, evData: BaileysEventMap[T]) {
|
emit<T extends BaileysEvent>(event: BaileysEvent, evData: BaileysEventMap[T]) {
|
||||||
if(buffersInProgress && BUFFERABLE_EVENT_SET.has(event)) {
|
if (buffersInProgress && BUFFERABLE_EVENT_SET.has(event)) {
|
||||||
append(data, historyCache, event as BufferableEvent, evData, logger)
|
append(data, historyCache, event as BufferableEvent, evData, logger)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -145,7 +152,7 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
|||||||
buffer,
|
buffer,
|
||||||
flush,
|
flush,
|
||||||
createBufferedFunction(work) {
|
createBufferedFunction(work) {
|
||||||
return async(...args) => {
|
return async (...args) => {
|
||||||
buffer()
|
buffer()
|
||||||
try {
|
try {
|
||||||
const result = await work(...args)
|
const result = await work(...args)
|
||||||
@@ -157,30 +164,30 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
|||||||
},
|
},
|
||||||
on: (...args) => ev.on(...args),
|
on: (...args) => ev.on(...args),
|
||||||
off: (...args) => ev.off(...args),
|
off: (...args) => ev.off(...args),
|
||||||
removeAllListeners: (...args) => ev.removeAllListeners(...args),
|
removeAllListeners: (...args) => ev.removeAllListeners(...args)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const makeBufferData = (): BufferedEventData => {
|
const makeBufferData = (): BufferedEventData => {
|
||||||
return {
|
return {
|
||||||
historySets: {
|
historySets: {
|
||||||
chats: { },
|
chats: {},
|
||||||
messages: { },
|
messages: {},
|
||||||
contacts: { },
|
contacts: {},
|
||||||
isLatest: false,
|
isLatest: false,
|
||||||
empty: true
|
empty: true
|
||||||
},
|
},
|
||||||
chatUpserts: { },
|
chatUpserts: {},
|
||||||
chatUpdates: { },
|
chatUpdates: {},
|
||||||
chatDeletes: new Set(),
|
chatDeletes: new Set(),
|
||||||
contactUpserts: { },
|
contactUpserts: {},
|
||||||
contactUpdates: { },
|
contactUpdates: {},
|
||||||
messageUpserts: { },
|
messageUpserts: {},
|
||||||
messageUpdates: { },
|
messageUpdates: {},
|
||||||
messageReactions: { },
|
messageReactions: {},
|
||||||
messageDeletes: { },
|
messageDeletes: {},
|
||||||
messageReceipts: { },
|
messageReceipts: {},
|
||||||
groupUpdates: { }
|
groupUpdates: {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,13 +201,13 @@ function append<E extends BufferableEvent>(
|
|||||||
) {
|
) {
|
||||||
switch (event) {
|
switch (event) {
|
||||||
case 'messaging-history.set':
|
case 'messaging-history.set':
|
||||||
for(const chat of eventData.chats as Chat[]) {
|
for (const chat of eventData.chats as Chat[]) {
|
||||||
const existingChat = data.historySets.chats[chat.id]
|
const existingChat = data.historySets.chats[chat.id]
|
||||||
if(existingChat) {
|
if (existingChat) {
|
||||||
existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType
|
existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!existingChat && !historyCache.has(chat.id)) {
|
if (!existingChat && !historyCache.has(chat.id)) {
|
||||||
data.historySets.chats[chat.id] = chat
|
data.historySets.chats[chat.id] = chat
|
||||||
historyCache.add(chat.id)
|
historyCache.add(chat.id)
|
||||||
|
|
||||||
@@ -208,24 +215,24 @@ function append<E extends BufferableEvent>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const contact of eventData.contacts as Contact[]) {
|
for (const contact of eventData.contacts as Contact[]) {
|
||||||
const existingContact = data.historySets.contacts[contact.id]
|
const existingContact = data.historySets.contacts[contact.id]
|
||||||
if(existingContact) {
|
if (existingContact) {
|
||||||
Object.assign(existingContact, trimUndefined(contact))
|
Object.assign(existingContact, trimUndefined(contact))
|
||||||
} else {
|
} else {
|
||||||
const historyContactId = `c:${contact.id}`
|
const historyContactId = `c:${contact.id}`
|
||||||
const hasAnyName = contact.notify || contact.name || contact.verifiedName
|
const hasAnyName = contact.notify || contact.name || contact.verifiedName
|
||||||
if(!historyCache.has(historyContactId) || hasAnyName) {
|
if (!historyCache.has(historyContactId) || hasAnyName) {
|
||||||
data.historySets.contacts[contact.id] = contact
|
data.historySets.contacts[contact.id] = contact
|
||||||
historyCache.add(historyContactId)
|
historyCache.add(historyContactId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const message of eventData.messages as WAMessage[]) {
|
for (const message of eventData.messages as WAMessage[]) {
|
||||||
const key = stringifyMessageKey(message.key)
|
const key = stringifyMessageKey(message.key)
|
||||||
const existingMsg = data.historySets.messages[key]
|
const existingMsg = data.historySets.messages[key]
|
||||||
if(!existingMsg && !historyCache.has(key)) {
|
if (!existingMsg && !historyCache.has(key)) {
|
||||||
data.historySets.messages[key] = message
|
data.historySets.messages[key] = message
|
||||||
historyCache.add(key)
|
historyCache.add(key)
|
||||||
}
|
}
|
||||||
@@ -239,16 +246,16 @@ function append<E extends BufferableEvent>(
|
|||||||
|
|
||||||
break
|
break
|
||||||
case 'chats.upsert':
|
case 'chats.upsert':
|
||||||
for(const chat of eventData as Chat[]) {
|
for (const chat of eventData as Chat[]) {
|
||||||
let upsert = data.chatUpserts[chat.id]
|
let upsert = data.chatUpserts[chat.id]
|
||||||
if(!upsert) {
|
if (!upsert) {
|
||||||
upsert = data.historySets[chat.id]
|
upsert = data.historySets[chat.id]
|
||||||
if(upsert) {
|
if (upsert) {
|
||||||
logger.debug({ chatId: chat.id }, 'absorbed chat upsert in chat set')
|
logger.debug({ chatId: chat.id }, 'absorbed chat upsert in chat set')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(upsert) {
|
if (upsert) {
|
||||||
upsert = concatChats(upsert, chat)
|
upsert = concatChats(upsert, chat)
|
||||||
} else {
|
} else {
|
||||||
upsert = chat
|
upsert = chat
|
||||||
@@ -257,29 +264,29 @@ function append<E extends BufferableEvent>(
|
|||||||
|
|
||||||
absorbingChatUpdate(upsert)
|
absorbingChatUpdate(upsert)
|
||||||
|
|
||||||
if(data.chatDeletes.has(chat.id)) {
|
if (data.chatDeletes.has(chat.id)) {
|
||||||
data.chatDeletes.delete(chat.id)
|
data.chatDeletes.delete(chat.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break
|
||||||
case 'chats.update':
|
case 'chats.update':
|
||||||
for(const update of eventData as ChatUpdate[]) {
|
for (const update of eventData as ChatUpdate[]) {
|
||||||
const chatId = update.id!
|
const chatId = update.id!
|
||||||
const conditionMatches = update.conditional ? update.conditional(data) : true
|
const conditionMatches = update.conditional ? update.conditional(data) : true
|
||||||
if(conditionMatches) {
|
if (conditionMatches) {
|
||||||
delete update.conditional
|
delete update.conditional
|
||||||
|
|
||||||
// if there is an existing upsert, merge the update into it
|
// if there is an existing upsert, merge the update into it
|
||||||
const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId]
|
const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId]
|
||||||
if(upsert) {
|
if (upsert) {
|
||||||
concatChats(upsert, update)
|
concatChats(upsert, update)
|
||||||
} else {
|
} else {
|
||||||
// merge the update into the existing update
|
// merge the update into the existing update
|
||||||
const chatUpdate = data.chatUpdates[chatId] || { }
|
const chatUpdate = data.chatUpdates[chatId] || {}
|
||||||
data.chatUpdates[chatId] = concatChats(chatUpdate, update)
|
data.chatUpdates[chatId] = concatChats(chatUpdate, update)
|
||||||
}
|
}
|
||||||
} else if(conditionMatches === undefined) {
|
} else if (conditionMatches === undefined) {
|
||||||
// condition yet to be fulfilled
|
// condition yet to be fulfilled
|
||||||
data.chatUpdates[chatId] = update
|
data.chatUpdates[chatId] = update
|
||||||
}
|
}
|
||||||
@@ -287,52 +294,51 @@ function append<E extends BufferableEvent>(
|
|||||||
|
|
||||||
// if the chat has been updated
|
// if the chat has been updated
|
||||||
// ignore any existing chat delete
|
// ignore any existing chat delete
|
||||||
if(data.chatDeletes.has(chatId)) {
|
if (data.chatDeletes.has(chatId)) {
|
||||||
data.chatDeletes.delete(chatId)
|
data.chatDeletes.delete(chatId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break
|
||||||
case 'chats.delete':
|
case 'chats.delete':
|
||||||
for(const chatId of eventData as string[]) {
|
for (const chatId of eventData as string[]) {
|
||||||
if(!data.chatDeletes.has(chatId)) {
|
if (!data.chatDeletes.has(chatId)) {
|
||||||
data.chatDeletes.add(chatId)
|
data.chatDeletes.add(chatId)
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove any prior updates & upserts
|
// remove any prior updates & upserts
|
||||||
if(data.chatUpdates[chatId]) {
|
if (data.chatUpdates[chatId]) {
|
||||||
delete data.chatUpdates[chatId]
|
delete data.chatUpdates[chatId]
|
||||||
}
|
}
|
||||||
|
|
||||||
if(data.chatUpserts[chatId]) {
|
if (data.chatUpserts[chatId]) {
|
||||||
delete data.chatUpserts[chatId]
|
delete data.chatUpserts[chatId]
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(data.historySets.chats[chatId]) {
|
if (data.historySets.chats[chatId]) {
|
||||||
delete data.historySets.chats[chatId]
|
delete data.historySets.chats[chatId]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break
|
||||||
case 'contacts.upsert':
|
case 'contacts.upsert':
|
||||||
for(const contact of eventData as Contact[]) {
|
for (const contact of eventData as Contact[]) {
|
||||||
let upsert = data.contactUpserts[contact.id]
|
let upsert = data.contactUpserts[contact.id]
|
||||||
if(!upsert) {
|
if (!upsert) {
|
||||||
upsert = data.historySets.contacts[contact.id]
|
upsert = data.historySets.contacts[contact.id]
|
||||||
if(upsert) {
|
if (upsert) {
|
||||||
logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set')
|
logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(upsert) {
|
if (upsert) {
|
||||||
upsert = Object.assign(upsert, trimUndefined(contact))
|
upsert = Object.assign(upsert, trimUndefined(contact))
|
||||||
} else {
|
} else {
|
||||||
upsert = contact
|
upsert = contact
|
||||||
data.contactUpserts[contact.id] = upsert
|
data.contactUpserts[contact.id] = upsert
|
||||||
}
|
}
|
||||||
|
|
||||||
if(data.contactUpdates[contact.id]) {
|
if (data.contactUpdates[contact.id]) {
|
||||||
upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact)) as Contact
|
upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact)) as Contact
|
||||||
delete data.contactUpdates[contact.id]
|
delete data.contactUpdates[contact.id]
|
||||||
}
|
}
|
||||||
@@ -341,15 +347,15 @@ function append<E extends BufferableEvent>(
|
|||||||
break
|
break
|
||||||
case 'contacts.update':
|
case 'contacts.update':
|
||||||
const contactUpdates = eventData as BaileysEventMap['contacts.update']
|
const contactUpdates = eventData as BaileysEventMap['contacts.update']
|
||||||
for(const update of contactUpdates) {
|
for (const update of contactUpdates) {
|
||||||
const id = update.id!
|
const id = update.id!
|
||||||
// merge into prior upsert
|
// merge into prior upsert
|
||||||
const upsert = data.historySets.contacts[id] || data.contactUpserts[id]
|
const upsert = data.historySets.contacts[id] || data.contactUpserts[id]
|
||||||
if(upsert) {
|
if (upsert) {
|
||||||
Object.assign(upsert, update)
|
Object.assign(upsert, update)
|
||||||
} else {
|
} else {
|
||||||
// merge into prior update
|
// merge into prior update
|
||||||
const contactUpdate = data.contactUpdates[id] || { }
|
const contactUpdate = data.contactUpdates[id] || {}
|
||||||
data.contactUpdates[id] = Object.assign(contactUpdate, update)
|
data.contactUpdates[id] = Object.assign(contactUpdate, update)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -357,34 +363,32 @@ function append<E extends BufferableEvent>(
|
|||||||
break
|
break
|
||||||
case 'messages.upsert':
|
case 'messages.upsert':
|
||||||
const { messages, type } = eventData as BaileysEventMap['messages.upsert']
|
const { messages, type } = eventData as BaileysEventMap['messages.upsert']
|
||||||
for(const message of messages) {
|
for (const message of messages) {
|
||||||
const key = stringifyMessageKey(message.key)
|
const key = stringifyMessageKey(message.key)
|
||||||
let existing = data.messageUpserts[key]?.message
|
let existing = data.messageUpserts[key]?.message
|
||||||
if(!existing) {
|
if (!existing) {
|
||||||
existing = data.historySets.messages[key]
|
existing = data.historySets.messages[key]
|
||||||
if(existing) {
|
if (existing) {
|
||||||
logger.debug({ messageId: key }, 'absorbed message upsert in message set')
|
logger.debug({ messageId: key }, 'absorbed message upsert in message set')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(existing) {
|
if (existing) {
|
||||||
message.messageTimestamp = existing.messageTimestamp
|
message.messageTimestamp = existing.messageTimestamp
|
||||||
}
|
}
|
||||||
|
|
||||||
if(data.messageUpdates[key]) {
|
if (data.messageUpdates[key]) {
|
||||||
logger.debug('absorbed prior message update in message upsert')
|
logger.debug('absorbed prior message update in message upsert')
|
||||||
Object.assign(message, data.messageUpdates[key].update)
|
Object.assign(message, data.messageUpdates[key].update)
|
||||||
delete data.messageUpdates[key]
|
delete data.messageUpdates[key]
|
||||||
}
|
}
|
||||||
|
|
||||||
if(data.historySets.messages[key]) {
|
if (data.historySets.messages[key]) {
|
||||||
data.historySets.messages[key] = message
|
data.historySets.messages[key] = message
|
||||||
} else {
|
} else {
|
||||||
data.messageUpserts[key] = {
|
data.messageUpserts[key] = {
|
||||||
message,
|
message,
|
||||||
type: type === 'notify' || data.messageUpserts[key]?.type === 'notify'
|
type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
|
||||||
? 'notify'
|
|
||||||
: type
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -392,19 +396,19 @@ function append<E extends BufferableEvent>(
|
|||||||
break
|
break
|
||||||
case 'messages.update':
|
case 'messages.update':
|
||||||
const msgUpdates = eventData as BaileysEventMap['messages.update']
|
const msgUpdates = eventData as BaileysEventMap['messages.update']
|
||||||
for(const { key, update } of msgUpdates) {
|
for (const { key, update } of msgUpdates) {
|
||||||
const keyStr = stringifyMessageKey(key)
|
const keyStr = stringifyMessageKey(key)
|
||||||
const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message
|
const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message
|
||||||
if(existing) {
|
if (existing) {
|
||||||
Object.assign(existing, update)
|
Object.assign(existing, update)
|
||||||
// if the message was received & read by us
|
// if the message was received & read by us
|
||||||
// the chat counter must have been incremented
|
// the chat counter must have been incremented
|
||||||
// so we need to decrement it
|
// so we need to decrement it
|
||||||
if(update.status === WAMessageStatus.READ && !key.fromMe) {
|
if (update.status === WAMessageStatus.READ && !key.fromMe) {
|
||||||
decrementChatReadCounterIfMsgDidUnread(existing)
|
decrementChatReadCounterIfMsgDidUnread(existing)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const msgUpdate = data.messageUpdates[keyStr] || { key, update: { } }
|
const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} }
|
||||||
Object.assign(msgUpdate.update, update)
|
Object.assign(msgUpdate.update, update)
|
||||||
data.messageUpdates[keyStr] = msgUpdate
|
data.messageUpdates[keyStr] = msgUpdate
|
||||||
}
|
}
|
||||||
@@ -413,20 +417,19 @@ function append<E extends BufferableEvent>(
|
|||||||
break
|
break
|
||||||
case 'messages.delete':
|
case 'messages.delete':
|
||||||
const deleteData = eventData as BaileysEventMap['messages.delete']
|
const deleteData = eventData as BaileysEventMap['messages.delete']
|
||||||
if('keys' in deleteData) {
|
if ('keys' in deleteData) {
|
||||||
const { keys } = deleteData
|
const { keys } = deleteData
|
||||||
for(const key of keys) {
|
for (const key of keys) {
|
||||||
const keyStr = stringifyMessageKey(key)
|
const keyStr = stringifyMessageKey(key)
|
||||||
if(!data.messageDeletes[keyStr]) {
|
if (!data.messageDeletes[keyStr]) {
|
||||||
data.messageDeletes[keyStr] = key
|
data.messageDeletes[keyStr] = key
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(data.messageUpserts[keyStr]) {
|
if (data.messageUpserts[keyStr]) {
|
||||||
delete data.messageUpserts[keyStr]
|
delete data.messageUpserts[keyStr]
|
||||||
}
|
}
|
||||||
|
|
||||||
if(data.messageUpdates[keyStr]) {
|
if (data.messageUpdates[keyStr]) {
|
||||||
delete data.messageUpdates[keyStr]
|
delete data.messageUpdates[keyStr]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -437,14 +440,13 @@ function append<E extends BufferableEvent>(
|
|||||||
break
|
break
|
||||||
case 'messages.reaction':
|
case 'messages.reaction':
|
||||||
const reactions = eventData as BaileysEventMap['messages.reaction']
|
const reactions = eventData as BaileysEventMap['messages.reaction']
|
||||||
for(const { key, reaction } of reactions) {
|
for (const { key, reaction } of reactions) {
|
||||||
const keyStr = stringifyMessageKey(key)
|
const keyStr = stringifyMessageKey(key)
|
||||||
const existing = data.messageUpserts[keyStr]
|
const existing = data.messageUpserts[keyStr]
|
||||||
if(existing) {
|
if (existing) {
|
||||||
updateMessageWithReaction(existing.message, reaction)
|
updateMessageWithReaction(existing.message, reaction)
|
||||||
} else {
|
} else {
|
||||||
data.messageReactions[keyStr] = data.messageReactions[keyStr]
|
data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] }
|
||||||
|| { key, reactions: [] }
|
|
||||||
updateMessageWithReaction(data.messageReactions[keyStr], reaction)
|
updateMessageWithReaction(data.messageReactions[keyStr], reaction)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -452,14 +454,13 @@ function append<E extends BufferableEvent>(
|
|||||||
break
|
break
|
||||||
case 'message-receipt.update':
|
case 'message-receipt.update':
|
||||||
const receipts = eventData as BaileysEventMap['message-receipt.update']
|
const receipts = eventData as BaileysEventMap['message-receipt.update']
|
||||||
for(const { key, receipt } of receipts) {
|
for (const { key, receipt } of receipts) {
|
||||||
const keyStr = stringifyMessageKey(key)
|
const keyStr = stringifyMessageKey(key)
|
||||||
const existing = data.messageUpserts[keyStr]
|
const existing = data.messageUpserts[keyStr]
|
||||||
if(existing) {
|
if (existing) {
|
||||||
updateMessageWithReceipt(existing.message, receipt)
|
updateMessageWithReceipt(existing.message, receipt)
|
||||||
} else {
|
} else {
|
||||||
data.messageReceipts[keyStr] = data.messageReceipts[keyStr]
|
data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] }
|
||||||
|| { key, userReceipt: [] }
|
|
||||||
updateMessageWithReceipt(data.messageReceipts[keyStr], receipt)
|
updateMessageWithReceipt(data.messageReceipts[keyStr], receipt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -467,12 +468,11 @@ function append<E extends BufferableEvent>(
|
|||||||
break
|
break
|
||||||
case 'groups.update':
|
case 'groups.update':
|
||||||
const groupUpdates = eventData as BaileysEventMap['groups.update']
|
const groupUpdates = eventData as BaileysEventMap['groups.update']
|
||||||
for(const update of groupUpdates) {
|
for (const update of groupUpdates) {
|
||||||
const id = update.id!
|
const id = update.id!
|
||||||
const groupUpdate = data.groupUpdates[id] || { }
|
const groupUpdate = data.groupUpdates[id] || {}
|
||||||
if(!data.groupUpdates[id]) {
|
if (!data.groupUpdates[id]) {
|
||||||
data.groupUpdates[id] = Object.assign(groupUpdate, update)
|
data.groupUpdates[id] = Object.assign(groupUpdate, update)
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -484,14 +484,14 @@ function append<E extends BufferableEvent>(
|
|||||||
function absorbingChatUpdate(existing: Chat) {
|
function absorbingChatUpdate(existing: Chat) {
|
||||||
const chatId = existing.id
|
const chatId = existing.id
|
||||||
const update = data.chatUpdates[chatId]
|
const update = data.chatUpdates[chatId]
|
||||||
if(update) {
|
if (update) {
|
||||||
const conditionMatches = update.conditional ? update.conditional(data) : true
|
const conditionMatches = update.conditional ? update.conditional(data) : true
|
||||||
if(conditionMatches) {
|
if (conditionMatches) {
|
||||||
delete update.conditional
|
delete update.conditional
|
||||||
logger.debug({ chatId }, 'absorbed chat update in existing chat')
|
logger.debug({ chatId }, 'absorbed chat update in existing chat')
|
||||||
Object.assign(existing, concatChats(update as Chat, existing))
|
Object.assign(existing, concatChats(update as Chat, existing))
|
||||||
delete data.chatUpdates[chatId]
|
delete data.chatUpdates[chatId]
|
||||||
} else if(conditionMatches === false) {
|
} else if (conditionMatches === false) {
|
||||||
logger.debug({ chatId }, 'chat update condition fail, removing')
|
logger.debug({ chatId }, 'chat update condition fail, removing')
|
||||||
delete data.chatUpdates[chatId]
|
delete data.chatUpdates[chatId]
|
||||||
}
|
}
|
||||||
@@ -503,15 +503,15 @@ function append<E extends BufferableEvent>(
|
|||||||
// if the message has already been marked read by us
|
// if the message has already been marked read by us
|
||||||
const chatId = message.key.remoteJid!
|
const chatId = message.key.remoteJid!
|
||||||
const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId]
|
const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId]
|
||||||
if(
|
if (
|
||||||
isRealMessage(message, '')
|
isRealMessage(message, '') &&
|
||||||
&& shouldIncrementChatUnread(message)
|
shouldIncrementChatUnread(message) &&
|
||||||
&& typeof chat?.unreadCount === 'number'
|
typeof chat?.unreadCount === 'number' &&
|
||||||
&& chat.unreadCount > 0
|
chat.unreadCount > 0
|
||||||
) {
|
) {
|
||||||
logger.debug({ chatId: chat.id }, 'decrementing chat counter')
|
logger.debug({ chatId: chat.id }, 'decrementing chat counter')
|
||||||
chat.unreadCount -= 1
|
chat.unreadCount -= 1
|
||||||
if(chat.unreadCount === 0) {
|
if (chat.unreadCount === 0) {
|
||||||
delete chat.unreadCount
|
delete chat.unreadCount
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -519,9 +519,9 @@ function append<E extends BufferableEvent>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function consolidateEvents(data: BufferedEventData) {
|
function consolidateEvents(data: BufferedEventData) {
|
||||||
const map: BaileysEventData = { }
|
const map: BaileysEventData = {}
|
||||||
|
|
||||||
if(!data.historySets.empty) {
|
if (!data.historySets.empty) {
|
||||||
map['messaging-history.set'] = {
|
map['messaging-history.set'] = {
|
||||||
chats: Object.values(data.historySets.chats),
|
chats: Object.values(data.historySets.chats),
|
||||||
messages: Object.values(data.historySets.messages),
|
messages: Object.values(data.historySets.messages),
|
||||||
@@ -534,22 +534,22 @@ function consolidateEvents(data: BufferedEventData) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const chatUpsertList = Object.values(data.chatUpserts)
|
const chatUpsertList = Object.values(data.chatUpserts)
|
||||||
if(chatUpsertList.length) {
|
if (chatUpsertList.length) {
|
||||||
map['chats.upsert'] = chatUpsertList
|
map['chats.upsert'] = chatUpsertList
|
||||||
}
|
}
|
||||||
|
|
||||||
const chatUpdateList = Object.values(data.chatUpdates)
|
const chatUpdateList = Object.values(data.chatUpdates)
|
||||||
if(chatUpdateList.length) {
|
if (chatUpdateList.length) {
|
||||||
map['chats.update'] = chatUpdateList
|
map['chats.update'] = chatUpdateList
|
||||||
}
|
}
|
||||||
|
|
||||||
const chatDeleteList = Array.from(data.chatDeletes)
|
const chatDeleteList = Array.from(data.chatDeletes)
|
||||||
if(chatDeleteList.length) {
|
if (chatDeleteList.length) {
|
||||||
map['chats.delete'] = chatDeleteList
|
map['chats.delete'] = chatDeleteList
|
||||||
}
|
}
|
||||||
|
|
||||||
const messageUpsertList = Object.values(data.messageUpserts)
|
const messageUpsertList = Object.values(data.messageUpserts)
|
||||||
if(messageUpsertList.length) {
|
if (messageUpsertList.length) {
|
||||||
const type = messageUpsertList[0].type
|
const type = messageUpsertList[0].type
|
||||||
map['messages.upsert'] = {
|
map['messages.upsert'] = {
|
||||||
messages: messageUpsertList.map(m => m.message),
|
messages: messageUpsertList.map(m => m.message),
|
||||||
@@ -558,41 +558,41 @@ function consolidateEvents(data: BufferedEventData) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const messageUpdateList = Object.values(data.messageUpdates)
|
const messageUpdateList = Object.values(data.messageUpdates)
|
||||||
if(messageUpdateList.length) {
|
if (messageUpdateList.length) {
|
||||||
map['messages.update'] = messageUpdateList
|
map['messages.update'] = messageUpdateList
|
||||||
}
|
}
|
||||||
|
|
||||||
const messageDeleteList = Object.values(data.messageDeletes)
|
const messageDeleteList = Object.values(data.messageDeletes)
|
||||||
if(messageDeleteList.length) {
|
if (messageDeleteList.length) {
|
||||||
map['messages.delete'] = { keys: messageDeleteList }
|
map['messages.delete'] = { keys: messageDeleteList }
|
||||||
}
|
}
|
||||||
|
|
||||||
const messageReactionList = Object.values(data.messageReactions).flatMap(
|
const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) =>
|
||||||
({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction }))
|
reactions.flatMap(reaction => ({ key, reaction }))
|
||||||
)
|
)
|
||||||
if(messageReactionList.length) {
|
if (messageReactionList.length) {
|
||||||
map['messages.reaction'] = messageReactionList
|
map['messages.reaction'] = messageReactionList
|
||||||
}
|
}
|
||||||
|
|
||||||
const messageReceiptList = Object.values(data.messageReceipts).flatMap(
|
const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) =>
|
||||||
({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt }))
|
userReceipt.flatMap(receipt => ({ key, receipt }))
|
||||||
)
|
)
|
||||||
if(messageReceiptList.length) {
|
if (messageReceiptList.length) {
|
||||||
map['message-receipt.update'] = messageReceiptList
|
map['message-receipt.update'] = messageReceiptList
|
||||||
}
|
}
|
||||||
|
|
||||||
const contactUpsertList = Object.values(data.contactUpserts)
|
const contactUpsertList = Object.values(data.contactUpserts)
|
||||||
if(contactUpsertList.length) {
|
if (contactUpsertList.length) {
|
||||||
map['contacts.upsert'] = contactUpsertList
|
map['contacts.upsert'] = contactUpsertList
|
||||||
}
|
}
|
||||||
|
|
||||||
const contactUpdateList = Object.values(data.contactUpdates)
|
const contactUpdateList = Object.values(data.contactUpdates)
|
||||||
if(contactUpdateList.length) {
|
if (contactUpdateList.length) {
|
||||||
map['contacts.update'] = contactUpdateList
|
map['contacts.update'] = contactUpdateList
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupUpdateList = Object.values(data.groupUpdates)
|
const groupUpdateList = Object.values(data.groupUpdates)
|
||||||
if(groupUpdateList.length) {
|
if (groupUpdateList.length) {
|
||||||
map['groups.update'] = groupUpdateList
|
map['groups.update'] = groupUpdateList
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -600,15 +600,17 @@ function consolidateEvents(data: BufferedEventData) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function concatChats<C extends Partial<Chat>>(a: C, b: Partial<Chat>) {
|
function concatChats<C extends Partial<Chat>>(a: C, b: Partial<Chat>) {
|
||||||
if(b.unreadCount === null && // neutralize unread counter
|
if (
|
||||||
a.unreadCount! < 0) {
|
b.unreadCount === null && // neutralize unread counter
|
||||||
|
a.unreadCount! < 0
|
||||||
|
) {
|
||||||
a.unreadCount = undefined
|
a.unreadCount = undefined
|
||||||
b.unreadCount = undefined
|
b.unreadCount = undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
|
if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
|
||||||
b = { ...b }
|
b = { ...b }
|
||||||
if(b.unreadCount! >= 0) {
|
if (b.unreadCount! >= 0) {
|
||||||
b.unreadCount = Math.max(b.unreadCount!, 0) + Math.max(a.unreadCount, 0)
|
b.unreadCount = Math.max(b.unreadCount!, 0) + Math.max(a.unreadCount, 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,26 +4,34 @@ import { createHash, randomBytes } from 'crypto'
|
|||||||
import { platform, release } from 'os'
|
import { platform, release } from 'os'
|
||||||
import { proto } from '../../WAProto'
|
import { proto } from '../../WAProto'
|
||||||
import { version as baileysVersion } from '../Defaults/baileys-version.json'
|
import { version as baileysVersion } from '../Defaults/baileys-version.json'
|
||||||
import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, ConnectionState, DisconnectReason, WACallUpdateType, WAVersion } from '../Types'
|
import {
|
||||||
|
BaileysEventEmitter,
|
||||||
|
BaileysEventMap,
|
||||||
|
BrowsersMap,
|
||||||
|
ConnectionState,
|
||||||
|
DisconnectReason,
|
||||||
|
WACallUpdateType,
|
||||||
|
WAVersion
|
||||||
|
} from '../Types'
|
||||||
import { BinaryNode, getAllBinaryNodeChildren, jidDecode } from '../WABinary'
|
import { BinaryNode, getAllBinaryNodeChildren, jidDecode } from '../WABinary'
|
||||||
|
|
||||||
const PLATFORM_MAP = {
|
const PLATFORM_MAP = {
|
||||||
'aix': 'AIX',
|
aix: 'AIX',
|
||||||
'darwin': 'Mac OS',
|
darwin: 'Mac OS',
|
||||||
'win32': 'Windows',
|
win32: 'Windows',
|
||||||
'android': 'Android',
|
android: 'Android',
|
||||||
'freebsd': 'FreeBSD',
|
freebsd: 'FreeBSD',
|
||||||
'openbsd': 'OpenBSD',
|
openbsd: 'OpenBSD',
|
||||||
'sunos': 'Solaris'
|
sunos: 'Solaris'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Browsers: BrowsersMap = {
|
export const Browsers: BrowsersMap = {
|
||||||
ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
|
ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
|
||||||
macOS: (browser) => ['Mac OS', browser, '14.4.1'],
|
macOS: browser => ['Mac OS', browser, '14.4.1'],
|
||||||
baileys: (browser) => ['Baileys', browser, '6.5.0'],
|
baileys: browser => ['Baileys', browser, '6.5.0'],
|
||||||
windows: (browser) => ['Windows', browser, '10.0.22631'],
|
windows: browser => ['Windows', browser, '10.0.22631'],
|
||||||
/** The appropriate browser based on your OS & release */
|
/** The appropriate browser based on your OS & release */
|
||||||
appropriate: (browser) => [ PLATFORM_MAP[platform()] || 'Ubuntu', browser, release() ]
|
appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getPlatformId = (browser: string) => {
|
export const getPlatformId = (browser: string) => {
|
||||||
@@ -34,7 +42,7 @@ export const getPlatformId = (browser: string) => {
|
|||||||
export const BufferJSON = {
|
export const BufferJSON = {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
replacer: (k, value: any) => {
|
replacer: (k, value: any) => {
|
||||||
if(Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
|
if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
|
||||||
return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
|
return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +51,7 @@ export const BufferJSON = {
|
|||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
reviver: (_, value: any) => {
|
reviver: (_, value: any) => {
|
||||||
if(typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
|
if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
|
||||||
const val = value.data || value.value
|
const val = value.data || value.value
|
||||||
return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
|
return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
|
||||||
}
|
}
|
||||||
@@ -52,17 +60,13 @@ export const BufferJSON = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getKeyAuthor = (
|
export const getKeyAuthor = (key: proto.IMessageKey | undefined | null, meId = 'me') =>
|
||||||
key: proto.IMessageKey | undefined | null,
|
|
||||||
meId = 'me'
|
|
||||||
) => (
|
|
||||||
(key?.fromMe ? meId : key?.participant || key?.remoteJid) || ''
|
(key?.fromMe ? meId : key?.participant || key?.remoteJid) || ''
|
||||||
)
|
|
||||||
|
|
||||||
export const writeRandomPadMax16 = (msg: Uint8Array) => {
|
export const writeRandomPadMax16 = (msg: Uint8Array) => {
|
||||||
const pad = randomBytes(1)
|
const pad = randomBytes(1)
|
||||||
pad[0] &= 0xf
|
pad[0] &= 0xf
|
||||||
if(!pad[0]) {
|
if (!pad[0]) {
|
||||||
pad[0] = 0xf
|
pad[0] = 0xf
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,23 +75,19 @@ export const writeRandomPadMax16 = (msg: Uint8Array) => {
|
|||||||
|
|
||||||
export const unpadRandomMax16 = (e: Uint8Array | Buffer) => {
|
export const unpadRandomMax16 = (e: Uint8Array | Buffer) => {
|
||||||
const t = new Uint8Array(e)
|
const t = new Uint8Array(e)
|
||||||
if(0 === t.length) {
|
if (0 === t.length) {
|
||||||
throw new Error('unpadPkcs7 given empty bytes')
|
throw new Error('unpadPkcs7 given empty bytes')
|
||||||
}
|
}
|
||||||
|
|
||||||
var r = t[t.length - 1]
|
var r = t[t.length - 1]
|
||||||
if(r > t.length) {
|
if (r > t.length) {
|
||||||
throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
|
throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
|
return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const encodeWAMessage = (message: proto.IMessage) => (
|
export const encodeWAMessage = (message: proto.IMessage) => writeRandomPadMax16(proto.Message.encode(message).finish())
|
||||||
writeRandomPadMax16(
|
|
||||||
proto.Message.encode(message).finish()
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
export const generateRegistrationId = (): number => {
|
export const generateRegistrationId = (): number => {
|
||||||
return Uint16Array.from(randomBytes(2))[0] & 16383
|
return Uint16Array.from(randomBytes(2))[0] & 16383
|
||||||
@@ -96,7 +96,7 @@ export const generateRegistrationId = (): number => {
|
|||||||
export const encodeBigEndian = (e: number, t = 4) => {
|
export const encodeBigEndian = (e: number, t = 4) => {
|
||||||
let r = e
|
let r = e
|
||||||
const a = new Uint8Array(t)
|
const a = new Uint8Array(t)
|
||||||
for(let i = t - 1; i >= 0; i--) {
|
for (let i = t - 1; i >= 0; i--) {
|
||||||
a[i] = 255 & r
|
a[i] = 255 & r
|
||||||
r >>>= 8
|
r >>>= 8
|
||||||
}
|
}
|
||||||
@@ -104,7 +104,8 @@ export const encodeBigEndian = (e: number, t = 4) => {
|
|||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
|
|
||||||
export const toNumber = (t: Long | number | null | undefined): number => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : (t as Long).low) : t || 0)
|
export const toNumber = (t: Long | number | null | undefined): number =>
|
||||||
|
typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : (t as Long).low) : t || 0
|
||||||
|
|
||||||
/** unix timestamp of a date in seconds */
|
/** unix timestamp of a date in seconds */
|
||||||
export const unixTimestampSeconds = (date: Date = new Date()) => Math.floor(date.getTime() / 1000)
|
export const unixTimestampSeconds = (date: Date = new Date()) => Math.floor(date.getTime() / 1000)
|
||||||
@@ -124,12 +125,12 @@ export const debouncedTimeout = (intervalMs = 1000, task?: () => void) => {
|
|||||||
timeout && clearTimeout(timeout)
|
timeout && clearTimeout(timeout)
|
||||||
timeout = undefined
|
timeout = undefined
|
||||||
},
|
},
|
||||||
setTask: (newTask: () => void) => task = newTask,
|
setTask: (newTask: () => void) => (task = newTask),
|
||||||
setInterval: (newInterval: number) => intervalMs = newInterval
|
setInterval: (newInterval: number) => (intervalMs = newInterval)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const delay = (ms: number) => delayCancellable (ms).delay
|
export const delay = (ms: number) => delayCancellable(ms).delay
|
||||||
|
|
||||||
export const delayCancellable = (ms: number) => {
|
export const delayCancellable = (ms: number) => {
|
||||||
const stack = new Error().stack
|
const stack = new Error().stack
|
||||||
@@ -140,7 +141,7 @@ export const delayCancellable = (ms: number) => {
|
|||||||
reject = _reject
|
reject = _reject
|
||||||
})
|
})
|
||||||
const cancel = () => {
|
const cancel = () => {
|
||||||
clearTimeout (timeout)
|
clearTimeout(timeout)
|
||||||
reject(
|
reject(
|
||||||
new Boom('Cancelled', {
|
new Boom('Cancelled', {
|
||||||
statusCode: 500,
|
statusCode: 500,
|
||||||
@@ -154,29 +155,33 @@ export const delayCancellable = (ms: number) => {
|
|||||||
return { delay, cancel }
|
return { delay, cancel }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error) => void) => void) {
|
export async function promiseTimeout<T>(
|
||||||
if(!ms) {
|
ms: number | undefined,
|
||||||
|
promise: (resolve: (v: T) => void, reject: (error) => void) => void
|
||||||
|
) {
|
||||||
|
if (!ms) {
|
||||||
return new Promise(promise)
|
return new Promise(promise)
|
||||||
}
|
}
|
||||||
|
|
||||||
const stack = new Error().stack
|
const stack = new Error().stack
|
||||||
// Create a promise that rejects in <ms> milliseconds
|
// Create a promise that rejects in <ms> milliseconds
|
||||||
const { delay, cancel } = delayCancellable (ms)
|
const { delay, cancel } = delayCancellable(ms)
|
||||||
const p = new Promise((resolve, reject) => {
|
const p = new Promise((resolve, reject) => {
|
||||||
delay
|
delay
|
||||||
.then(() => reject(
|
.then(() =>
|
||||||
|
reject(
|
||||||
new Boom('Timed Out', {
|
new Boom('Timed Out', {
|
||||||
statusCode: DisconnectReason.timedOut,
|
statusCode: DisconnectReason.timedOut,
|
||||||
data: {
|
data: {
|
||||||
stack
|
stack
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
))
|
)
|
||||||
.catch (err => reject(err))
|
)
|
||||||
|
.catch(err => reject(err))
|
||||||
|
|
||||||
promise (resolve, reject)
|
promise(resolve, reject)
|
||||||
})
|
}).finally(cancel)
|
||||||
.finally (cancel)
|
|
||||||
return p as Promise<T>
|
return p as Promise<T>
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,9 +191,9 @@ export const generateMessageIDV2 = (userId?: string): string => {
|
|||||||
const data = Buffer.alloc(8 + 20 + 16)
|
const data = Buffer.alloc(8 + 20 + 16)
|
||||||
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
|
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
|
||||||
|
|
||||||
if(userId) {
|
if (userId) {
|
||||||
const id = jidDecode(userId)
|
const id = jidDecode(userId)
|
||||||
if(id?.user) {
|
if (id?.user) {
|
||||||
data.write(id.user, 8)
|
data.write(id.user, 8)
|
||||||
data.write('@c.us', 8 + id.user.length)
|
data.write('@c.us', 8 + id.user.length)
|
||||||
}
|
}
|
||||||
@@ -205,37 +210,30 @@ export const generateMessageIDV2 = (userId?: string): string => {
|
|||||||
export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase()
|
export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase()
|
||||||
|
|
||||||
export function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T) {
|
export function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T) {
|
||||||
return async(check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => {
|
return async (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => {
|
||||||
let listener: (item: BaileysEventMap[T]) => void
|
let listener: (item: BaileysEventMap[T]) => void
|
||||||
let closeListener: (state: Partial<ConnectionState>) => void
|
let closeListener: (state: Partial<ConnectionState>) => void
|
||||||
await (
|
await promiseTimeout<void>(timeoutMs, (resolve, reject) => {
|
||||||
promiseTimeout<void>(
|
|
||||||
timeoutMs,
|
|
||||||
(resolve, reject) => {
|
|
||||||
closeListener = ({ connection, lastDisconnect }) => {
|
closeListener = ({ connection, lastDisconnect }) => {
|
||||||
if(connection === 'close') {
|
if (connection === 'close') {
|
||||||
reject(
|
reject(
|
||||||
lastDisconnect?.error
|
lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
||||||
|| new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ev.on('connection.update', closeListener)
|
ev.on('connection.update', closeListener)
|
||||||
listener = async(update) => {
|
listener = async update => {
|
||||||
if(await check(update)) {
|
if (await check(update)) {
|
||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ev.on(event, listener)
|
ev.on(event, listener)
|
||||||
}
|
}).finally(() => {
|
||||||
)
|
|
||||||
.finally(() => {
|
|
||||||
ev.off(event, listener)
|
ev.off(event, listener)
|
||||||
ev.off('connection.update', closeListener)
|
ev.off('connection.update', closeListener)
|
||||||
})
|
})
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,21 +243,18 @@ export const bindWaitForConnectionUpdate = (ev: BaileysEventEmitter) => bindWait
|
|||||||
* utility that fetches latest baileys version from the master branch.
|
* utility that fetches latest baileys version from the master branch.
|
||||||
* Use to ensure your WA connection is always on the latest version
|
* Use to ensure your WA connection is always on the latest version
|
||||||
*/
|
*/
|
||||||
export const fetchLatestBaileysVersion = async(options: AxiosRequestConfig<{}> = { }) => {
|
export const fetchLatestBaileysVersion = async (options: AxiosRequestConfig<{}> = {}) => {
|
||||||
const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json'
|
const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json'
|
||||||
try {
|
try {
|
||||||
const result = await axios.get<{ version: WAVersion }>(
|
const result = await axios.get<{ version: WAVersion }>(URL, {
|
||||||
URL,
|
|
||||||
{
|
|
||||||
...options,
|
...options,
|
||||||
responseType: 'json'
|
responseType: 'json'
|
||||||
}
|
})
|
||||||
)
|
|
||||||
return {
|
return {
|
||||||
version: result.data.version,
|
version: result.data.version,
|
||||||
isLatest: true
|
isLatest: true
|
||||||
}
|
}
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
return {
|
return {
|
||||||
version: baileysVersion as WAVersion,
|
version: baileysVersion as WAVersion,
|
||||||
isLatest: false,
|
isLatest: false,
|
||||||
@@ -272,20 +267,17 @@ export const fetchLatestBaileysVersion = async(options: AxiosRequestConfig<{}> =
|
|||||||
* A utility that fetches the latest web version of whatsapp.
|
* A utility that fetches the latest web version of whatsapp.
|
||||||
* Use to ensure your WA connection is always on the latest version
|
* Use to ensure your WA connection is always on the latest version
|
||||||
*/
|
*/
|
||||||
export const fetchLatestWaWebVersion = async(options: AxiosRequestConfig<{}>) => {
|
export const fetchLatestWaWebVersion = async (options: AxiosRequestConfig<{}>) => {
|
||||||
try {
|
try {
|
||||||
const { data } = await axios.get(
|
const { data } = await axios.get('https://web.whatsapp.com/sw.js', {
|
||||||
'https://web.whatsapp.com/sw.js',
|
|
||||||
{
|
|
||||||
...options,
|
...options,
|
||||||
responseType: 'json'
|
responseType: 'json'
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
const regex = /\\?"client_revision\\?":\s*(\d+)/
|
const regex = /\\?"client_revision\\?":\s*(\d+)/
|
||||||
const match = data.match(regex)
|
const match = data.match(regex)
|
||||||
|
|
||||||
if(!match?.[1]) {
|
if (!match?.[1]) {
|
||||||
return {
|
return {
|
||||||
version: baileysVersion as WAVersion,
|
version: baileysVersion as WAVersion,
|
||||||
isLatest: false,
|
isLatest: false,
|
||||||
@@ -301,7 +293,7 @@ export const fetchLatestWaWebVersion = async(options: AxiosRequestConfig<{}>) =>
|
|||||||
version: [2, 3000, +clientRevision] as WAVersion,
|
version: [2, 3000, +clientRevision] as WAVersion,
|
||||||
isLatest: true
|
isLatest: true
|
||||||
}
|
}
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
return {
|
return {
|
||||||
version: baileysVersion as WAVersion,
|
version: baileysVersion as WAVersion,
|
||||||
isLatest: false,
|
isLatest: false,
|
||||||
@@ -317,9 +309,9 @@ export const generateMdTagPrefix = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const STATUS_MAP: { [_: string]: proto.WebMessageInfo.Status } = {
|
const STATUS_MAP: { [_: string]: proto.WebMessageInfo.Status } = {
|
||||||
'sender': proto.WebMessageInfo.Status.SERVER_ACK,
|
sender: proto.WebMessageInfo.Status.SERVER_ACK,
|
||||||
'played': proto.WebMessageInfo.Status.PLAYED,
|
played: proto.WebMessageInfo.Status.PLAYED,
|
||||||
'read': proto.WebMessageInfo.Status.READ,
|
read: proto.WebMessageInfo.Status.READ,
|
||||||
'read-self': proto.WebMessageInfo.Status.READ
|
'read-self': proto.WebMessageInfo.Status.READ
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -328,7 +320,7 @@ const STATUS_MAP: { [_: string]: proto.WebMessageInfo.Status } = {
|
|||||||
*/
|
*/
|
||||||
export const getStatusFromReceiptType = (type: string | undefined) => {
|
export const getStatusFromReceiptType = (type: string | undefined) => {
|
||||||
const status = STATUS_MAP[type!]
|
const status = STATUS_MAP[type!]
|
||||||
if(typeof type === 'undefined') {
|
if (typeof type === 'undefined') {
|
||||||
return proto.WebMessageInfo.Status.DELIVERY_ACK
|
return proto.WebMessageInfo.Status.DELIVERY_ACK
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -348,7 +340,7 @@ export const getErrorCodeFromStreamError = (node: BinaryNode) => {
|
|||||||
let reason = reasonNode?.tag || 'unknown'
|
let reason = reasonNode?.tag || 'unknown'
|
||||||
const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession)
|
const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession)
|
||||||
|
|
||||||
if(statusCode === DisconnectReason.restartRequired) {
|
if (statusCode === DisconnectReason.restartRequired) {
|
||||||
reason = 'restart required'
|
reason = 'restart required'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -366,7 +358,7 @@ export const getCallStatusFromNode = ({ tag, attrs }: BinaryNode) => {
|
|||||||
status = 'offer'
|
status = 'offer'
|
||||||
break
|
break
|
||||||
case 'terminate':
|
case 'terminate':
|
||||||
if(attrs.reason === 'timeout') {
|
if (attrs.reason === 'timeout') {
|
||||||
status = 'timeout'
|
status = 'timeout'
|
||||||
} else {
|
} else {
|
||||||
//fired when accepted/rejected/timeout/caller hangs up
|
//fired when accepted/rejected/timeout/caller hangs up
|
||||||
@@ -392,16 +384,17 @@ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
|
|||||||
|
|
||||||
export const getCodeFromWSError = (error: Error) => {
|
export const getCodeFromWSError = (error: Error) => {
|
||||||
let statusCode = 500
|
let statusCode = 500
|
||||||
if(error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
|
if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
|
||||||
const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length)
|
const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length)
|
||||||
if(!Number.isNaN(code) && code >= 400) {
|
if (!Number.isNaN(code) && code >= 400) {
|
||||||
statusCode = code
|
statusCode = code
|
||||||
}
|
}
|
||||||
} else if(
|
} else if (
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
(error as any)?.code?.startsWith('E')
|
(error as any)?.code?.startsWith('E') ||
|
||||||
|| error?.message?.includes('timed out')
|
error?.message?.includes('timed out')
|
||||||
) { // handle ETIMEOUT, ENOTFOUND etc
|
) {
|
||||||
|
// handle ETIMEOUT, ENOTFOUND etc
|
||||||
statusCode = 408
|
statusCode = 408
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -417,9 +410,9 @@ export const isWABusinessPlatform = (platform: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
export function trimUndefined(obj: {[_: string]: any}) {
|
export function trimUndefined(obj: { [_: string]: any }) {
|
||||||
for(const key in obj) {
|
for (const key in obj) {
|
||||||
if(typeof obj[key] === 'undefined') {
|
if (typeof obj[key] === 'undefined') {
|
||||||
delete obj[key]
|
delete obj[key]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -434,17 +427,17 @@ export function bytesToCrockford(buffer: Buffer): string {
|
|||||||
let bitCount = 0
|
let bitCount = 0
|
||||||
const crockford: string[] = []
|
const crockford: string[] = []
|
||||||
|
|
||||||
for(const element of buffer) {
|
for (const element of buffer) {
|
||||||
value = (value << 8) | (element & 0xff)
|
value = (value << 8) | (element & 0xff)
|
||||||
bitCount += 8
|
bitCount += 8
|
||||||
|
|
||||||
while(bitCount >= 5) {
|
while (bitCount >= 5) {
|
||||||
crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
|
crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
|
||||||
bitCount -= 5
|
bitCount -= 5
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(bitCount > 0) {
|
if (bitCount > 0) {
|
||||||
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
|
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,10 +10,7 @@ import { downloadContentFromMessage } from './messages-media'
|
|||||||
|
|
||||||
const inflatePromise = promisify(inflate)
|
const inflatePromise = promisify(inflate)
|
||||||
|
|
||||||
export const downloadHistory = async(
|
export const downloadHistory = async (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => {
|
||||||
msg: proto.Message.IHistorySyncNotification,
|
|
||||||
options: AxiosRequestConfig<{}>
|
|
||||||
) => {
|
|
||||||
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
||||||
const bufferArray: Buffer[] = []
|
const bufferArray: Buffer[] = []
|
||||||
for await (const chunk of stream) {
|
for await (const chunk of stream) {
|
||||||
@@ -39,7 +36,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
|
|||||||
case proto.HistorySync.HistorySyncType.RECENT:
|
case proto.HistorySync.HistorySyncType.RECENT:
|
||||||
case proto.HistorySync.HistorySyncType.FULL:
|
case proto.HistorySync.HistorySyncType.FULL:
|
||||||
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
||||||
for(const chat of item.conversations! as Chat[]) {
|
for (const chat of item.conversations! as Chat[]) {
|
||||||
contacts.push({ id: chat.id, name: chat.name || undefined })
|
contacts.push({ id: chat.id, name: chat.name || undefined })
|
||||||
|
|
||||||
const msgs = chat.messages || []
|
const msgs = chat.messages || []
|
||||||
@@ -48,33 +45,32 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
|
|||||||
delete chat.muteEndTime
|
delete chat.muteEndTime
|
||||||
delete chat.pinned
|
delete chat.pinned
|
||||||
|
|
||||||
for(const item of msgs) {
|
for (const item of msgs) {
|
||||||
const message = item.message!
|
const message = item.message!
|
||||||
messages.push(message)
|
messages.push(message)
|
||||||
|
|
||||||
if(!chat.messages?.length) {
|
if (!chat.messages?.length) {
|
||||||
// keep only the most recent message in the chat array
|
// keep only the most recent message in the chat array
|
||||||
chat.messages = [{ message }]
|
chat.messages = [{ message }]
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
||||||
chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
|
chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(
|
if (
|
||||||
(message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
|
(message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
|
||||||
|| message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB
|
message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
|
||||||
)
|
message.messageStubParameters?.[0]
|
||||||
&& message.messageStubParameters?.[0]
|
|
||||||
) {
|
) {
|
||||||
contacts.push({
|
contacts.push({
|
||||||
id: message.key.participant || message.key.remoteJid!,
|
id: message.key.participant || message.key.remoteJid!,
|
||||||
verifiedName: message.messageStubParameters?.[0],
|
verifiedName: message.messageStubParameters?.[0]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(isJidUser(chat.id) && chat.readOnly && chat.archived) {
|
if (isJidUser(chat.id) && chat.readOnly && chat.archived) {
|
||||||
delete chat.readOnly
|
delete chat.readOnly
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,7 +79,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
|
|||||||
|
|
||||||
break
|
break
|
||||||
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
||||||
for(const c of item.pushnames!) {
|
for (const c of item.pushnames!) {
|
||||||
contacts.push({ id: c.id!, notify: c.pushname! })
|
contacts.push({ id: c.id!, notify: c.pushname! })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +95,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const downloadAndProcessHistorySyncNotification = async(
|
export const downloadAndProcessHistorySyncNotification = async (
|
||||||
msg: proto.Message.IHistorySyncNotification,
|
msg: proto.Message.IHistorySyncNotification,
|
||||||
options: AxiosRequestConfig<{}>
|
options: AxiosRequestConfig<{}>
|
||||||
) => {
|
) => {
|
||||||
|
|||||||
@@ -7,10 +7,7 @@ import { extractImageThumb, getHttpStream } from './messages-media'
|
|||||||
const THUMBNAIL_WIDTH_PX = 192
|
const THUMBNAIL_WIDTH_PX = 192
|
||||||
|
|
||||||
/** Fetches an image and generates a thumbnail for it */
|
/** Fetches an image and generates a thumbnail for it */
|
||||||
const getCompressedJpegThumbnail = async(
|
const getCompressedJpegThumbnail = async (url: string, { thumbnailWidth, fetchOpts }: URLGenerationOptions) => {
|
||||||
url: string,
|
|
||||||
{ thumbnailWidth, fetchOpts }: URLGenerationOptions
|
|
||||||
) => {
|
|
||||||
const stream = await getHttpStream(url, fetchOpts)
|
const stream = await getHttpStream(url, fetchOpts)
|
||||||
const result = await extractImageThumb(stream, thumbnailWidth)
|
const result = await extractImageThumb(stream, thumbnailWidth)
|
||||||
return result
|
return result
|
||||||
@@ -34,12 +31,12 @@ export type URLGenerationOptions = {
|
|||||||
* @param text first matched URL in text
|
* @param text first matched URL in text
|
||||||
* @returns the URL info required to generate link preview
|
* @returns the URL info required to generate link preview
|
||||||
*/
|
*/
|
||||||
export const getUrlInfo = async(
|
export const getUrlInfo = async (
|
||||||
text: string,
|
text: string,
|
||||||
opts: URLGenerationOptions = {
|
opts: URLGenerationOptions = {
|
||||||
thumbnailWidth: THUMBNAIL_WIDTH_PX,
|
thumbnailWidth: THUMBNAIL_WIDTH_PX,
|
||||||
fetchOpts: { timeout: 3000 }
|
fetchOpts: { timeout: 3000 }
|
||||||
},
|
}
|
||||||
): Promise<WAUrlInfo | undefined> => {
|
): Promise<WAUrlInfo | undefined> => {
|
||||||
try {
|
try {
|
||||||
// retries
|
// retries
|
||||||
@@ -48,7 +45,7 @@ export const getUrlInfo = async(
|
|||||||
|
|
||||||
const { getLinkPreview } = await import('link-preview-js')
|
const { getLinkPreview } = await import('link-preview-js')
|
||||||
let previewLink = text
|
let previewLink = text
|
||||||
if(!text.startsWith('https://') && !text.startsWith('http://')) {
|
if (!text.startsWith('https://') && !text.startsWith('http://')) {
|
||||||
previewLink = 'https://' + previewLink
|
previewLink = 'https://' + previewLink
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,14 +55,14 @@ export const getUrlInfo = async(
|
|||||||
handleRedirects: (baseURL: string, forwardedURL: string) => {
|
handleRedirects: (baseURL: string, forwardedURL: string) => {
|
||||||
const urlObj = new URL(baseURL)
|
const urlObj = new URL(baseURL)
|
||||||
const forwardedURLObj = new URL(forwardedURL)
|
const forwardedURLObj = new URL(forwardedURL)
|
||||||
if(retries >= maxRetry) {
|
if (retries >= maxRetry) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if(
|
if (
|
||||||
forwardedURLObj.hostname === urlObj.hostname
|
forwardedURLObj.hostname === urlObj.hostname ||
|
||||||
|| forwardedURLObj.hostname === 'www.' + urlObj.hostname
|
forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
|
||||||
|| 'www.' + forwardedURLObj.hostname === urlObj.hostname
|
'www.' + forwardedURLObj.hostname === urlObj.hostname
|
||||||
) {
|
) {
|
||||||
retries + 1
|
retries + 1
|
||||||
return true
|
return true
|
||||||
@@ -75,7 +72,7 @@ export const getUrlInfo = async(
|
|||||||
},
|
},
|
||||||
headers: opts.fetchOpts as {}
|
headers: opts.fetchOpts as {}
|
||||||
})
|
})
|
||||||
if(info && 'title' in info && info.title) {
|
if (info && 'title' in info && info.title) {
|
||||||
const [image] = info.images
|
const [image] = info.images
|
||||||
|
|
||||||
const urlInfo: WAUrlInfo = {
|
const urlInfo: WAUrlInfo = {
|
||||||
@@ -86,7 +83,7 @@ export const getUrlInfo = async(
|
|||||||
originalThumbnailUrl: image
|
originalThumbnailUrl: image
|
||||||
}
|
}
|
||||||
|
|
||||||
if(opts.uploadImage) {
|
if (opts.uploadImage) {
|
||||||
const { imageMessage } = await prepareWAMessageMedia(
|
const { imageMessage } = await prepareWAMessageMedia(
|
||||||
{ image: { url: image } },
|
{ image: { url: image } },
|
||||||
{
|
{
|
||||||
@@ -95,27 +92,20 @@ export const getUrlInfo = async(
|
|||||||
options: opts.fetchOpts
|
options: opts.fetchOpts
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail
|
urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined
|
||||||
? Buffer.from(imageMessage.jpegThumbnail)
|
|
||||||
: undefined
|
|
||||||
urlInfo.highQualityThumbnail = imageMessage || undefined
|
urlInfo.highQualityThumbnail = imageMessage || undefined
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
urlInfo.jpegThumbnail = image
|
urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined
|
||||||
? (await getCompressedJpegThumbnail(image, opts)).buffer
|
} catch (error) {
|
||||||
: undefined
|
opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail')
|
||||||
} catch(error) {
|
|
||||||
opts.logger?.debug(
|
|
||||||
{ err: error.stack, url: previewLink },
|
|
||||||
'error in generating thumbnail'
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return urlInfo
|
return urlInfo
|
||||||
}
|
}
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
if(!error.message.includes('receive a valid')) {
|
if (!error.message.includes('receive a valid')) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { hkdf } from './crypto'
|
|||||||
const o = 128
|
const o = 128
|
||||||
|
|
||||||
class d {
|
class d {
|
||||||
|
|
||||||
salt: string
|
salt: string
|
||||||
|
|
||||||
constructor(e: string) {
|
constructor(e: string) {
|
||||||
@@ -17,7 +16,7 @@ class d {
|
|||||||
}
|
}
|
||||||
add(e, t) {
|
add(e, t) {
|
||||||
var r = this
|
var r = this
|
||||||
for(const item of t) {
|
for (const item of t) {
|
||||||
e = r._addSingle(e, item)
|
e = r._addSingle(e, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,7 +24,7 @@ class d {
|
|||||||
}
|
}
|
||||||
subtract(e, t) {
|
subtract(e, t) {
|
||||||
var r = this
|
var r = this
|
||||||
for(const item of t) {
|
for (const item of t) {
|
||||||
e = r._subtractSingle(e, item)
|
e = r._subtractSingle(e, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,20 +37,20 @@ class d {
|
|||||||
async _addSingle(e, t) {
|
async _addSingle(e, t) {
|
||||||
var r = this
|
var r = this
|
||||||
const n = new Uint8Array(await hkdf(Buffer.from(t), o, { info: r.salt })).buffer
|
const n = new Uint8Array(await hkdf(Buffer.from(t), o, { info: r.salt })).buffer
|
||||||
return r.performPointwiseWithOverflow(await e, n, ((e, t) => e + t))
|
return r.performPointwiseWithOverflow(await e, n, (e, t) => e + t)
|
||||||
}
|
}
|
||||||
async _subtractSingle(e, t) {
|
async _subtractSingle(e, t) {
|
||||||
var r = this
|
var r = this
|
||||||
|
|
||||||
const n = new Uint8Array(await hkdf(Buffer.from(t), o, { info: r.salt })).buffer
|
const n = new Uint8Array(await hkdf(Buffer.from(t), o, { info: r.salt })).buffer
|
||||||
return r.performPointwiseWithOverflow(await e, n, ((e, t) => e - t))
|
return r.performPointwiseWithOverflow(await e, n, (e, t) => e - t)
|
||||||
}
|
}
|
||||||
performPointwiseWithOverflow(e, t, r) {
|
performPointwiseWithOverflow(e, t, r) {
|
||||||
const n = new DataView(e)
|
const n = new DataView(e),
|
||||||
, i = new DataView(t)
|
i = new DataView(t),
|
||||||
, a = new ArrayBuffer(n.byteLength)
|
a = new ArrayBuffer(n.byteLength),
|
||||||
, s = new DataView(a)
|
s = new DataView(a)
|
||||||
for(let e = 0; e < n.byteLength; e += 2) {
|
for (let e = 0; e < n.byteLength; e += 2) {
|
||||||
s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0)
|
s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ export const makeMutex = () => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
mutex<T>(code: () => Promise<T> | T): Promise<T> {
|
mutex<T>(code: () => Promise<T> | T): Promise<T> {
|
||||||
task = (async() => {
|
task = (async () => {
|
||||||
// wait for the previous task to complete
|
// wait for the previous task to complete
|
||||||
// if there is an error, we swallow so as to not block the queue
|
// if there is an error, we swallow so as to not block the queue
|
||||||
try {
|
try {
|
||||||
await task
|
await task
|
||||||
} catch{ }
|
} catch {}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// execute the current task
|
// execute the current task
|
||||||
@@ -24,7 +24,7 @@ export const makeMutex = () => {
|
|||||||
// we replace the existing task, appending the new piece of execution to it
|
// we replace the existing task, appending the new piece of execution to it
|
||||||
// so the next task will have to wait for this one to finish
|
// so the next task will have to wait for this one to finish
|
||||||
return task
|
return task
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ export const makeKeyedMutex = () => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
mutex<T>(key: string, task: () => Promise<T> | T): Promise<T> {
|
mutex<T>(key: string, task: () => Promise<T> | T): Promise<T> {
|
||||||
if(!map[key]) {
|
if (!map[key]) {
|
||||||
map[key] = makeMutex()
|
map[key] = makeMutex()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,20 @@ import { Readable, Transform } from 'stream'
|
|||||||
import { URL } from 'url'
|
import { URL } from 'url'
|
||||||
import { proto } from '../../WAProto'
|
import { proto } from '../../WAProto'
|
||||||
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults'
|
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults'
|
||||||
import { BaileysEventMap, DownloadableMessage, MediaConnInfo, MediaDecryptionKeyInfo, MediaType, MessageType, SocketConfig, WAGenericMediaMessage, WAMediaPayloadURL, WAMediaUpload, WAMediaUploadFunction, WAMessageContent } from '../Types'
|
import {
|
||||||
|
BaileysEventMap,
|
||||||
|
DownloadableMessage,
|
||||||
|
MediaConnInfo,
|
||||||
|
MediaDecryptionKeyInfo,
|
||||||
|
MediaType,
|
||||||
|
MessageType,
|
||||||
|
SocketConfig,
|
||||||
|
WAGenericMediaMessage,
|
||||||
|
WAMediaPayloadURL,
|
||||||
|
WAMediaUpload,
|
||||||
|
WAMediaUploadFunction,
|
||||||
|
WAMessageContent
|
||||||
|
} from '../Types'
|
||||||
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
|
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
|
||||||
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
|
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
|
||||||
import { generateMessageIDV2 } from './generics'
|
import { generateMessageIDV2 } from './generics'
|
||||||
@@ -19,30 +32,24 @@ import { ILogger } from './logger'
|
|||||||
|
|
||||||
const getTmpFilesDirectory = () => tmpdir()
|
const getTmpFilesDirectory = () => tmpdir()
|
||||||
|
|
||||||
const getImageProcessingLibrary = async() => {
|
const getImageProcessingLibrary = async () => {
|
||||||
const [_jimp, sharp] = await Promise.all([
|
const [_jimp, sharp] = await Promise.all([
|
||||||
(async() => {
|
(async () => {
|
||||||
const jimp = await (
|
const jimp = await import('jimp').catch(() => {})
|
||||||
import('jimp')
|
|
||||||
.catch(() => { })
|
|
||||||
)
|
|
||||||
return jimp
|
return jimp
|
||||||
})(),
|
})(),
|
||||||
(async() => {
|
(async () => {
|
||||||
const sharp = await (
|
const sharp = await import('sharp').catch(() => {})
|
||||||
import('sharp')
|
|
||||||
.catch(() => { })
|
|
||||||
)
|
|
||||||
return sharp
|
return sharp
|
||||||
})()
|
})()
|
||||||
])
|
])
|
||||||
|
|
||||||
if(sharp) {
|
if (sharp) {
|
||||||
return { sharp }
|
return { sharp }
|
||||||
}
|
}
|
||||||
|
|
||||||
const jimp = _jimp?.default || _jimp
|
const jimp = _jimp?.default || _jimp
|
||||||
if(jimp) {
|
if (jimp) {
|
||||||
return { jimp }
|
return { jimp }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,12 +62,15 @@ export const hkdfInfoKey = (type: MediaType) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** generates all the keys required to encrypt/decrypt & sign a media message */
|
/** generates all the keys required to encrypt/decrypt & sign a media message */
|
||||||
export async function getMediaKeys(buffer: Uint8Array | string | null | undefined, mediaType: MediaType): Promise<MediaDecryptionKeyInfo> {
|
export async function getMediaKeys(
|
||||||
if(!buffer) {
|
buffer: Uint8Array | string | null | undefined,
|
||||||
|
mediaType: MediaType
|
||||||
|
): Promise<MediaDecryptionKeyInfo> {
|
||||||
|
if (!buffer) {
|
||||||
throw new Boom('Cannot derive from empty media key')
|
throw new Boom('Cannot derive from empty media key')
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof buffer === 'string') {
|
if (typeof buffer === 'string') {
|
||||||
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64')
|
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,49 +79,47 @@ export async function getMediaKeys(buffer: Uint8Array | string | null | undefine
|
|||||||
return {
|
return {
|
||||||
iv: expandedMediaKey.slice(0, 16),
|
iv: expandedMediaKey.slice(0, 16),
|
||||||
cipherKey: expandedMediaKey.slice(16, 48),
|
cipherKey: expandedMediaKey.slice(16, 48),
|
||||||
macKey: expandedMediaKey.slice(48, 80),
|
macKey: expandedMediaKey.slice(48, 80)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Extracts video thumb using FFMPEG */
|
/** Extracts video thumb using FFMPEG */
|
||||||
const extractVideoThumb = async(
|
const extractVideoThumb = async (
|
||||||
path: string,
|
path: string,
|
||||||
destPath: string,
|
destPath: string,
|
||||||
time: string,
|
time: string,
|
||||||
size: { width: number, height: number },
|
size: { width: number; height: number }
|
||||||
) => new Promise<void>((resolve, reject) => {
|
) =>
|
||||||
|
new Promise<void>((resolve, reject) => {
|
||||||
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`
|
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`
|
||||||
exec(cmd, (err) => {
|
exec(cmd, err => {
|
||||||
if(err) {
|
if (err) {
|
||||||
reject(err)
|
reject(err)
|
||||||
} else {
|
} else {
|
||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | string, width = 32) => {
|
export const extractImageThumb = async (bufferOrFilePath: Readable | Buffer | string, width = 32) => {
|
||||||
if(bufferOrFilePath instanceof Readable) {
|
if (bufferOrFilePath instanceof Readable) {
|
||||||
bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
const lib = await getImageProcessingLibrary()
|
const lib = await getImageProcessingLibrary()
|
||||||
if('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
||||||
const img = lib.sharp.default(bufferOrFilePath)
|
const img = lib.sharp.default(bufferOrFilePath)
|
||||||
const dimensions = await img.metadata()
|
const dimensions = await img.metadata()
|
||||||
|
|
||||||
const buffer = await img
|
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer()
|
||||||
.resize(width)
|
|
||||||
.jpeg({ quality: 50 })
|
|
||||||
.toBuffer()
|
|
||||||
return {
|
return {
|
||||||
buffer,
|
buffer,
|
||||||
original: {
|
original: {
|
||||||
width: dimensions.width,
|
width: dimensions.width,
|
||||||
height: dimensions.height,
|
height: dimensions.height
|
||||||
},
|
|
||||||
}
|
}
|
||||||
} else if('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
}
|
||||||
|
} else if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
||||||
const { read, MIME_JPEG, RESIZE_BILINEAR, AUTO } = lib.jimp
|
const { read, MIME_JPEG, RESIZE_BILINEAR, AUTO } = lib.jimp
|
||||||
|
|
||||||
const jimp = await read(bufferOrFilePath as string)
|
const jimp = await read(bufferOrFilePath as string)
|
||||||
@@ -119,10 +127,7 @@ export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | str
|
|||||||
width: jimp.getWidth(),
|
width: jimp.getWidth(),
|
||||||
height: jimp.getHeight()
|
height: jimp.getHeight()
|
||||||
}
|
}
|
||||||
const buffer = await jimp
|
const buffer = await jimp.quality(50).resize(width, AUTO, RESIZE_BILINEAR).getBufferAsync(MIME_JPEG)
|
||||||
.quality(50)
|
|
||||||
.resize(width, AUTO, RESIZE_BILINEAR)
|
|
||||||
.getBufferAsync(MIME_JPEG)
|
|
||||||
return {
|
return {
|
||||||
buffer,
|
buffer,
|
||||||
original: dimensions
|
original: dimensions
|
||||||
@@ -132,20 +137,14 @@ export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | str
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const encodeBase64EncodedStringForUpload = (b64: string) => (
|
export const encodeBase64EncodedStringForUpload = (b64: string) =>
|
||||||
encodeURIComponent(
|
encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''))
|
||||||
b64
|
|
||||||
.replace(/\+/g, '-')
|
|
||||||
.replace(/\//g, '_')
|
|
||||||
.replace(/\=+$/, '')
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
export const generateProfilePicture = async(mediaUpload: WAMediaUpload) => {
|
export const generateProfilePicture = async (mediaUpload: WAMediaUpload) => {
|
||||||
let bufferOrFilePath: Buffer | string
|
let bufferOrFilePath: Buffer | string
|
||||||
if(Buffer.isBuffer(mediaUpload)) {
|
if (Buffer.isBuffer(mediaUpload)) {
|
||||||
bufferOrFilePath = mediaUpload
|
bufferOrFilePath = mediaUpload
|
||||||
} else if('url' in mediaUpload) {
|
} else if ('url' in mediaUpload) {
|
||||||
bufferOrFilePath = mediaUpload.url.toString()
|
bufferOrFilePath = mediaUpload.url.toString()
|
||||||
} else {
|
} else {
|
||||||
bufferOrFilePath = await toBuffer(mediaUpload.stream)
|
bufferOrFilePath = await toBuffer(mediaUpload.stream)
|
||||||
@@ -153,44 +152,42 @@ export const generateProfilePicture = async(mediaUpload: WAMediaUpload) => {
|
|||||||
|
|
||||||
const lib = await getImageProcessingLibrary()
|
const lib = await getImageProcessingLibrary()
|
||||||
let img: Promise<Buffer>
|
let img: Promise<Buffer>
|
||||||
if('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
||||||
img = lib.sharp.default(bufferOrFilePath)
|
img = lib.sharp
|
||||||
|
.default(bufferOrFilePath)
|
||||||
.resize(640, 640)
|
.resize(640, 640)
|
||||||
.jpeg({
|
.jpeg({
|
||||||
quality: 50,
|
quality: 50
|
||||||
})
|
})
|
||||||
.toBuffer()
|
.toBuffer()
|
||||||
} else if('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
} else if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
||||||
const { read, MIME_JPEG, RESIZE_BILINEAR } = lib.jimp
|
const { read, MIME_JPEG, RESIZE_BILINEAR } = lib.jimp
|
||||||
const jimp = await read(bufferOrFilePath as string)
|
const jimp = await read(bufferOrFilePath as string)
|
||||||
const min = Math.min(jimp.getWidth(), jimp.getHeight())
|
const min = Math.min(jimp.getWidth(), jimp.getHeight())
|
||||||
const cropped = jimp.crop(0, 0, min, min)
|
const cropped = jimp.crop(0, 0, min, min)
|
||||||
|
|
||||||
img = cropped
|
img = cropped.quality(50).resize(640, 640, RESIZE_BILINEAR).getBufferAsync(MIME_JPEG)
|
||||||
.quality(50)
|
|
||||||
.resize(640, 640, RESIZE_BILINEAR)
|
|
||||||
.getBufferAsync(MIME_JPEG)
|
|
||||||
} else {
|
} else {
|
||||||
throw new Boom('No image processing library available')
|
throw new Boom('No image processing library available')
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
img: await img,
|
img: await img
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** gets the SHA256 of the given media message */
|
/** gets the SHA256 of the given media message */
|
||||||
export const mediaMessageSHA256B64 = (message: WAMessageContent) => {
|
export const mediaMessageSHA256B64 = (message: WAMessageContent) => {
|
||||||
const media = Object.values(message)[0] as WAGenericMediaMessage
|
const media = Object.values(message)[0] as WAGenericMediaMessage
|
||||||
return media?.fileSha256 && Buffer.from(media.fileSha256).toString ('base64')
|
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64')
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAudioDuration(buffer: Buffer | string | Readable) {
|
export async function getAudioDuration(buffer: Buffer | string | Readable) {
|
||||||
const musicMetadata = await import('music-metadata')
|
const musicMetadata = await import('music-metadata')
|
||||||
let metadata: IAudioMetadata
|
let metadata: IAudioMetadata
|
||||||
if(Buffer.isBuffer(buffer)) {
|
if (Buffer.isBuffer(buffer)) {
|
||||||
metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true })
|
metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true })
|
||||||
} else if(typeof buffer === 'string') {
|
} else if (typeof buffer === 'string') {
|
||||||
const rStream = createReadStream(buffer)
|
const rStream = createReadStream(buffer)
|
||||||
try {
|
try {
|
||||||
metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true })
|
metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true })
|
||||||
@@ -209,11 +206,11 @@ export async function getAudioDuration(buffer: Buffer | string | Readable) {
|
|||||||
*/
|
*/
|
||||||
export async function getAudioWaveform(buffer: Buffer | string | Readable, logger?: ILogger) {
|
export async function getAudioWaveform(buffer: Buffer | string | Readable, logger?: ILogger) {
|
||||||
try {
|
try {
|
||||||
const { default: decoder } = await eval('import(\'audio-decode\')')
|
const { default: decoder } = await eval("import('audio-decode')")
|
||||||
let audioData: Buffer
|
let audioData: Buffer
|
||||||
if(Buffer.isBuffer(buffer)) {
|
if (Buffer.isBuffer(buffer)) {
|
||||||
audioData = buffer
|
audioData = buffer
|
||||||
} else if(typeof buffer === 'string') {
|
} else if (typeof buffer === 'string') {
|
||||||
const rStream = createReadStream(buffer)
|
const rStream = createReadStream(buffer)
|
||||||
audioData = await toBuffer(rStream)
|
audioData = await toBuffer(rStream)
|
||||||
} else {
|
} else {
|
||||||
@@ -226,10 +223,10 @@ export async function getAudioWaveform(buffer: Buffer | string | Readable, logge
|
|||||||
const samples = 64 // Number of samples we want to have in our final data set
|
const samples = 64 // Number of samples we want to have in our final data set
|
||||||
const blockSize = Math.floor(rawData.length / samples) // the number of samples in each subdivision
|
const blockSize = Math.floor(rawData.length / samples) // the number of samples in each subdivision
|
||||||
const filteredData: number[] = []
|
const filteredData: number[] = []
|
||||||
for(let i = 0; i < samples; i++) {
|
for (let i = 0; i < samples; i++) {
|
||||||
const blockStart = blockSize * i // the location of the first sample in the block
|
const blockStart = blockSize * i // the location of the first sample in the block
|
||||||
let sum = 0
|
let sum = 0
|
||||||
for(let j = 0; j < blockSize; j++) {
|
for (let j = 0; j < blockSize; j++) {
|
||||||
sum = sum + Math.abs(rawData[blockStart + j]) // find the sum of all the samples in the block
|
sum = sum + Math.abs(rawData[blockStart + j]) // find the sum of all the samples in the block
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,20 +235,17 @@ export async function getAudioWaveform(buffer: Buffer | string | Readable, logge
|
|||||||
|
|
||||||
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
||||||
const multiplier = Math.pow(Math.max(...filteredData), -1)
|
const multiplier = Math.pow(Math.max(...filteredData), -1)
|
||||||
const normalizedData = filteredData.map((n) => n * multiplier)
|
const normalizedData = filteredData.map(n => n * multiplier)
|
||||||
|
|
||||||
// Generate waveform like WhatsApp
|
// Generate waveform like WhatsApp
|
||||||
const waveform = new Uint8Array(
|
const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)))
|
||||||
normalizedData.map((n) => Math.floor(100 * n))
|
|
||||||
)
|
|
||||||
|
|
||||||
return waveform
|
return waveform
|
||||||
} catch(e) {
|
} catch (e) {
|
||||||
logger?.debug('Failed to generate waveform: ' + e)
|
logger?.debug('Failed to generate waveform: ' + e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const toReadable = (buffer: Buffer) => {
|
export const toReadable = (buffer: Buffer) => {
|
||||||
const readable = new Readable({ read: () => {} })
|
const readable = new Readable({ read: () => {} })
|
||||||
readable.push(buffer)
|
readable.push(buffer)
|
||||||
@@ -259,7 +253,7 @@ export const toReadable = (buffer: Buffer) => {
|
|||||||
return readable
|
return readable
|
||||||
}
|
}
|
||||||
|
|
||||||
export const toBuffer = async(stream: Readable) => {
|
export const toBuffer = async (stream: Readable) => {
|
||||||
const chunks: Buffer[] = []
|
const chunks: Buffer[] = []
|
||||||
for await (const chunk of stream) {
|
for await (const chunk of stream) {
|
||||||
chunks.push(chunk)
|
chunks.push(chunk)
|
||||||
@@ -269,16 +263,16 @@ export const toBuffer = async(stream: Readable) => {
|
|||||||
return Buffer.concat(chunks)
|
return Buffer.concat(chunks)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getStream = async(item: WAMediaUpload, opts?: AxiosRequestConfig) => {
|
export const getStream = async (item: WAMediaUpload, opts?: AxiosRequestConfig) => {
|
||||||
if(Buffer.isBuffer(item)) {
|
if (Buffer.isBuffer(item)) {
|
||||||
return { stream: toReadable(item), type: 'buffer' } as const
|
return { stream: toReadable(item), type: 'buffer' } as const
|
||||||
}
|
}
|
||||||
|
|
||||||
if('stream' in item) {
|
if ('stream' in item) {
|
||||||
return { stream: item.stream, type: 'readable' } as const
|
return { stream: item.stream, type: 'readable' } as const
|
||||||
}
|
}
|
||||||
|
|
||||||
if(item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
|
if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
|
||||||
return { stream: await getHttpStream(item.url, opts), type: 'remote' } as const
|
return { stream: await getHttpStream(item.url, opts), type: 'remote' } as const
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,17 +288,17 @@ export async function generateThumbnail(
|
|||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
let thumbnail: string | undefined
|
let thumbnail: string | undefined
|
||||||
let originalImageDimensions: { width: number, height: number } | undefined
|
let originalImageDimensions: { width: number; height: number } | undefined
|
||||||
if(mediaType === 'image') {
|
if (mediaType === 'image') {
|
||||||
const { buffer, original } = await extractImageThumb(file)
|
const { buffer, original } = await extractImageThumb(file)
|
||||||
thumbnail = buffer.toString('base64')
|
thumbnail = buffer.toString('base64')
|
||||||
if(original.width && original.height) {
|
if (original.width && original.height) {
|
||||||
originalImageDimensions = {
|
originalImageDimensions = {
|
||||||
width: original.width,
|
width: original.width,
|
||||||
height: original.height,
|
height: original.height
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if(mediaType === 'video') {
|
} else if (mediaType === 'video') {
|
||||||
const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg')
|
const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg')
|
||||||
try {
|
try {
|
||||||
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 })
|
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 })
|
||||||
@@ -312,7 +306,7 @@ export async function generateThumbnail(
|
|||||||
thumbnail = buff.toString('base64')
|
thumbnail = buff.toString('base64')
|
||||||
|
|
||||||
await fs.unlink(imgFilename)
|
await fs.unlink(imgFilename)
|
||||||
} catch(err) {
|
} catch (err) {
|
||||||
options.logger?.debug('could not generate video thumb: ' + err)
|
options.logger?.debug('could not generate video thumb: ' + err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -323,7 +317,7 @@ export async function generateThumbnail(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getHttpStream = async(url: string | URL, options: AxiosRequestConfig & { isStream?: true } = {}) => {
|
export const getHttpStream = async (url: string | URL, options: AxiosRequestConfig & { isStream?: true } = {}) => {
|
||||||
const fetched = await axios.get(url.toString(), { ...options, responseType: 'stream' })
|
const fetched = await axios.get(url.toString(), { ...options, responseType: 'stream' })
|
||||||
return fetched.data as Readable
|
return fetched.data as Readable
|
||||||
}
|
}
|
||||||
@@ -334,7 +328,7 @@ type EncryptedStreamOptions = {
|
|||||||
opts?: AxiosRequestConfig
|
opts?: AxiosRequestConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
export const encryptedStream = async(
|
export const encryptedStream = async (
|
||||||
media: WAMediaUpload,
|
media: WAMediaUpload,
|
||||||
mediaType: MediaType,
|
mediaType: MediaType,
|
||||||
{ logger, saveOriginalFileIfRequired, opts }: EncryptedStreamOptions = {}
|
{ logger, saveOriginalFileIfRequired, opts }: EncryptedStreamOptions = {}
|
||||||
@@ -350,9 +344,9 @@ export const encryptedStream = async(
|
|||||||
let bodyPath: string | undefined
|
let bodyPath: string | undefined
|
||||||
let writeStream: WriteStream | undefined
|
let writeStream: WriteStream | undefined
|
||||||
let didSaveToTmpPath = false
|
let didSaveToTmpPath = false
|
||||||
if(type === 'file') {
|
if (type === 'file') {
|
||||||
bodyPath = (media as WAMediaPayloadURL).url.toString()
|
bodyPath = (media as WAMediaPayloadURL).url.toString()
|
||||||
} else if(saveOriginalFileIfRequired) {
|
} else if (saveOriginalFileIfRequired) {
|
||||||
bodyPath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2())
|
bodyPath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2())
|
||||||
writeStream = createWriteStream(bodyPath)
|
writeStream = createWriteStream(bodyPath)
|
||||||
didSaveToTmpPath = true
|
didSaveToTmpPath = true
|
||||||
@@ -368,21 +362,14 @@ export const encryptedStream = async(
|
|||||||
for await (const data of stream) {
|
for await (const data of stream) {
|
||||||
fileLength += data.length
|
fileLength += data.length
|
||||||
|
|
||||||
if(
|
if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
|
||||||
type === 'remote'
|
throw new Boom(`content length exceeded when encrypting "${type}"`, {
|
||||||
&& opts?.maxContentLength
|
|
||||||
&& fileLength + data.length > opts.maxContentLength
|
|
||||||
) {
|
|
||||||
throw new Boom(
|
|
||||||
`content length exceeded when encrypting "${type}"`,
|
|
||||||
{
|
|
||||||
data: { media, type }
|
data: { media, type }
|
||||||
}
|
})
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sha256Plain = sha256Plain.update(data)
|
sha256Plain = sha256Plain.update(data)
|
||||||
if(writeStream && !writeStream.write(data)) {
|
if (writeStream && !writeStream.write(data)) {
|
||||||
await once(writeStream, 'drain')
|
await once(writeStream, 'drain')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -415,7 +402,7 @@ export const encryptedStream = async(
|
|||||||
fileLength,
|
fileLength,
|
||||||
didSaveToTmpPath
|
didSaveToTmpPath
|
||||||
}
|
}
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
// destroy all streams with error
|
// destroy all streams with error
|
||||||
encWriteStream.destroy()
|
encWriteStream.destroy()
|
||||||
writeStream?.destroy()
|
writeStream?.destroy()
|
||||||
@@ -425,10 +412,10 @@ export const encryptedStream = async(
|
|||||||
sha256Enc.destroy()
|
sha256Enc.destroy()
|
||||||
stream.destroy()
|
stream.destroy()
|
||||||
|
|
||||||
if(didSaveToTmpPath) {
|
if (didSaveToTmpPath) {
|
||||||
try {
|
try {
|
||||||
await fs.unlink(bodyPath!)
|
await fs.unlink(bodyPath!)
|
||||||
} catch(err) {
|
} catch (err) {
|
||||||
logger?.error({ err }, 'failed to save to tmp path')
|
logger?.error({ err }, 'failed to save to tmp path')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -458,10 +445,10 @@ export type MediaDownloadOptions = {
|
|||||||
|
|
||||||
export const getUrlFromDirectPath = (directPath: string) => `https://${DEF_HOST}${directPath}`
|
export const getUrlFromDirectPath = (directPath: string) => `https://${DEF_HOST}${directPath}`
|
||||||
|
|
||||||
export const downloadContentFromMessage = async(
|
export const downloadContentFromMessage = async (
|
||||||
{ mediaKey, directPath, url }: DownloadableMessage,
|
{ mediaKey, directPath, url }: DownloadableMessage,
|
||||||
type: MediaType,
|
type: MediaType,
|
||||||
opts: MediaDownloadOptions = { }
|
opts: MediaDownloadOptions = {}
|
||||||
) => {
|
) => {
|
||||||
const downloadUrl = url || getUrlFromDirectPath(directPath!)
|
const downloadUrl = url || getUrlFromDirectPath(directPath!)
|
||||||
const keys = await getMediaKeys(mediaKey, type)
|
const keys = await getMediaKeys(mediaKey, type)
|
||||||
@@ -473,18 +460,18 @@ export const downloadContentFromMessage = async(
|
|||||||
* Decrypts and downloads an AES256-CBC encrypted file given the keys.
|
* Decrypts and downloads an AES256-CBC encrypted file given the keys.
|
||||||
* Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
|
* Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
|
||||||
* */
|
* */
|
||||||
export const downloadEncryptedContent = async(
|
export const downloadEncryptedContent = async (
|
||||||
downloadUrl: string,
|
downloadUrl: string,
|
||||||
{ cipherKey, iv }: MediaDecryptionKeyInfo,
|
{ cipherKey, iv }: MediaDecryptionKeyInfo,
|
||||||
{ startByte, endByte, options }: MediaDownloadOptions = { }
|
{ startByte, endByte, options }: MediaDownloadOptions = {}
|
||||||
) => {
|
) => {
|
||||||
let bytesFetched = 0
|
let bytesFetched = 0
|
||||||
let startChunk = 0
|
let startChunk = 0
|
||||||
let firstBlockIsIV = false
|
let firstBlockIsIV = false
|
||||||
// if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
|
// if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
|
||||||
if(startByte) {
|
if (startByte) {
|
||||||
const chunk = toSmallestChunkSize(startByte || 0)
|
const chunk = toSmallestChunkSize(startByte || 0)
|
||||||
if(chunk) {
|
if (chunk) {
|
||||||
startChunk = chunk - AES_CHUNK_SIZE
|
startChunk = chunk - AES_CHUNK_SIZE
|
||||||
bytesFetched = chunk
|
bytesFetched = chunk
|
||||||
|
|
||||||
@@ -495,33 +482,30 @@ export const downloadEncryptedContent = async(
|
|||||||
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
||||||
|
|
||||||
const headers: AxiosRequestConfig['headers'] = {
|
const headers: AxiosRequestConfig['headers'] = {
|
||||||
...options?.headers || { },
|
...(options?.headers || {}),
|
||||||
Origin: DEFAULT_ORIGIN,
|
Origin: DEFAULT_ORIGIN
|
||||||
}
|
}
|
||||||
if(startChunk || endChunk) {
|
if (startChunk || endChunk) {
|
||||||
headers.Range = `bytes=${startChunk}-`
|
headers.Range = `bytes=${startChunk}-`
|
||||||
if(endChunk) {
|
if (endChunk) {
|
||||||
headers.Range += endChunk
|
headers.Range += endChunk
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// download the message
|
// download the message
|
||||||
const fetched = await getHttpStream(
|
const fetched = await getHttpStream(downloadUrl, {
|
||||||
downloadUrl,
|
...(options || {}),
|
||||||
{
|
|
||||||
...options || { },
|
|
||||||
headers,
|
headers,
|
||||||
maxBodyLength: Infinity,
|
maxBodyLength: Infinity,
|
||||||
maxContentLength: Infinity,
|
maxContentLength: Infinity
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
let remainingBytes = Buffer.from([])
|
let remainingBytes = Buffer.from([])
|
||||||
|
|
||||||
let aes: Crypto.Decipher
|
let aes: Crypto.Decipher
|
||||||
|
|
||||||
const pushBytes = (bytes: Buffer, push: (bytes: Buffer) => void) => {
|
const pushBytes = (bytes: Buffer, push: (bytes: Buffer) => void) => {
|
||||||
if(startByte || endByte) {
|
if (startByte || endByte) {
|
||||||
const start = bytesFetched >= startByte! ? undefined : Math.max(startByte! - bytesFetched, 0)
|
const start = bytesFetched >= startByte! ? undefined : Math.max(startByte! - bytesFetched, 0)
|
||||||
const end = bytesFetched + bytes.length < endByte! ? undefined : Math.max(endByte! - bytesFetched, 0)
|
const end = bytesFetched + bytes.length < endByte! ? undefined : Math.max(endByte! - bytesFetched, 0)
|
||||||
|
|
||||||
@@ -541,9 +525,9 @@ export const downloadEncryptedContent = async(
|
|||||||
remainingBytes = data.slice(decryptLength)
|
remainingBytes = data.slice(decryptLength)
|
||||||
data = data.slice(0, decryptLength)
|
data = data.slice(0, decryptLength)
|
||||||
|
|
||||||
if(!aes) {
|
if (!aes) {
|
||||||
let ivValue = iv
|
let ivValue = iv
|
||||||
if(firstBlockIsIV) {
|
if (firstBlockIsIV) {
|
||||||
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
||||||
data = data.slice(AES_CHUNK_SIZE)
|
data = data.slice(AES_CHUNK_SIZE)
|
||||||
}
|
}
|
||||||
@@ -551,16 +535,15 @@ export const downloadEncryptedContent = async(
|
|||||||
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
||||||
// if an end byte that is not EOF is specified
|
// if an end byte that is not EOF is specified
|
||||||
// stop auto padding (PKCS7) -- otherwise throws an error for decryption
|
// stop auto padding (PKCS7) -- otherwise throws an error for decryption
|
||||||
if(endByte) {
|
if (endByte) {
|
||||||
aes.setAutoPadding(false)
|
aes.setAutoPadding(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
pushBytes(aes.update(data), b => this.push(b))
|
pushBytes(aes.update(data), b => this.push(b))
|
||||||
callback()
|
callback()
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
callback(error)
|
callback(error)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -568,10 +551,10 @@ export const downloadEncryptedContent = async(
|
|||||||
try {
|
try {
|
||||||
pushBytes(aes.final(), b => this.push(b))
|
pushBytes(aes.final(), b => this.push(b))
|
||||||
callback()
|
callback()
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
callback(error)
|
callback(error)
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
})
|
})
|
||||||
return fetched.pipe(output, { end: true })
|
return fetched.pipe(output, { end: true })
|
||||||
}
|
}
|
||||||
@@ -580,11 +563,7 @@ export function extensionForMediaMessage(message: WAMessageContent) {
|
|||||||
const getExtension = (mimetype: string) => mimetype.split(';')[0].split('/')[1]
|
const getExtension = (mimetype: string) => mimetype.split(';')[0].split('/')[1]
|
||||||
const type = Object.keys(message)[0] as MessageType
|
const type = Object.keys(message)[0] as MessageType
|
||||||
let extension: string
|
let extension: string
|
||||||
if(
|
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
|
||||||
type === 'locationMessage' ||
|
|
||||||
type === 'liveLocationMessage' ||
|
|
||||||
type === 'productMessage'
|
|
||||||
) {
|
|
||||||
extension = '.jpeg'
|
extension = '.jpeg'
|
||||||
} else {
|
} else {
|
||||||
const messageContent = message[type] as WAGenericMediaMessage
|
const messageContent = message[type] as WAGenericMediaMessage
|
||||||
@@ -596,18 +575,18 @@ export function extensionForMediaMessage(message: WAMessageContent) {
|
|||||||
|
|
||||||
export const getWAUploadToServer = (
|
export const getWAUploadToServer = (
|
||||||
{ customUploadHosts, fetchAgent, logger, options }: SocketConfig,
|
{ customUploadHosts, fetchAgent, logger, options }: SocketConfig,
|
||||||
refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>,
|
refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>
|
||||||
): WAMediaUploadFunction => {
|
): WAMediaUploadFunction => {
|
||||||
return async(stream, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
return async (stream, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
||||||
// send a query JSON to obtain the url & auth token to upload our media
|
// send a query JSON to obtain the url & auth token to upload our media
|
||||||
let uploadInfo = await refreshMediaConn(false)
|
let uploadInfo = await refreshMediaConn(false)
|
||||||
|
|
||||||
let urls: { mediaUrl: string, directPath: string } | undefined
|
let urls: { mediaUrl: string; directPath: string } | undefined
|
||||||
const hosts = [ ...customUploadHosts, ...uploadInfo.hosts ]
|
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
||||||
|
|
||||||
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
||||||
|
|
||||||
for(const { hostname } of hosts) {
|
for (const { hostname } of hosts) {
|
||||||
logger.debug(`uploading to "${hostname}"`)
|
logger.debug(`uploading to "${hostname}"`)
|
||||||
|
|
||||||
const auth = encodeURIComponent(uploadInfo.auth) // the auth token
|
const auth = encodeURIComponent(uploadInfo.auth) // the auth token
|
||||||
@@ -615,27 +594,22 @@ export const getWAUploadToServer = (
|
|||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
let result: any
|
let result: any
|
||||||
try {
|
try {
|
||||||
|
const body = await axios.post(url, stream, {
|
||||||
const body = await axios.post(
|
|
||||||
url,
|
|
||||||
stream,
|
|
||||||
{
|
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
...options.headers || { },
|
...(options.headers || {}),
|
||||||
'Content-Type': 'application/octet-stream',
|
'Content-Type': 'application/octet-stream',
|
||||||
'Origin': DEFAULT_ORIGIN
|
Origin: DEFAULT_ORIGIN
|
||||||
},
|
},
|
||||||
httpsAgent: fetchAgent,
|
httpsAgent: fetchAgent,
|
||||||
timeout: timeoutMs,
|
timeout: timeoutMs,
|
||||||
responseType: 'json',
|
responseType: 'json',
|
||||||
maxBodyLength: Infinity,
|
maxBodyLength: Infinity,
|
||||||
maxContentLength: Infinity,
|
maxContentLength: Infinity
|
||||||
}
|
})
|
||||||
)
|
|
||||||
result = body.data
|
result = body.data
|
||||||
|
|
||||||
if(result?.url || result?.directPath) {
|
if (result?.url || result?.directPath) {
|
||||||
urls = {
|
urls = {
|
||||||
mediaUrl: result.url,
|
mediaUrl: result.url,
|
||||||
directPath: result.direct_path
|
directPath: result.direct_path
|
||||||
@@ -645,21 +619,21 @@ export const getWAUploadToServer = (
|
|||||||
uploadInfo = await refreshMediaConn(true)
|
uploadInfo = await refreshMediaConn(true)
|
||||||
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
||||||
}
|
}
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
if(axios.isAxiosError(error)) {
|
if (axios.isAxiosError(error)) {
|
||||||
result = error.response?.data
|
result = error.response?.data
|
||||||
}
|
}
|
||||||
|
|
||||||
const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
|
const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
|
||||||
logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`)
|
logger.warn(
|
||||||
|
{ trace: error.stack, uploadResult: result },
|
||||||
|
`Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!urls) {
|
if (!urls) {
|
||||||
throw new Boom(
|
throw new Boom('Media upload failed on all hosts', { statusCode: 500 })
|
||||||
'Media upload failed on all hosts',
|
|
||||||
{ statusCode: 500 }
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return urls
|
return urls
|
||||||
@@ -673,11 +647,7 @@ const getMediaRetryKey = (mediaKey: Buffer | Uint8Array) => {
|
|||||||
/**
|
/**
|
||||||
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
||||||
*/
|
*/
|
||||||
export const encryptMediaRetryRequest = async(
|
export const encryptMediaRetryRequest = async (key: proto.IMessageKey, mediaKey: Buffer | Uint8Array, meId: string) => {
|
||||||
key: proto.IMessageKey,
|
|
||||||
mediaKey: Buffer | Uint8Array,
|
|
||||||
meId: string
|
|
||||||
) => {
|
|
||||||
const recp: proto.IServerErrorReceipt = { stanzaId: key.id }
|
const recp: proto.IServerErrorReceipt = { stanzaId: key.id }
|
||||||
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
|
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
|
||||||
|
|
||||||
@@ -698,17 +668,17 @@ export const encryptMediaRetryRequest = async(
|
|||||||
// keeping it here to maintain parity with WA Web
|
// keeping it here to maintain parity with WA Web
|
||||||
{
|
{
|
||||||
tag: 'encrypt',
|
tag: 'encrypt',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{ tag: 'enc_p', attrs: { }, content: ciphertext },
|
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
||||||
{ tag: 'enc_iv', attrs: { }, content: iv }
|
{ tag: 'enc_iv', attrs: {}, content: iv }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'rmr',
|
tag: 'rmr',
|
||||||
attrs: {
|
attrs: {
|
||||||
jid: key.remoteJid!,
|
jid: key.remoteJid!,
|
||||||
'from_me': (!!key.fromMe).toString(),
|
from_me: (!!key.fromMe).toString(),
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
participant: key.participant || undefined
|
participant: key.participant || undefined
|
||||||
}
|
}
|
||||||
@@ -732,17 +702,17 @@ export const decodeMediaRetryNode = (node: BinaryNode) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const errorNode = getBinaryNodeChild(node, 'error')
|
const errorNode = getBinaryNodeChild(node, 'error')
|
||||||
if(errorNode) {
|
if (errorNode) {
|
||||||
const errorCode = +errorNode.attrs.code
|
const errorCode = +errorNode.attrs.code
|
||||||
event.error = new Boom(
|
event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
|
||||||
`Failed to re-upload media (${errorCode})`,
|
data: errorNode.attrs,
|
||||||
{ data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(errorCode) }
|
statusCode: getStatusCodeForMediaRetry(errorCode)
|
||||||
)
|
})
|
||||||
} else {
|
} else {
|
||||||
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
|
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
|
||||||
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
|
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
|
||||||
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
|
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
|
||||||
if(ciphertext && iv) {
|
if (ciphertext && iv) {
|
||||||
event.media = { ciphertext, iv }
|
event.media = { ciphertext, iv }
|
||||||
} else {
|
} else {
|
||||||
event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
||||||
@@ -752,8 +722,8 @@ export const decodeMediaRetryNode = (node: BinaryNode) => {
|
|||||||
return event
|
return event
|
||||||
}
|
}
|
||||||
|
|
||||||
export const decryptMediaRetryData = async(
|
export const decryptMediaRetryData = async (
|
||||||
{ ciphertext, iv }: { ciphertext: Uint8Array, iv: Uint8Array },
|
{ ciphertext, iv }: { ciphertext: Uint8Array; iv: Uint8Array },
|
||||||
mediaKey: Uint8Array,
|
mediaKey: Uint8Array,
|
||||||
msgId: string
|
msgId: string
|
||||||
) => {
|
) => {
|
||||||
@@ -768,5 +738,5 @@ const MEDIA_RETRY_STATUS_MAP = {
|
|||||||
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
||||||
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
||||||
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
||||||
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
|
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
||||||
} as const
|
} as const
|
||||||
@@ -21,13 +21,20 @@ import {
|
|||||||
WAMessageContent,
|
WAMessageContent,
|
||||||
WAMessageStatus,
|
WAMessageStatus,
|
||||||
WAProto,
|
WAProto,
|
||||||
WATextMessage,
|
WATextMessage
|
||||||
} from '../Types'
|
} from '../Types'
|
||||||
import { isJidGroup, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
|
import { isJidGroup, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
|
||||||
import { sha256 } from './crypto'
|
import { sha256 } from './crypto'
|
||||||
import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics'
|
import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics'
|
||||||
import { ILogger } from './logger'
|
import { ILogger } from './logger'
|
||||||
import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, MediaDownloadOptions } from './messages-media'
|
import {
|
||||||
|
downloadContentFromMessage,
|
||||||
|
encryptedStream,
|
||||||
|
generateThumbnail,
|
||||||
|
getAudioDuration,
|
||||||
|
getAudioWaveform,
|
||||||
|
MediaDownloadOptions
|
||||||
|
} from './messages-media'
|
||||||
|
|
||||||
type MediaUploadData = {
|
type MediaUploadData = {
|
||||||
media: WAMediaUpload
|
media: WAMediaUpload
|
||||||
@@ -51,15 +58,15 @@ const MIMETYPE_MAP: { [T in MediaType]?: string } = {
|
|||||||
document: 'application/pdf',
|
document: 'application/pdf',
|
||||||
audio: 'audio/ogg; codecs=opus',
|
audio: 'audio/ogg; codecs=opus',
|
||||||
sticker: 'image/webp',
|
sticker: 'image/webp',
|
||||||
'product-catalog-image': 'image/jpeg',
|
'product-catalog-image': 'image/jpeg'
|
||||||
}
|
}
|
||||||
|
|
||||||
const MessageTypeProto = {
|
const MessageTypeProto = {
|
||||||
'image': WAProto.Message.ImageMessage,
|
image: WAProto.Message.ImageMessage,
|
||||||
'video': WAProto.Message.VideoMessage,
|
video: WAProto.Message.VideoMessage,
|
||||||
'audio': WAProto.Message.AudioMessage,
|
audio: WAProto.Message.AudioMessage,
|
||||||
'sticker': WAProto.Message.StickerMessage,
|
sticker: WAProto.Message.StickerMessage,
|
||||||
'document': WAProto.Message.DocumentMessage,
|
document: WAProto.Message.DocumentMessage
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,25 +76,30 @@ const MessageTypeProto = {
|
|||||||
*/
|
*/
|
||||||
export const extractUrlFromText = (text: string) => text.match(URL_REGEX)?.[0]
|
export const extractUrlFromText = (text: string) => text.match(URL_REGEX)?.[0]
|
||||||
|
|
||||||
export const generateLinkPreviewIfRequired = async(text: string, getUrlInfo: MessageGenerationOptions['getUrlInfo'], logger: MessageGenerationOptions['logger']) => {
|
export const generateLinkPreviewIfRequired = async (
|
||||||
|
text: string,
|
||||||
|
getUrlInfo: MessageGenerationOptions['getUrlInfo'],
|
||||||
|
logger: MessageGenerationOptions['logger']
|
||||||
|
) => {
|
||||||
const url = extractUrlFromText(text)
|
const url = extractUrlFromText(text)
|
||||||
if(!!getUrlInfo && url) {
|
if (!!getUrlInfo && url) {
|
||||||
try {
|
try {
|
||||||
const urlInfo = await getUrlInfo(url)
|
const urlInfo = await getUrlInfo(url)
|
||||||
return urlInfo
|
return urlInfo
|
||||||
} catch(error) { // ignore if fails
|
} catch (error) {
|
||||||
|
// ignore if fails
|
||||||
logger?.warn({ trace: error.stack }, 'url generation failed')
|
logger?.warn({ trace: error.stack }, 'url generation failed')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const assertColor = async(color) => {
|
const assertColor = async color => {
|
||||||
let assertedColor
|
let assertedColor
|
||||||
if(typeof color === 'number') {
|
if (typeof color === 'number') {
|
||||||
assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1
|
assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1
|
||||||
} else {
|
} else {
|
||||||
let hex = color.trim().replace('#', '')
|
let hex = color.trim().replace('#', '')
|
||||||
if(hex.length <= 6) {
|
if (hex.length <= 6) {
|
||||||
hex = 'FF' + hex.padStart(6, '0')
|
hex = 'FF' + hex.padStart(6, '0')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,20 +108,17 @@ const assertColor = async(color) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const prepareWAMessageMedia = async(
|
export const prepareWAMessageMedia = async (message: AnyMediaMessageContent, options: MediaGenerationOptions) => {
|
||||||
message: AnyMediaMessageContent,
|
|
||||||
options: MediaGenerationOptions
|
|
||||||
) => {
|
|
||||||
const logger = options.logger
|
const logger = options.logger
|
||||||
|
|
||||||
let mediaType: typeof MEDIA_KEYS[number] | undefined
|
let mediaType: (typeof MEDIA_KEYS)[number] | undefined
|
||||||
for(const key of MEDIA_KEYS) {
|
for (const key of MEDIA_KEYS) {
|
||||||
if(key in message) {
|
if (key in message) {
|
||||||
mediaType = key
|
mediaType = key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!mediaType) {
|
if (!mediaType) {
|
||||||
throw new Boom('Invalid media type', { statusCode: 400 })
|
throw new Boom('Invalid media type', { statusCode: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,26 +128,26 @@ export const prepareWAMessageMedia = async(
|
|||||||
}
|
}
|
||||||
delete uploadData[mediaType]
|
delete uploadData[mediaType]
|
||||||
// check if cacheable + generate cache key
|
// check if cacheable + generate cache key
|
||||||
const cacheableKey = typeof uploadData.media === 'object' &&
|
const cacheableKey =
|
||||||
('url' in uploadData.media) &&
|
typeof uploadData.media === 'object' &&
|
||||||
|
'url' in uploadData.media &&
|
||||||
!!uploadData.media.url &&
|
!!uploadData.media.url &&
|
||||||
!!options.mediaCache && (
|
!!options.mediaCache &&
|
||||||
// generate the key
|
// generate the key
|
||||||
mediaType + ':' + uploadData.media.url.toString()
|
mediaType + ':' + uploadData.media.url.toString()
|
||||||
)
|
|
||||||
|
|
||||||
if(mediaType === 'document' && !uploadData.fileName) {
|
if (mediaType === 'document' && !uploadData.fileName) {
|
||||||
uploadData.fileName = 'file'
|
uploadData.fileName = 'file'
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!uploadData.mimetype) {
|
if (!uploadData.mimetype) {
|
||||||
uploadData.mimetype = MIMETYPE_MAP[mediaType]
|
uploadData.mimetype = MIMETYPE_MAP[mediaType]
|
||||||
}
|
}
|
||||||
|
|
||||||
// check for cache hit
|
// check for cache hit
|
||||||
if(cacheableKey) {
|
if (cacheableKey) {
|
||||||
const mediaBuff = options.mediaCache!.get<Buffer>(cacheableKey)
|
const mediaBuff = options.mediaCache!.get<Buffer>(cacheableKey)
|
||||||
if(mediaBuff) {
|
if (mediaBuff) {
|
||||||
logger?.debug({ cacheableKey }, 'got media cache hit')
|
logger?.debug({ cacheableKey }, 'got media cache hit')
|
||||||
|
|
||||||
const obj = WAProto.Message.decode(mediaBuff)
|
const obj = WAProto.Message.decode(mediaBuff)
|
||||||
@@ -151,48 +160,39 @@ export const prepareWAMessageMedia = async(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
|
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
|
||||||
const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
|
const requiresThumbnailComputation =
|
||||||
(typeof uploadData['jpegThumbnail'] === 'undefined')
|
(mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined'
|
||||||
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true
|
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true
|
||||||
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true
|
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true
|
||||||
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation
|
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation
|
||||||
const {
|
const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath } =
|
||||||
mediaKey,
|
await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
|
||||||
encWriteStream,
|
|
||||||
bodyPath,
|
|
||||||
fileEncSha256,
|
|
||||||
fileSha256,
|
|
||||||
fileLength,
|
|
||||||
didSaveToTmpPath
|
|
||||||
} = await encryptedStream(
|
|
||||||
uploadData.media,
|
|
||||||
options.mediaTypeOverride || mediaType,
|
|
||||||
{
|
|
||||||
logger,
|
logger,
|
||||||
saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
|
saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
|
||||||
opts: options.options
|
opts: options.options
|
||||||
}
|
})
|
||||||
)
|
|
||||||
// url safe Base64 encode the SHA256 hash of the body
|
// url safe Base64 encode the SHA256 hash of the body
|
||||||
const fileEncSha256B64 = fileEncSha256.toString('base64')
|
const fileEncSha256B64 = fileEncSha256.toString('base64')
|
||||||
const [{ mediaUrl, directPath }] = await Promise.all([
|
const [{ mediaUrl, directPath }] = await Promise.all([
|
||||||
(async() => {
|
(async () => {
|
||||||
const result = await options.upload(
|
const result = await options.upload(encWriteStream, {
|
||||||
encWriteStream,
|
fileEncSha256B64,
|
||||||
{ fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs }
|
mediaType,
|
||||||
)
|
timeoutMs: options.mediaUploadTimeoutMs
|
||||||
|
})
|
||||||
logger?.debug({ mediaType, cacheableKey }, 'uploaded media')
|
logger?.debug({ mediaType, cacheableKey }, 'uploaded media')
|
||||||
return result
|
return result
|
||||||
})(),
|
})(),
|
||||||
(async() => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
if(requiresThumbnailComputation) {
|
if (requiresThumbnailComputation) {
|
||||||
const {
|
const { thumbnail, originalImageDimensions } = await generateThumbnail(
|
||||||
thumbnail,
|
bodyPath!,
|
||||||
originalImageDimensions
|
mediaType as 'image' | 'video',
|
||||||
} = await generateThumbnail(bodyPath!, mediaType as 'image' | 'video', options)
|
options
|
||||||
|
)
|
||||||
uploadData.jpegThumbnail = thumbnail
|
uploadData.jpegThumbnail = thumbnail
|
||||||
if(!uploadData.width && originalImageDimensions) {
|
if (!uploadData.width && originalImageDimensions) {
|
||||||
uploadData.width = originalImageDimensions.width
|
uploadData.width = originalImageDimensions.width
|
||||||
uploadData.height = originalImageDimensions.height
|
uploadData.height = originalImageDimensions.height
|
||||||
logger?.debug('set dimensions')
|
logger?.debug('set dimensions')
|
||||||
@@ -201,44 +201,40 @@ export const prepareWAMessageMedia = async(
|
|||||||
logger?.debug('generated thumbnail')
|
logger?.debug('generated thumbnail')
|
||||||
}
|
}
|
||||||
|
|
||||||
if(requiresDurationComputation) {
|
if (requiresDurationComputation) {
|
||||||
uploadData.seconds = await getAudioDuration(bodyPath!)
|
uploadData.seconds = await getAudioDuration(bodyPath!)
|
||||||
logger?.debug('computed audio duration')
|
logger?.debug('computed audio duration')
|
||||||
}
|
}
|
||||||
|
|
||||||
if(requiresWaveformProcessing) {
|
if (requiresWaveformProcessing) {
|
||||||
uploadData.waveform = await getAudioWaveform(bodyPath!, logger)
|
uploadData.waveform = await getAudioWaveform(bodyPath!, logger)
|
||||||
logger?.debug('processed waveform')
|
logger?.debug('processed waveform')
|
||||||
}
|
}
|
||||||
|
|
||||||
if(requiresAudioBackground) {
|
if (requiresAudioBackground) {
|
||||||
uploadData.backgroundArgb = await assertColor(options.backgroundColor)
|
uploadData.backgroundArgb = await assertColor(options.backgroundColor)
|
||||||
logger?.debug('computed backgroundColor audio status')
|
logger?.debug('computed backgroundColor audio status')
|
||||||
}
|
}
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
logger?.warn({ trace: error.stack }, 'failed to obtain extra info')
|
logger?.warn({ trace: error.stack }, 'failed to obtain extra info')
|
||||||
}
|
}
|
||||||
})(),
|
})()
|
||||||
])
|
]).finally(async () => {
|
||||||
.finally(
|
|
||||||
async() => {
|
|
||||||
encWriteStream.destroy()
|
encWriteStream.destroy()
|
||||||
// remove tmp files
|
// remove tmp files
|
||||||
if(didSaveToTmpPath && bodyPath) {
|
if (didSaveToTmpPath && bodyPath) {
|
||||||
try {
|
try {
|
||||||
await fs.access(bodyPath)
|
await fs.access(bodyPath)
|
||||||
await fs.unlink(bodyPath)
|
await fs.unlink(bodyPath)
|
||||||
logger?.debug('removed tmp file')
|
logger?.debug('removed tmp file')
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
logger?.warn('failed to remove tmp file')
|
logger?.warn('failed to remove tmp file')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
const obj = WAProto.Message.fromObject({
|
const obj = WAProto.Message.fromObject({
|
||||||
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject(
|
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
||||||
{
|
|
||||||
url: mediaUrl,
|
url: mediaUrl,
|
||||||
directPath,
|
directPath,
|
||||||
mediaKey,
|
mediaKey,
|
||||||
@@ -248,16 +244,15 @@ export const prepareWAMessageMedia = async(
|
|||||||
mediaKeyTimestamp: unixTimestampSeconds(),
|
mediaKeyTimestamp: unixTimestampSeconds(),
|
||||||
...uploadData,
|
...uploadData,
|
||||||
media: undefined
|
media: undefined
|
||||||
}
|
})
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if(uploadData.ptv) {
|
if (uploadData.ptv) {
|
||||||
obj.ptvMessage = obj.videoMessage
|
obj.ptvMessage = obj.videoMessage
|
||||||
delete obj.videoMessage
|
delete obj.videoMessage
|
||||||
}
|
}
|
||||||
|
|
||||||
if(cacheableKey) {
|
if (cacheableKey) {
|
||||||
logger?.debug({ cacheableKey }, 'set cache')
|
logger?.debug({ cacheableKey }, 'set cache')
|
||||||
options.mediaCache!.set(cacheableKey, WAProto.Message.encode(obj).finish())
|
options.mediaCache!.set(cacheableKey, WAProto.Message.encode(obj).finish())
|
||||||
}
|
}
|
||||||
@@ -285,12 +280,9 @@ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration?: n
|
|||||||
* @param message the message to forward
|
* @param message the message to forward
|
||||||
* @param options.forceForward will show the message as forwarded even if it is from you
|
* @param options.forceForward will show the message as forwarded even if it is from you
|
||||||
*/
|
*/
|
||||||
export const generateForwardMessageContent = (
|
export const generateForwardMessageContent = (message: WAMessage, forceForward?: boolean) => {
|
||||||
message: WAMessage,
|
|
||||||
forceForward?: boolean
|
|
||||||
) => {
|
|
||||||
let content = message.message
|
let content = message.message
|
||||||
if(!content) {
|
if (!content) {
|
||||||
throw new Boom('no content in message', { statusCode: 400 })
|
throw new Boom('no content in message', { statusCode: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,14 +294,14 @@ export const generateForwardMessageContent = (
|
|||||||
|
|
||||||
let score = content[key].contextInfo?.forwardingScore || 0
|
let score = content[key].contextInfo?.forwardingScore || 0
|
||||||
score += message.key.fromMe && !forceForward ? 0 : 1
|
score += message.key.fromMe && !forceForward ? 0 : 1
|
||||||
if(key === 'conversation') {
|
if (key === 'conversation') {
|
||||||
content.extendedTextMessage = { text: content[key] }
|
content.extendedTextMessage = { text: content[key] }
|
||||||
delete content.conversation
|
delete content.conversation
|
||||||
|
|
||||||
key = 'extendedTextMessage'
|
key = 'extendedTextMessage'
|
||||||
}
|
}
|
||||||
|
|
||||||
if(score > 0) {
|
if (score > 0) {
|
||||||
content[key].contextInfo = { forwardingScore: score, isForwarded: true }
|
content[key].contextInfo = { forwardingScore: score, isForwarded: true }
|
||||||
} else {
|
} else {
|
||||||
content[key].contextInfo = {}
|
content[key].contextInfo = {}
|
||||||
@@ -318,20 +310,20 @@ export const generateForwardMessageContent = (
|
|||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
export const generateWAMessageContent = async(
|
export const generateWAMessageContent = async (
|
||||||
message: AnyMessageContent,
|
message: AnyMessageContent,
|
||||||
options: MessageContentGenerationOptions
|
options: MessageContentGenerationOptions
|
||||||
) => {
|
) => {
|
||||||
let m: WAMessageContent = {}
|
let m: WAMessageContent = {}
|
||||||
if('text' in message) {
|
if ('text' in message) {
|
||||||
const extContent = { text: message.text } as WATextMessage
|
const extContent = { text: message.text } as WATextMessage
|
||||||
|
|
||||||
let urlInfo = message.linkPreview
|
let urlInfo = message.linkPreview
|
||||||
if(typeof urlInfo === 'undefined') {
|
if (typeof urlInfo === 'undefined') {
|
||||||
urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger)
|
urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(urlInfo) {
|
if (urlInfo) {
|
||||||
extContent.matchedText = urlInfo['matched-text']
|
extContent.matchedText = urlInfo['matched-text']
|
||||||
extContent.jpegThumbnail = urlInfo.jpegThumbnail
|
extContent.jpegThumbnail = urlInfo.jpegThumbnail
|
||||||
extContent.description = urlInfo.description
|
extContent.description = urlInfo.description
|
||||||
@@ -339,7 +331,7 @@ export const generateWAMessageContent = async(
|
|||||||
extContent.previewType = 0
|
extContent.previewType = 0
|
||||||
|
|
||||||
const img = urlInfo.highQualityThumbnail
|
const img = urlInfo.highQualityThumbnail
|
||||||
if(img) {
|
if (img) {
|
||||||
extContent.thumbnailDirectPath = img.directPath
|
extContent.thumbnailDirectPath = img.directPath
|
||||||
extContent.mediaKey = img.mediaKey
|
extContent.mediaKey = img.mediaKey
|
||||||
extContent.mediaKeyTimestamp = img.mediaKeyTimestamp
|
extContent.mediaKeyTimestamp = img.mediaKeyTimestamp
|
||||||
@@ -350,50 +342,50 @@ export const generateWAMessageContent = async(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(options.backgroundColor) {
|
if (options.backgroundColor) {
|
||||||
extContent.backgroundArgb = await assertColor(options.backgroundColor)
|
extContent.backgroundArgb = await assertColor(options.backgroundColor)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(options.font) {
|
if (options.font) {
|
||||||
extContent.font = options.font
|
extContent.font = options.font
|
||||||
}
|
}
|
||||||
|
|
||||||
m.extendedTextMessage = extContent
|
m.extendedTextMessage = extContent
|
||||||
} else if('contacts' in message) {
|
} else if ('contacts' in message) {
|
||||||
const contactLen = message.contacts.contacts.length
|
const contactLen = message.contacts.contacts.length
|
||||||
if(!contactLen) {
|
if (!contactLen) {
|
||||||
throw new Boom('require atleast 1 contact', { statusCode: 400 })
|
throw new Boom('require atleast 1 contact', { statusCode: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
if(contactLen === 1) {
|
if (contactLen === 1) {
|
||||||
m.contactMessage = WAProto.Message.ContactMessage.fromObject(message.contacts.contacts[0])
|
m.contactMessage = WAProto.Message.ContactMessage.fromObject(message.contacts.contacts[0])
|
||||||
} else {
|
} else {
|
||||||
m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.fromObject(message.contacts)
|
m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.fromObject(message.contacts)
|
||||||
}
|
}
|
||||||
} else if('location' in message) {
|
} else if ('location' in message) {
|
||||||
m.locationMessage = WAProto.Message.LocationMessage.fromObject(message.location)
|
m.locationMessage = WAProto.Message.LocationMessage.fromObject(message.location)
|
||||||
} else if('react' in message) {
|
} else if ('react' in message) {
|
||||||
if(!message.react.senderTimestampMs) {
|
if (!message.react.senderTimestampMs) {
|
||||||
message.react.senderTimestampMs = Date.now()
|
message.react.senderTimestampMs = Date.now()
|
||||||
}
|
}
|
||||||
|
|
||||||
m.reactionMessage = WAProto.Message.ReactionMessage.fromObject(message.react)
|
m.reactionMessage = WAProto.Message.ReactionMessage.fromObject(message.react)
|
||||||
} else if('delete' in message) {
|
} else if ('delete' in message) {
|
||||||
m.protocolMessage = {
|
m.protocolMessage = {
|
||||||
key: message.delete,
|
key: message.delete,
|
||||||
type: WAProto.Message.ProtocolMessage.Type.REVOKE
|
type: WAProto.Message.ProtocolMessage.Type.REVOKE
|
||||||
}
|
}
|
||||||
} else if('forward' in message) {
|
} else if ('forward' in message) {
|
||||||
m = generateForwardMessageContent(
|
m = generateForwardMessageContent(message.forward, message.force)
|
||||||
message.forward,
|
} else if ('disappearingMessagesInChat' in message) {
|
||||||
message.force
|
const exp =
|
||||||
)
|
typeof message.disappearingMessagesInChat === 'boolean'
|
||||||
} else if('disappearingMessagesInChat' in message) {
|
? message.disappearingMessagesInChat
|
||||||
const exp = typeof message.disappearingMessagesInChat === 'boolean' ?
|
? WA_DEFAULT_EPHEMERAL
|
||||||
(message.disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) :
|
: 0
|
||||||
message.disappearingMessagesInChat
|
: message.disappearingMessagesInChat
|
||||||
m = prepareDisappearingMessageSettingContent(exp)
|
m = prepareDisappearingMessageSettingContent(exp)
|
||||||
} else if('groupInvite' in message) {
|
} else if ('groupInvite' in message) {
|
||||||
m.groupInviteMessage = {}
|
m.groupInviteMessage = {}
|
||||||
m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode
|
m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode
|
||||||
m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration
|
m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration
|
||||||
@@ -403,16 +395,16 @@ export const generateWAMessageContent = async(
|
|||||||
m.groupInviteMessage.groupName = message.groupInvite.subject
|
m.groupInviteMessage.groupName = message.groupInvite.subject
|
||||||
//TODO: use built-in interface and get disappearing mode info etc.
|
//TODO: use built-in interface and get disappearing mode info etc.
|
||||||
//TODO: cache / use store!?
|
//TODO: cache / use store!?
|
||||||
if(options.getProfilePicUrl) {
|
if (options.getProfilePicUrl) {
|
||||||
const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview')
|
const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview')
|
||||||
if(pfpUrl) {
|
if (pfpUrl) {
|
||||||
const resp = await axios.get(pfpUrl, { responseType: 'arraybuffer' })
|
const resp = await axios.get(pfpUrl, { responseType: 'arraybuffer' })
|
||||||
if(resp.status === 200) {
|
if (resp.status === 200) {
|
||||||
m.groupInviteMessage.jpegThumbnail = resp.data
|
m.groupInviteMessage.jpegThumbnail = resp.data
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if('pin' in message) {
|
} else if ('pin' in message) {
|
||||||
m.pinInChatMessage = {}
|
m.pinInChatMessage = {}
|
||||||
m.messageContextInfo = {}
|
m.messageContextInfo = {}
|
||||||
|
|
||||||
@@ -421,77 +413,67 @@ export const generateWAMessageContent = async(
|
|||||||
m.pinInChatMessage.senderTimestampMs = Date.now()
|
m.pinInChatMessage.senderTimestampMs = Date.now()
|
||||||
|
|
||||||
m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0
|
m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0
|
||||||
} else if('buttonReply' in message) {
|
} else if ('buttonReply' in message) {
|
||||||
switch (message.type) {
|
switch (message.type) {
|
||||||
case 'template':
|
case 'template':
|
||||||
m.templateButtonReplyMessage = {
|
m.templateButtonReplyMessage = {
|
||||||
selectedDisplayText: message.buttonReply.displayText,
|
selectedDisplayText: message.buttonReply.displayText,
|
||||||
selectedId: message.buttonReply.id,
|
selectedId: message.buttonReply.id,
|
||||||
selectedIndex: message.buttonReply.index,
|
selectedIndex: message.buttonReply.index
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
case 'plain':
|
case 'plain':
|
||||||
m.buttonsResponseMessage = {
|
m.buttonsResponseMessage = {
|
||||||
selectedButtonId: message.buttonReply.id,
|
selectedButtonId: message.buttonReply.id,
|
||||||
selectedDisplayText: message.buttonReply.displayText,
|
selectedDisplayText: message.buttonReply.displayText,
|
||||||
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
|
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
} else if('ptv' in message && message.ptv) {
|
} else if ('ptv' in message && message.ptv) {
|
||||||
const { videoMessage } = await prepareWAMessageMedia(
|
const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options)
|
||||||
{ video: message.video },
|
|
||||||
options
|
|
||||||
)
|
|
||||||
m.ptvMessage = videoMessage
|
m.ptvMessage = videoMessage
|
||||||
} else if('product' in message) {
|
} else if ('product' in message) {
|
||||||
const { imageMessage } = await prepareWAMessageMedia(
|
const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options)
|
||||||
{ image: message.product.productImage },
|
|
||||||
options
|
|
||||||
)
|
|
||||||
m.productMessage = WAProto.Message.ProductMessage.fromObject({
|
m.productMessage = WAProto.Message.ProductMessage.fromObject({
|
||||||
...message,
|
...message,
|
||||||
product: {
|
product: {
|
||||||
...message.product,
|
...message.product,
|
||||||
productImage: imageMessage,
|
productImage: imageMessage
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} else if('listReply' in message) {
|
} else if ('listReply' in message) {
|
||||||
m.listResponseMessage = { ...message.listReply }
|
m.listResponseMessage = { ...message.listReply }
|
||||||
} else if('poll' in message) {
|
} else if ('poll' in message) {
|
||||||
message.poll.selectableCount ||= 0
|
message.poll.selectableCount ||= 0
|
||||||
message.poll.toAnnouncementGroup ||= false
|
message.poll.toAnnouncementGroup ||= false
|
||||||
|
|
||||||
if(!Array.isArray(message.poll.values)) {
|
if (!Array.isArray(message.poll.values)) {
|
||||||
throw new Boom('Invalid poll values', { statusCode: 400 })
|
throw new Boom('Invalid poll values', { statusCode: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
if(
|
if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
|
||||||
message.poll.selectableCount < 0
|
throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
|
||||||
|| message.poll.selectableCount > message.poll.values.length
|
statusCode: 400
|
||||||
) {
|
})
|
||||||
throw new Boom(
|
|
||||||
`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`,
|
|
||||||
{ statusCode: 400 }
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
m.messageContextInfo = {
|
m.messageContextInfo = {
|
||||||
// encKey
|
// encKey
|
||||||
messageSecret: message.poll.messageSecret || randomBytes(32),
|
messageSecret: message.poll.messageSecret || randomBytes(32)
|
||||||
}
|
}
|
||||||
|
|
||||||
const pollCreationMessage = {
|
const pollCreationMessage = {
|
||||||
name: message.poll.name,
|
name: message.poll.name,
|
||||||
selectableOptionsCount: message.poll.selectableCount,
|
selectableOptionsCount: message.poll.selectableCount,
|
||||||
options: message.poll.values.map(optionName => ({ optionName })),
|
options: message.poll.values.map(optionName => ({ optionName }))
|
||||||
}
|
}
|
||||||
|
|
||||||
if(message.poll.toAnnouncementGroup) {
|
if (message.poll.toAnnouncementGroup) {
|
||||||
// poll v2 is for community announcement groups (single select and multiple)
|
// poll v2 is for community announcement groups (single select and multiple)
|
||||||
m.pollCreationMessageV2 = pollCreationMessage
|
m.pollCreationMessageV2 = pollCreationMessage
|
||||||
} else {
|
} else {
|
||||||
if(message.poll.selectableCount > 0) {
|
if (message.poll.selectableCount > 0) {
|
||||||
//poll v3 is for single select polls
|
//poll v3 is for single select polls
|
||||||
m.pollCreationMessageV3 = pollCreationMessage
|
m.pollCreationMessageV3 = pollCreationMessage
|
||||||
} else {
|
} else {
|
||||||
@@ -499,30 +481,27 @@ export const generateWAMessageContent = async(
|
|||||||
m.pollCreationMessage = pollCreationMessage
|
m.pollCreationMessage = pollCreationMessage
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if('sharePhoneNumber' in message) {
|
} else if ('sharePhoneNumber' in message) {
|
||||||
m.protocolMessage = {
|
m.protocolMessage = {
|
||||||
type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
|
type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
|
||||||
}
|
}
|
||||||
} else if('requestPhoneNumber' in message) {
|
} else if ('requestPhoneNumber' in message) {
|
||||||
m.requestPhoneNumberMessage = {}
|
m.requestPhoneNumberMessage = {}
|
||||||
} else {
|
} else {
|
||||||
m = await prepareWAMessageMedia(
|
m = await prepareWAMessageMedia(message, options)
|
||||||
message,
|
|
||||||
options
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if('viewOnce' in message && !!message.viewOnce) {
|
if ('viewOnce' in message && !!message.viewOnce) {
|
||||||
m = { viewOnceMessage: { message: m } }
|
m = { viewOnceMessage: { message: m } }
|
||||||
}
|
}
|
||||||
|
|
||||||
if('mentions' in message && message.mentions?.length) {
|
if ('mentions' in message && message.mentions?.length) {
|
||||||
const [messageType] = Object.keys(m)
|
const [messageType] = Object.keys(m)
|
||||||
m[messageType].contextInfo = m[messageType] || { }
|
m[messageType].contextInfo = m[messageType] || {}
|
||||||
m[messageType].contextInfo.mentionedJid = message.mentions
|
m[messageType].contextInfo.mentionedJid = message.mentions
|
||||||
}
|
}
|
||||||
|
|
||||||
if('edit' in message) {
|
if ('edit' in message) {
|
||||||
m = {
|
m = {
|
||||||
protocolMessage: {
|
protocolMessage: {
|
||||||
key: message.edit,
|
key: message.edit,
|
||||||
@@ -533,7 +512,7 @@ export const generateWAMessageContent = async(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if('contextInfo' in message && !!message.contextInfo) {
|
if ('contextInfo' in message && !!message.contextInfo) {
|
||||||
const [messageType] = Object.keys(m)
|
const [messageType] = Object.keys(m)
|
||||||
m[messageType] = m[messageType] || {}
|
m[messageType] = m[messageType] || {}
|
||||||
m[messageType].contextInfo = message.contextInfo
|
m[messageType].contextInfo = message.contextInfo
|
||||||
@@ -549,7 +528,7 @@ export const generateWAMessageFromContent = (
|
|||||||
) => {
|
) => {
|
||||||
// set timestamp to now
|
// set timestamp to now
|
||||||
// if not specified
|
// if not specified
|
||||||
if(!options.timestamp) {
|
if (!options.timestamp) {
|
||||||
options.timestamp = new Date()
|
options.timestamp = new Date()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -558,8 +537,10 @@ export const generateWAMessageFromContent = (
|
|||||||
const timestamp = unixTimestampSeconds(options.timestamp)
|
const timestamp = unixTimestampSeconds(options.timestamp)
|
||||||
const { quoted, userJid } = options
|
const { quoted, userJid } = options
|
||||||
|
|
||||||
if(quoted) {
|
if (quoted) {
|
||||||
const participant = quoted.key.fromMe ? userJid : (quoted.participant || quoted.key.participant || quoted.key.remoteJid)
|
const participant = quoted.key.fromMe
|
||||||
|
? userJid
|
||||||
|
: quoted.participant || quoted.key.participant || quoted.key.remoteJid
|
||||||
|
|
||||||
let quotedMsg = normalizeMessageContent(quoted.message)!
|
let quotedMsg = normalizeMessageContent(quoted.message)!
|
||||||
const msgType = getContentType(quotedMsg)!
|
const msgType = getContentType(quotedMsg)!
|
||||||
@@ -567,25 +548,25 @@ export const generateWAMessageFromContent = (
|
|||||||
quotedMsg = proto.Message.fromObject({ [msgType]: quotedMsg[msgType] })
|
quotedMsg = proto.Message.fromObject({ [msgType]: quotedMsg[msgType] })
|
||||||
|
|
||||||
const quotedContent = quotedMsg[msgType]
|
const quotedContent = quotedMsg[msgType]
|
||||||
if(typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
|
if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
|
||||||
delete quotedContent.contextInfo
|
delete quotedContent.contextInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
const contextInfo: proto.IContextInfo = innerMessage[key].contextInfo || { }
|
const contextInfo: proto.IContextInfo = innerMessage[key].contextInfo || {}
|
||||||
contextInfo.participant = jidNormalizedUser(participant!)
|
contextInfo.participant = jidNormalizedUser(participant!)
|
||||||
contextInfo.stanzaId = quoted.key.id
|
contextInfo.stanzaId = quoted.key.id
|
||||||
contextInfo.quotedMessage = quotedMsg
|
contextInfo.quotedMessage = quotedMsg
|
||||||
|
|
||||||
// if a participant is quoted, then it must be a group
|
// if a participant is quoted, then it must be a group
|
||||||
// hence, remoteJid of group must also be entered
|
// hence, remoteJid of group must also be entered
|
||||||
if(jid !== quoted.key.remoteJid) {
|
if (jid !== quoted.key.remoteJid) {
|
||||||
contextInfo.remoteJid = quoted.key.remoteJid
|
contextInfo.remoteJid = quoted.key.remoteJid
|
||||||
}
|
}
|
||||||
|
|
||||||
innerMessage[key].contextInfo = contextInfo
|
innerMessage[key].contextInfo = contextInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
if(
|
if (
|
||||||
// if we want to send a disappearing message
|
// if we want to send a disappearing message
|
||||||
!!options?.ephemeralExpiration &&
|
!!options?.ephemeralExpiration &&
|
||||||
// and it's not a protocol message -- delete, toggle disappear message
|
// and it's not a protocol message -- delete, toggle disappear message
|
||||||
@@ -595,7 +576,7 @@ export const generateWAMessageFromContent = (
|
|||||||
) {
|
) {
|
||||||
innerMessage[key].contextInfo = {
|
innerMessage[key].contextInfo = {
|
||||||
...(innerMessage[key].contextInfo || {}),
|
...(innerMessage[key].contextInfo || {}),
|
||||||
expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL,
|
expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
|
||||||
//ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
|
//ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -606,7 +587,7 @@ export const generateWAMessageFromContent = (
|
|||||||
key: {
|
key: {
|
||||||
remoteJid: jid,
|
remoteJid: jid,
|
||||||
fromMe: true,
|
fromMe: true,
|
||||||
id: options?.messageId || generateMessageIDV2(),
|
id: options?.messageId || generateMessageIDV2()
|
||||||
},
|
},
|
||||||
message: message,
|
message: message,
|
||||||
messageTimestamp: timestamp,
|
messageTimestamp: timestamp,
|
||||||
@@ -617,26 +598,15 @@ export const generateWAMessageFromContent = (
|
|||||||
return WAProto.WebMessageInfo.fromObject(messageJSON)
|
return WAProto.WebMessageInfo.fromObject(messageJSON)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const generateWAMessage = async(
|
export const generateWAMessage = async (jid: string, content: AnyMessageContent, options: MessageGenerationOptions) => {
|
||||||
jid: string,
|
|
||||||
content: AnyMessageContent,
|
|
||||||
options: MessageGenerationOptions,
|
|
||||||
) => {
|
|
||||||
// ensure msg ID is with every log
|
// ensure msg ID is with every log
|
||||||
options.logger = options?.logger?.child({ msgId: options.messageId })
|
options.logger = options?.logger?.child({ msgId: options.messageId })
|
||||||
return generateWAMessageFromContent(
|
return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options)
|
||||||
jid,
|
|
||||||
await generateWAMessageContent(
|
|
||||||
content,
|
|
||||||
options
|
|
||||||
),
|
|
||||||
options
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Get the key to access the true type of content */
|
/** Get the key to access the true type of content */
|
||||||
export const getContentType = (content: WAProto.IMessage | undefined) => {
|
export const getContentType = (content: WAProto.IMessage | undefined) => {
|
||||||
if(content) {
|
if (content) {
|
||||||
const keys = Object.keys(content)
|
const keys = Object.keys(content)
|
||||||
const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage')
|
const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage')
|
||||||
return key as keyof typeof content
|
return key as keyof typeof content
|
||||||
@@ -650,14 +620,14 @@ export const getContentType = (content: WAProto.IMessage | undefined) => {
|
|||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const normalizeMessageContent = (content: WAMessageContent | null | undefined): WAMessageContent | undefined => {
|
export const normalizeMessageContent = (content: WAMessageContent | null | undefined): WAMessageContent | undefined => {
|
||||||
if(!content) {
|
if (!content) {
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
// set max iterations to prevent an infinite loop
|
// set max iterations to prevent an infinite loop
|
||||||
for(let i = 0;i < 5;i++) {
|
for (let i = 0; i < 5; i++) {
|
||||||
const inner = getFutureProofMessage(content)
|
const inner = getFutureProofMessage(content)
|
||||||
if(!inner) {
|
if (!inner) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -668,12 +638,12 @@ export const normalizeMessageContent = (content: WAMessageContent | null | undef
|
|||||||
|
|
||||||
function getFutureProofMessage(message: typeof content) {
|
function getFutureProofMessage(message: typeof content) {
|
||||||
return (
|
return (
|
||||||
message?.ephemeralMessage
|
message?.ephemeralMessage ||
|
||||||
|| message?.viewOnceMessage
|
message?.viewOnceMessage ||
|
||||||
|| message?.documentWithCaptionMessage
|
message?.documentWithCaptionMessage ||
|
||||||
|| message?.viewOnceMessageV2
|
message?.viewOnceMessageV2 ||
|
||||||
|| message?.viewOnceMessageV2Extension
|
message?.viewOnceMessageV2Extension ||
|
||||||
|| message?.editedMessage
|
message?.editedMessage
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -683,40 +653,40 @@ export const normalizeMessageContent = (content: WAMessageContent | null | undef
|
|||||||
* Eg. extracts the inner message from a disappearing message/view once message
|
* Eg. extracts the inner message from a disappearing message/view once message
|
||||||
*/
|
*/
|
||||||
export const extractMessageContent = (content: WAMessageContent | undefined | null): WAMessageContent | undefined => {
|
export const extractMessageContent = (content: WAMessageContent | undefined | null): WAMessageContent | undefined => {
|
||||||
const extractFromTemplateMessage = (msg: proto.Message.TemplateMessage.IHydratedFourRowTemplate | proto.Message.IButtonsMessage) => {
|
const extractFromTemplateMessage = (
|
||||||
if(msg.imageMessage) {
|
msg: proto.Message.TemplateMessage.IHydratedFourRowTemplate | proto.Message.IButtonsMessage
|
||||||
|
) => {
|
||||||
|
if (msg.imageMessage) {
|
||||||
return { imageMessage: msg.imageMessage }
|
return { imageMessage: msg.imageMessage }
|
||||||
} else if(msg.documentMessage) {
|
} else if (msg.documentMessage) {
|
||||||
return { documentMessage: msg.documentMessage }
|
return { documentMessage: msg.documentMessage }
|
||||||
} else if(msg.videoMessage) {
|
} else if (msg.videoMessage) {
|
||||||
return { videoMessage: msg.videoMessage }
|
return { videoMessage: msg.videoMessage }
|
||||||
} else if(msg.locationMessage) {
|
} else if (msg.locationMessage) {
|
||||||
return { locationMessage: msg.locationMessage }
|
return { locationMessage: msg.locationMessage }
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
conversation:
|
conversation:
|
||||||
'contentText' in msg
|
'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
|
||||||
? msg.contentText
|
|
||||||
: ('hydratedContentText' in msg ? msg.hydratedContentText : '')
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
content = normalizeMessageContent(content)
|
content = normalizeMessageContent(content)
|
||||||
|
|
||||||
if(content?.buttonsMessage) {
|
if (content?.buttonsMessage) {
|
||||||
return extractFromTemplateMessage(content.buttonsMessage)
|
return extractFromTemplateMessage(content.buttonsMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(content?.templateMessage?.hydratedFourRowTemplate) {
|
if (content?.templateMessage?.hydratedFourRowTemplate) {
|
||||||
return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate)
|
return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(content?.templateMessage?.hydratedTemplate) {
|
if (content?.templateMessage?.hydratedTemplate) {
|
||||||
return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate)
|
return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(content?.templateMessage?.fourRowTemplate) {
|
if (content?.templateMessage?.fourRowTemplate) {
|
||||||
return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate)
|
return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -726,17 +696,22 @@ export const extractMessageContent = (content: WAMessageContent | undefined | nu
|
|||||||
/**
|
/**
|
||||||
* Returns the device predicted by message ID
|
* Returns the device predicted by message ID
|
||||||
*/
|
*/
|
||||||
export const getDevice = (id: string) => /^3A.{18}$/.test(id) ? 'ios' :
|
export const getDevice = (id: string) =>
|
||||||
/^3E.{20}$/.test(id) ? 'web' :
|
/^3A.{18}$/.test(id)
|
||||||
/^(.{21}|.{32})$/.test(id) ? 'android' :
|
? 'ios'
|
||||||
/^(3F|.{18}$)/.test(id) ? 'desktop' :
|
: /^3E.{20}$/.test(id)
|
||||||
'unknown'
|
? 'web'
|
||||||
|
: /^(.{21}|.{32})$/.test(id)
|
||||||
|
? 'android'
|
||||||
|
: /^(3F|.{18}$)/.test(id)
|
||||||
|
? 'desktop'
|
||||||
|
: 'unknown'
|
||||||
|
|
||||||
/** Upserts a receipt in the message */
|
/** Upserts a receipt in the message */
|
||||||
export const updateMessageWithReceipt = (msg: Pick<WAMessage, 'userReceipt'>, receipt: MessageUserReceipt) => {
|
export const updateMessageWithReceipt = (msg: Pick<WAMessage, 'userReceipt'>, receipt: MessageUserReceipt) => {
|
||||||
msg.userReceipt = msg.userReceipt || []
|
msg.userReceipt = msg.userReceipt || []
|
||||||
const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid)
|
const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid)
|
||||||
if(recp) {
|
if (recp) {
|
||||||
Object.assign(recp, receipt)
|
Object.assign(recp, receipt)
|
||||||
} else {
|
} else {
|
||||||
msg.userReceipt.push(receipt)
|
msg.userReceipt.push(receipt)
|
||||||
@@ -747,9 +722,8 @@ export const updateMessageWithReceipt = (msg: Pick<WAMessage, 'userReceipt'>, re
|
|||||||
export const updateMessageWithReaction = (msg: Pick<WAMessage, 'reactions'>, reaction: proto.IReaction) => {
|
export const updateMessageWithReaction = (msg: Pick<WAMessage, 'reactions'>, reaction: proto.IReaction) => {
|
||||||
const authorID = getKeyAuthor(reaction.key)
|
const authorID = getKeyAuthor(reaction.key)
|
||||||
|
|
||||||
const reactions = (msg.reactions || [])
|
const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID)
|
||||||
.filter(r => getKeyAuthor(r.key) !== authorID)
|
if (reaction.text) {
|
||||||
if(reaction.text) {
|
|
||||||
reactions.push(reaction)
|
reactions.push(reaction)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -757,15 +731,11 @@ export const updateMessageWithReaction = (msg: Pick<WAMessage, 'reactions'>, rea
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Update the message with a new poll update */
|
/** Update the message with a new poll update */
|
||||||
export const updateMessageWithPollUpdate = (
|
export const updateMessageWithPollUpdate = (msg: Pick<WAMessage, 'pollUpdates'>, update: proto.IPollUpdate) => {
|
||||||
msg: Pick<WAMessage, 'pollUpdates'>,
|
|
||||||
update: proto.IPollUpdate
|
|
||||||
) => {
|
|
||||||
const authorID = getKeyAuthor(update.pollUpdateMessageKey)
|
const authorID = getKeyAuthor(update.pollUpdateMessageKey)
|
||||||
|
|
||||||
const reactions = (msg.pollUpdates || [])
|
const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
|
||||||
.filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
|
if (update.vote?.selectedOptions?.length) {
|
||||||
if(update.vote?.selectedOptions?.length) {
|
|
||||||
reactions.push(update)
|
reactions.push(update)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -787,26 +757,33 @@ export function getAggregateVotesInPollMessage(
|
|||||||
{ message, pollUpdates }: Pick<WAMessage, 'pollUpdates' | 'message'>,
|
{ message, pollUpdates }: Pick<WAMessage, 'pollUpdates' | 'message'>,
|
||||||
meId?: string
|
meId?: string
|
||||||
) {
|
) {
|
||||||
const opts = message?.pollCreationMessage?.options || message?.pollCreationMessageV2?.options || message?.pollCreationMessageV3?.options || []
|
const opts =
|
||||||
const voteHashMap = opts.reduce((acc, opt) => {
|
message?.pollCreationMessage?.options ||
|
||||||
|
message?.pollCreationMessageV2?.options ||
|
||||||
|
message?.pollCreationMessageV3?.options ||
|
||||||
|
[]
|
||||||
|
const voteHashMap = opts.reduce(
|
||||||
|
(acc, opt) => {
|
||||||
const hash = sha256(Buffer.from(opt.optionName || '')).toString()
|
const hash = sha256(Buffer.from(opt.optionName || '')).toString()
|
||||||
acc[hash] = {
|
acc[hash] = {
|
||||||
name: opt.optionName || '',
|
name: opt.optionName || '',
|
||||||
voters: []
|
voters: []
|
||||||
}
|
}
|
||||||
return acc
|
return acc
|
||||||
}, {} as { [_: string]: VoteAggregation })
|
},
|
||||||
|
{} as { [_: string]: VoteAggregation }
|
||||||
|
)
|
||||||
|
|
||||||
for(const update of pollUpdates || []) {
|
for (const update of pollUpdates || []) {
|
||||||
const { vote } = update
|
const { vote } = update
|
||||||
if(!vote) {
|
if (!vote) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const option of vote.selectedOptions || []) {
|
for (const option of vote.selectedOptions || []) {
|
||||||
const hash = option.toString()
|
const hash = option.toString()
|
||||||
let data = voteHashMap[hash]
|
let data = voteHashMap[hash]
|
||||||
if(!data) {
|
if (!data) {
|
||||||
voteHashMap[hash] = {
|
voteHashMap[hash] = {
|
||||||
name: 'Unknown',
|
name: 'Unknown',
|
||||||
voters: []
|
voters: []
|
||||||
@@ -814,9 +791,7 @@ export function getAggregateVotesInPollMessage(
|
|||||||
data = voteHashMap[hash]
|
data = voteHashMap[hash]
|
||||||
}
|
}
|
||||||
|
|
||||||
voteHashMap[hash].voters.push(
|
voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId))
|
||||||
getKeyAuthor(update.pollUpdateMessageKey, meId)
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -825,11 +800,11 @@ export function getAggregateVotesInPollMessage(
|
|||||||
|
|
||||||
/** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
|
/** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
|
||||||
export const aggregateMessageKeysNotFromMe = (keys: proto.IMessageKey[]) => {
|
export const aggregateMessageKeysNotFromMe = (keys: proto.IMessageKey[]) => {
|
||||||
const keyMap: { [id: string]: { jid: string, participant: string | undefined, messageIds: string[] } } = { }
|
const keyMap: { [id: string]: { jid: string; participant: string | undefined; messageIds: string[] } } = {}
|
||||||
for(const { remoteJid, id, participant, fromMe } of keys) {
|
for (const { remoteJid, id, participant, fromMe } of keys) {
|
||||||
if(!fromMe) {
|
if (!fromMe) {
|
||||||
const uqKey = `${remoteJid}:${participant || ''}`
|
const uqKey = `${remoteJid}:${participant || ''}`
|
||||||
if(!keyMap[uqKey]) {
|
if (!keyMap[uqKey]) {
|
||||||
keyMap[uqKey] = {
|
keyMap[uqKey] = {
|
||||||
jid: remoteJid!,
|
jid: remoteJid!,
|
||||||
participant: participant!,
|
participant: participant!,
|
||||||
@@ -854,16 +829,18 @@ const REUPLOAD_REQUIRED_STATUS = [410, 404]
|
|||||||
/**
|
/**
|
||||||
* Downloads the given message. Throws an error if it's not a media message
|
* Downloads the given message. Throws an error if it's not a media message
|
||||||
*/
|
*/
|
||||||
export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
export const downloadMediaMessage = async <Type extends 'buffer' | 'stream'>(
|
||||||
message: WAMessage,
|
message: WAMessage,
|
||||||
type: Type,
|
type: Type,
|
||||||
options: MediaDownloadOptions,
|
options: MediaDownloadOptions,
|
||||||
ctx?: DownloadMediaMessageContext
|
ctx?: DownloadMediaMessageContext
|
||||||
) => {
|
) => {
|
||||||
const result = await downloadMsg()
|
const result = await downloadMsg().catch(async error => {
|
||||||
.catch(async(error) => {
|
if (
|
||||||
if(ctx && axios.isAxiosError(error) && // check if the message requires a reupload
|
ctx &&
|
||||||
REUPLOAD_REQUIRED_STATUS.includes(error.response?.status!)) {
|
axios.isAxiosError(error) && // check if the message requires a reupload
|
||||||
|
REUPLOAD_REQUIRED_STATUS.includes(error.response?.status!)
|
||||||
|
) {
|
||||||
ctx.logger.info({ key: message.key }, 'sending reupload media request...')
|
ctx.logger.info({ key: message.key }, 'sending reupload media request...')
|
||||||
// request reupload
|
// request reupload
|
||||||
message = await ctx.reuploadRequest(message)
|
message = await ctx.reuploadRequest(message)
|
||||||
@@ -878,7 +855,7 @@ export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
|||||||
|
|
||||||
async function downloadMsg() {
|
async function downloadMsg() {
|
||||||
const mContent = extractMessageContent(message.message)
|
const mContent = extractMessageContent(message.message)
|
||||||
if(!mContent) {
|
if (!mContent) {
|
||||||
throw new Boom('No message present', { statusCode: 400, data: message })
|
throw new Boom('No message present', { statusCode: 400, data: message })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -886,12 +863,12 @@ export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
|||||||
let mediaType = contentType?.replace('Message', '') as MediaType
|
let mediaType = contentType?.replace('Message', '') as MediaType
|
||||||
const media = mContent[contentType!]
|
const media = mContent[contentType!]
|
||||||
|
|
||||||
if(!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
|
if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
|
||||||
throw new Boom(`"${contentType}" message is not a media message`)
|
throw new Boom(`"${contentType}" message is not a media message`)
|
||||||
}
|
}
|
||||||
|
|
||||||
let download: DownloadableMessage
|
let download: DownloadableMessage
|
||||||
if('thumbnailDirectPath' in media && !('url' in media)) {
|
if ('thumbnailDirectPath' in media && !('url' in media)) {
|
||||||
download = {
|
download = {
|
||||||
directPath: media.thumbnailDirectPath,
|
directPath: media.thumbnailDirectPath,
|
||||||
mediaKey: media.mediaKey
|
mediaKey: media.mediaKey
|
||||||
@@ -902,7 +879,7 @@ export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const stream = await downloadContentFromMessage(download, mediaType, options)
|
const stream = await downloadContentFromMessage(download, mediaType, options)
|
||||||
if(type === 'buffer') {
|
if (type === 'buffer') {
|
||||||
const bufferArray: Buffer[] = []
|
const bufferArray: Buffer[] = []
|
||||||
for await (const chunk of stream) {
|
for await (const chunk of stream) {
|
||||||
bufferArray.push(chunk)
|
bufferArray.push(chunk)
|
||||||
@@ -918,16 +895,14 @@ export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
|||||||
/** Checks whether the given message is a media message; if it is returns the inner content */
|
/** Checks whether the given message is a media message; if it is returns the inner content */
|
||||||
export const assertMediaContent = (content: proto.IMessage | null | undefined) => {
|
export const assertMediaContent = (content: proto.IMessage | null | undefined) => {
|
||||||
content = extractMessageContent(content)
|
content = extractMessageContent(content)
|
||||||
const mediaContent = content?.documentMessage
|
const mediaContent =
|
||||||
|| content?.imageMessage
|
content?.documentMessage ||
|
||||||
|| content?.videoMessage
|
content?.imageMessage ||
|
||||||
|| content?.audioMessage
|
content?.videoMessage ||
|
||||||
|| content?.stickerMessage
|
content?.audioMessage ||
|
||||||
if(!mediaContent) {
|
content?.stickerMessage
|
||||||
throw new Boom(
|
if (!mediaContent) {
|
||||||
'given message is not a media message',
|
throw new Boom('given message is not a media message', { statusCode: 400, data: content })
|
||||||
{ statusCode: 400, data: content }
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return mediaContent
|
return mediaContent
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export const makeNoiseHandler = ({
|
|||||||
logger = logger.child({ class: 'ns' })
|
logger = logger.child({ class: 'ns' })
|
||||||
|
|
||||||
const authenticate = (data: Uint8Array) => {
|
const authenticate = (data: Uint8Array) => {
|
||||||
if(!isFinished) {
|
if (!isFinished) {
|
||||||
hash = sha256(Buffer.concat([hash, data]))
|
hash = sha256(Buffer.concat([hash, data]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -47,7 +47,7 @@ export const makeNoiseHandler = ({
|
|||||||
const iv = generateIV(isFinished ? readCounter : writeCounter)
|
const iv = generateIV(isFinished ? readCounter : writeCounter)
|
||||||
const result = aesDecryptGCM(ciphertext, decKey, iv, hash)
|
const result = aesDecryptGCM(ciphertext, decKey, iv, hash)
|
||||||
|
|
||||||
if(isFinished) {
|
if (isFinished) {
|
||||||
readCounter += 1
|
readCounter += 1
|
||||||
} else {
|
} else {
|
||||||
writeCounter += 1
|
writeCounter += 1
|
||||||
@@ -57,12 +57,12 @@ export const makeNoiseHandler = ({
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
const localHKDF = async(data: Uint8Array) => {
|
const localHKDF = async (data: Uint8Array) => {
|
||||||
const key = await hkdf(Buffer.from(data), 64, { salt, info: '' })
|
const key = await hkdf(Buffer.from(data), 64, { salt, info: '' })
|
||||||
return [key.slice(0, 32), key.slice(32)]
|
return [key.slice(0, 32), key.slice(32)]
|
||||||
}
|
}
|
||||||
|
|
||||||
const mixIntoKey = async(data: Uint8Array) => {
|
const mixIntoKey = async (data: Uint8Array) => {
|
||||||
const [write, read] = await localHKDF(data)
|
const [write, read] = await localHKDF(data)
|
||||||
salt = write
|
salt = write
|
||||||
encKey = read
|
encKey = read
|
||||||
@@ -71,7 +71,7 @@ export const makeNoiseHandler = ({
|
|||||||
writeCounter = 0
|
writeCounter = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
const finishInit = async() => {
|
const finishInit = async () => {
|
||||||
const [write, read] = await localHKDF(new Uint8Array(0))
|
const [write, read] = await localHKDF(new Uint8Array(0))
|
||||||
encKey = write
|
encKey = write
|
||||||
decKey = read
|
decKey = read
|
||||||
@@ -102,7 +102,7 @@ export const makeNoiseHandler = ({
|
|||||||
authenticate,
|
authenticate,
|
||||||
mixIntoKey,
|
mixIntoKey,
|
||||||
finishInit,
|
finishInit,
|
||||||
processHandshake: async({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => {
|
processHandshake: async ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => {
|
||||||
authenticate(serverHello!.ephemeral!)
|
authenticate(serverHello!.ephemeral!)
|
||||||
await mixIntoKey(Curve.sharedKey(privateKey, serverHello!.ephemeral!))
|
await mixIntoKey(Curve.sharedKey(privateKey, serverHello!.ephemeral!))
|
||||||
|
|
||||||
@@ -115,7 +115,7 @@ export const makeNoiseHandler = ({
|
|||||||
|
|
||||||
const { issuerSerial } = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate!.details!)
|
const { issuerSerial } = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate!.details!)
|
||||||
|
|
||||||
if(issuerSerial !== WA_CERT_DETAILS.SERIAL) {
|
if (issuerSerial !== WA_CERT_DETAILS.SERIAL) {
|
||||||
throw new Boom('certification match failed', { statusCode: 400 })
|
throw new Boom('certification match failed', { statusCode: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,13 +125,13 @@ export const makeNoiseHandler = ({
|
|||||||
return keyEnc
|
return keyEnc
|
||||||
},
|
},
|
||||||
encodeFrame: (data: Buffer | Uint8Array) => {
|
encodeFrame: (data: Buffer | Uint8Array) => {
|
||||||
if(isFinished) {
|
if (isFinished) {
|
||||||
data = encrypt(data)
|
data = encrypt(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
let header: Buffer
|
let header: Buffer
|
||||||
|
|
||||||
if(routingInfo) {
|
if (routingInfo) {
|
||||||
header = Buffer.alloc(7)
|
header = Buffer.alloc(7)
|
||||||
header.write('ED', 0, 'utf8')
|
header.write('ED', 0, 'utf8')
|
||||||
header.writeUint8(0, 2)
|
header.writeUint8(0, 2)
|
||||||
@@ -146,7 +146,7 @@ export const makeNoiseHandler = ({
|
|||||||
const introSize = sentIntro ? 0 : header.length
|
const introSize = sentIntro ? 0 : header.length
|
||||||
const frame = Buffer.alloc(introSize + 3 + data.byteLength)
|
const frame = Buffer.alloc(introSize + 3 + data.byteLength)
|
||||||
|
|
||||||
if(!sentIntro) {
|
if (!sentIntro) {
|
||||||
frame.set(header)
|
frame.set(header)
|
||||||
sentIntro = true
|
sentIntro = true
|
||||||
}
|
}
|
||||||
@@ -157,26 +157,26 @@ export const makeNoiseHandler = ({
|
|||||||
|
|
||||||
return frame
|
return frame
|
||||||
},
|
},
|
||||||
decodeFrame: async(newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => {
|
decodeFrame: async (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => {
|
||||||
// the binary protocol uses its own framing mechanism
|
// the binary protocol uses its own framing mechanism
|
||||||
// on top of the WS frames
|
// on top of the WS frames
|
||||||
// so we get this data and separate out the frames
|
// so we get this data and separate out the frames
|
||||||
const getBytesSize = () => {
|
const getBytesSize = () => {
|
||||||
if(inBytes.length >= 3) {
|
if (inBytes.length >= 3) {
|
||||||
return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1)
|
return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inBytes = Buffer.concat([ inBytes, newData ])
|
inBytes = Buffer.concat([inBytes, newData])
|
||||||
|
|
||||||
logger.trace(`recv ${newData.length} bytes, total recv ${inBytes.length} bytes`)
|
logger.trace(`recv ${newData.length} bytes, total recv ${inBytes.length} bytes`)
|
||||||
|
|
||||||
let size = getBytesSize()
|
let size = getBytesSize()
|
||||||
while(size && inBytes.length >= size + 3) {
|
while (size && inBytes.length >= size + 3) {
|
||||||
let frame: Uint8Array | BinaryNode = inBytes.slice(3, size + 3)
|
let frame: Uint8Array | BinaryNode = inBytes.slice(3, size + 3)
|
||||||
inBytes = inBytes.slice(size + 3)
|
inBytes = inBytes.slice(size + 3)
|
||||||
|
|
||||||
if(isFinished) {
|
if (isFinished) {
|
||||||
const result = decrypt(frame)
|
const result = decrypt(frame)
|
||||||
frame = await decodeBinaryNode(result)
|
frame = await decodeBinaryNode(result)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,17 @@
|
|||||||
import { AxiosRequestConfig } from 'axios'
|
import { AxiosRequestConfig } from 'axios'
|
||||||
import { proto } from '../../WAProto'
|
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 { getContentType, normalizeMessageContent } from '../Utils/messages'
|
||||||
import { areJidsSameUser, isJidBroadcast, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
|
import { areJidsSameUser, isJidBroadcast, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
|
||||||
import { aesDecryptGCM, hmacSign } from './crypto'
|
import { aesDecryptGCM, hmacSign } from './crypto'
|
||||||
@@ -25,9 +36,7 @@ const REAL_MSG_STUB_TYPES = new Set([
|
|||||||
WAMessageStubType.CALL_MISSED_VOICE
|
WAMessageStubType.CALL_MISSED_VOICE
|
||||||
])
|
])
|
||||||
|
|
||||||
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
|
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
|
||||||
WAMessageStubType.GROUP_PARTICIPANT_ADD
|
|
||||||
])
|
|
||||||
|
|
||||||
/** Cleans a received message to further processing */
|
/** Cleans a received message to further processing */
|
||||||
export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
|
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
|
message.key.participant = message.key.participant ? jidNormalizedUser(message.key.participant) : undefined
|
||||||
const content = normalizeMessageContent(message.message)
|
const content = normalizeMessageContent(message.message)
|
||||||
// if the message has a reaction, ensure fromMe & remoteJid are from our perspective
|
// if the message has a reaction, ensure fromMe & remoteJid are from our perspective
|
||||||
if(content?.reactionMessage) {
|
if (content?.reactionMessage) {
|
||||||
normaliseKey(content.reactionMessage.key!)
|
normaliseKey(content.reactionMessage.key!)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(content?.pollUpdateMessage) {
|
if (content?.pollUpdateMessage) {
|
||||||
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey!)
|
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey!)
|
||||||
}
|
}
|
||||||
|
|
||||||
function normaliseKey(msgKey: proto.IMessageKey) {
|
function normaliseKey(msgKey: proto.IMessageKey) {
|
||||||
// if the reaction is from another user
|
// if the reaction is from another user
|
||||||
// we've to correctly map the key to this user's perspective
|
// 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
|
// 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
|
// we've to correct the key to be from them, or some other participant
|
||||||
msgKey.fromMe = !msgKey.fromMe
|
msgKey.fromMe = !msgKey.fromMe
|
||||||
? areJidsSameUser(msgKey.participant || msgKey.remoteJid!, meId)
|
? areJidsSameUser(msgKey.participant || msgKey.remoteJid!, meId)
|
||||||
// if the message being reacted to, was from them
|
: // if the message being reacted to, was from them
|
||||||
// fromMe automatically becomes false
|
// fromMe automatically becomes false
|
||||||
: false
|
false
|
||||||
// set the remoteJid to being the same as the chat the message came from
|
// set the remoteJid to being the same as the chat the message came from
|
||||||
msgKey.remoteJid = message.key.remoteJid
|
msgKey.remoteJid = message.key.remoteJid
|
||||||
// set participant of the message
|
// set participant of the message
|
||||||
@@ -67,33 +76,26 @@ export const isRealMessage = (message: proto.IWebMessageInfo, meId: string) => {
|
|||||||
const normalizedContent = normalizeMessageContent(message.message)
|
const normalizedContent = normalizeMessageContent(message.message)
|
||||||
const hasSomeContent = !!getContentType(normalizedContent)
|
const hasSomeContent = !!getContentType(normalizedContent)
|
||||||
return (
|
return (
|
||||||
!!normalizedContent
|
(!!normalizedContent ||
|
||||||
|| REAL_MSG_STUB_TYPES.has(message.messageStubType!)
|
REAL_MSG_STUB_TYPES.has(message.messageStubType!) ||
|
||||||
|| (
|
(REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType!) &&
|
||||||
REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType!)
|
message.messageStubParameters?.some(p => areJidsSameUser(meId, p)))) &&
|
||||||
&& 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
|
!message.key.fromMe && !message.messageStubType
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the ID of the chat from the given key.
|
* Get the ID of the chat from the given key.
|
||||||
* Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
|
* Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
|
||||||
*/
|
*/
|
||||||
export const getChatId = ({ remoteJid, participant, fromMe }: proto.IMessageKey) => {
|
export const getChatId = ({ remoteJid, participant, fromMe }: proto.IMessageKey) => {
|
||||||
if(
|
if (isJidBroadcast(remoteJid!) && !isJidStatusBroadcast(remoteJid!) && !fromMe) {
|
||||||
isJidBroadcast(remoteJid!)
|
|
||||||
&& !isJidStatusBroadcast(remoteJid!)
|
|
||||||
&& !fromMe
|
|
||||||
) {
|
|
||||||
return participant!
|
return participant!
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,22 +121,15 @@ type PollContext = {
|
|||||||
*/
|
*/
|
||||||
export function decryptPollVote(
|
export function decryptPollVote(
|
||||||
{ encPayload, encIv }: proto.Message.IPollEncValue,
|
{ encPayload, encIv }: proto.Message.IPollEncValue,
|
||||||
{
|
{ pollCreatorJid, pollMsgId, pollEncKey, voterJid }: PollContext
|
||||||
pollCreatorJid,
|
|
||||||
pollMsgId,
|
|
||||||
pollEncKey,
|
|
||||||
voterJid,
|
|
||||||
}: PollContext
|
|
||||||
) {
|
) {
|
||||||
const sign = Buffer.concat(
|
const sign = Buffer.concat([
|
||||||
[
|
|
||||||
toBinary(pollMsgId),
|
toBinary(pollMsgId),
|
||||||
toBinary(pollCreatorJid),
|
toBinary(pollCreatorJid),
|
||||||
toBinary(voterJid),
|
toBinary(voterJid),
|
||||||
toBinary('Poll Vote'),
|
toBinary('Poll Vote'),
|
||||||
new Uint8Array([1])
|
new Uint8Array([1])
|
||||||
]
|
])
|
||||||
)
|
|
||||||
|
|
||||||
const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
|
const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
|
||||||
const decKey = hmacSign(sign, key0, 'sha256')
|
const decKey = hmacSign(sign, key0, 'sha256')
|
||||||
@@ -148,17 +143,9 @@ export function decryptPollVote(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const processMessage = async(
|
const processMessage = async (
|
||||||
message: proto.IWebMessageInfo,
|
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 meId = creds.me!.id
|
||||||
const { accountSettings } = creds
|
const { accountSettings } = creds
|
||||||
@@ -166,11 +153,11 @@ const processMessage = async(
|
|||||||
const chat: Partial<Chat> = { id: jidNormalizedUser(getChatId(message.key)) }
|
const chat: Partial<Chat> = { id: jidNormalizedUser(getChatId(message.key)) }
|
||||||
const isRealMsg = isRealMessage(message, meId)
|
const isRealMsg = isRealMessage(message, meId)
|
||||||
|
|
||||||
if(isRealMsg) {
|
if (isRealMsg) {
|
||||||
chat.messages = [{ message }]
|
chat.messages = [{ message }]
|
||||||
chat.conversationTimestamp = toNumber(message.messageTimestamp)
|
chat.conversationTimestamp = toNumber(message.messageTimestamp)
|
||||||
// only increment unread count if not CIPHERTEXT and from another person
|
// only increment unread count if not CIPHERTEXT and from another person
|
||||||
if(shouldIncrementChatUnread(message)) {
|
if (shouldIncrementChatUnread(message)) {
|
||||||
chat.unreadCount = (chat.unreadCount || 0) + 1
|
chat.unreadCount = (chat.unreadCount || 0) + 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,31 +166,31 @@ const processMessage = async(
|
|||||||
|
|
||||||
// unarchive chat if it's a real message, or someone reacted to our message
|
// unarchive chat if it's a real message, or someone reacted to our message
|
||||||
// and we've the unarchive chats setting on
|
// and we've the unarchive chats setting on
|
||||||
if(
|
if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
|
||||||
(isRealMsg || content?.reactionMessage?.key?.fromMe)
|
|
||||||
&& accountSettings?.unarchiveChats
|
|
||||||
) {
|
|
||||||
chat.archived = false
|
chat.archived = false
|
||||||
chat.readOnly = false
|
chat.readOnly = false
|
||||||
}
|
}
|
||||||
|
|
||||||
const protocolMsg = content?.protocolMessage
|
const protocolMsg = content?.protocolMessage
|
||||||
if(protocolMsg) {
|
if (protocolMsg) {
|
||||||
switch (protocolMsg.type) {
|
switch (protocolMsg.type) {
|
||||||
case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
|
case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
|
||||||
const histNotification = protocolMsg.historySyncNotification!
|
const histNotification = protocolMsg.historySyncNotification!
|
||||||
const process = shouldProcessHistoryMsg
|
const process = shouldProcessHistoryMsg
|
||||||
const isLatest = !creds.processedHistoryMessages?.length
|
const isLatest = !creds.processedHistoryMessages?.length
|
||||||
|
|
||||||
logger?.info({
|
logger?.info(
|
||||||
|
{
|
||||||
histNotification,
|
histNotification,
|
||||||
process,
|
process,
|
||||||
id: message.key.id,
|
id: message.key.id,
|
||||||
isLatest,
|
isLatest
|
||||||
}, 'got history notification')
|
},
|
||||||
|
'got history notification'
|
||||||
|
)
|
||||||
|
|
||||||
if(process) {
|
if (process) {
|
||||||
if(histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
|
if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
|
||||||
ev.emit('creds.update', {
|
ev.emit('creds.update', {
|
||||||
processedHistoryMessages: [
|
processedHistoryMessages: [
|
||||||
...(creds.processedHistoryMessages || []),
|
...(creds.processedHistoryMessages || []),
|
||||||
@@ -212,17 +199,11 @@ const processMessage = async(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await downloadAndProcessHistorySyncNotification(
|
const data = await downloadAndProcessHistorySyncNotification(histNotification, options)
|
||||||
histNotification,
|
|
||||||
options
|
|
||||||
)
|
|
||||||
|
|
||||||
ev.emit('messaging-history.set', {
|
ev.emit('messaging-history.set', {
|
||||||
...data,
|
...data,
|
||||||
isLatest:
|
isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
|
||||||
histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND
|
|
||||||
? isLatest
|
|
||||||
: undefined,
|
|
||||||
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
|
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -230,12 +211,11 @@ const processMessage = async(
|
|||||||
break
|
break
|
||||||
case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
|
case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
|
||||||
const keys = protocolMsg.appStateSyncKeyShare!.keys
|
const keys = protocolMsg.appStateSyncKeyShare!.keys
|
||||||
if(keys?.length) {
|
if (keys?.length) {
|
||||||
let newAppStateSyncKeyId = ''
|
let newAppStateSyncKeyId = ''
|
||||||
await keyStore.transaction(
|
await keyStore.transaction(async () => {
|
||||||
async() => {
|
|
||||||
const newKeys: string[] = []
|
const newKeys: string[] = []
|
||||||
for(const { keyData, keyId } of keys) {
|
for (const { keyData, keyId } of keys) {
|
||||||
const strKeyId = Buffer.from(keyId!.keyId!).toString('base64')
|
const strKeyId = Buffer.from(keyId!.keyId!).toString('base64')
|
||||||
newKeys.push(strKeyId)
|
newKeys.push(strKeyId)
|
||||||
|
|
||||||
@@ -244,12 +224,8 @@ const processMessage = async(
|
|||||||
newAppStateSyncKeyId = strKeyId
|
newAppStateSyncKeyId = strKeyId
|
||||||
}
|
}
|
||||||
|
|
||||||
logger?.info(
|
logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
|
||||||
{ newAppStateSyncKeyId, newKeys },
|
})
|
||||||
'injecting new app state sync keys'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
|
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
|
||||||
} else {
|
} else {
|
||||||
@@ -276,14 +252,14 @@ const processMessage = async(
|
|||||||
break
|
break
|
||||||
case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
|
case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
|
||||||
const response = protocolMsg.peerDataOperationRequestResponseMessage!
|
const response = protocolMsg.peerDataOperationRequestResponseMessage!
|
||||||
if(response) {
|
if (response) {
|
||||||
placeholderResendCache?.del(response.stanzaId!)
|
placeholderResendCache?.del(response.stanzaId!)
|
||||||
// TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
|
// TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
|
||||||
const { peerDataOperationResult } = response
|
const { peerDataOperationResult } = response
|
||||||
for(const result of peerDataOperationResult!) {
|
for (const result of peerDataOperationResult!) {
|
||||||
const { placeholderMessageResendResponse: retryResponse } = result
|
const { placeholderMessageResendResponse: retryResponse } = result
|
||||||
//eslint-disable-next-line max-depth
|
//eslint-disable-next-line max-depth
|
||||||
if(retryResponse) {
|
if (retryResponse) {
|
||||||
const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes!)
|
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
|
// wait till another upsert event is available, don't want it to be part of the PDO response message
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -298,9 +274,7 @@ const processMessage = async(
|
|||||||
}
|
}
|
||||||
|
|
||||||
case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
|
case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
|
||||||
ev.emit(
|
ev.emit('messages.update', [
|
||||||
'messages.update',
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
// flip the sender / fromMe properties because they're in the perspective of the sender
|
// flip the sender / fromMe properties because they're in the perspective of the sender
|
||||||
key: { ...message.key, id: protocolMsg.key?.id },
|
key: { ...message.key, id: protocolMsg.key?.id },
|
||||||
@@ -315,26 +289,26 @@ const processMessage = async(
|
|||||||
: message.messageTimestamp
|
: message.messageTimestamp
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
])
|
||||||
)
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
} else if(content?.reactionMessage) {
|
} else if (content?.reactionMessage) {
|
||||||
const reaction: proto.IReaction = {
|
const reaction: proto.IReaction = {
|
||||||
...content.reactionMessage,
|
...content.reactionMessage,
|
||||||
key: message.key,
|
key: message.key
|
||||||
}
|
}
|
||||||
ev.emit('messages.reaction', [{
|
ev.emit('messages.reaction', [
|
||||||
|
{
|
||||||
reaction,
|
reaction,
|
||||||
key: content.reactionMessage?.key!,
|
key: content.reactionMessage?.key!
|
||||||
}])
|
}
|
||||||
} else if(message.messageStubType) {
|
])
|
||||||
|
} else if (message.messageStubType) {
|
||||||
const jid = message.key?.remoteJid!
|
const jid = message.key?.remoteJid!
|
||||||
//let actor = whatsappID (message.participant)
|
//let actor = whatsappID (message.participant)
|
||||||
let participants: string[]
|
let participants: string[]
|
||||||
const emitParticipantsUpdate = (action: ParticipantAction) => (
|
const emitParticipantsUpdate = (action: ParticipantAction) =>
|
||||||
ev.emit('group-participants.update', { id: jid, author: message.participant!, participants, action })
|
ev.emit('group-participants.update', { id: jid, author: message.participant!, participants, action })
|
||||||
)
|
|
||||||
const emitGroupUpdate = (update: Partial<GroupMetadata>) => {
|
const emitGroupUpdate = (update: Partial<GroupMetadata>) => {
|
||||||
ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ?? undefined }])
|
ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ?? undefined }])
|
||||||
}
|
}
|
||||||
@@ -355,7 +329,7 @@ const processMessage = async(
|
|||||||
participants = message.messageStubParameters || []
|
participants = message.messageStubParameters || []
|
||||||
emitParticipantsUpdate('remove')
|
emitParticipantsUpdate('remove')
|
||||||
// mark the chat read only if you left the group
|
// mark the chat read only if you left the group
|
||||||
if(participantsIncludesMe()) {
|
if (participantsIncludesMe()) {
|
||||||
chat.readOnly = true
|
chat.readOnly = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -364,7 +338,7 @@ const processMessage = async(
|
|||||||
case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
|
case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
|
||||||
case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
|
case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
|
||||||
participants = message.messageStubParameters || []
|
participants = message.messageStubParameters || []
|
||||||
if(participantsIncludesMe()) {
|
if (participantsIncludesMe()) {
|
||||||
chat.readOnly = false
|
chat.readOnly = false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -415,7 +389,6 @@ const processMessage = async(
|
|||||||
emitGroupRequestJoin(participant, action, method)
|
emitGroupRequestJoin(participant, action, method)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
} /* else if(content?.pollUpdateMessage) {
|
} /* else if(content?.pollUpdateMessage) {
|
||||||
const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
|
const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
|
||||||
// we need to fetch the poll creation message to get the poll enc key
|
// 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])
|
ev.emit('chats.update', [chat])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,39 @@
|
|||||||
import { chunk } from 'lodash'
|
import { chunk } from 'lodash'
|
||||||
import { KEY_BUNDLE_TYPE } from '../Defaults'
|
import { KEY_BUNDLE_TYPE } from '../Defaults'
|
||||||
import { SignalRepository } from '../Types'
|
import { SignalRepository } from '../Types'
|
||||||
import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth'
|
import {
|
||||||
import { assertNodeErrorFree, BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, jidDecode, JidWithDevice, S_WHATSAPP_NET } from '../WABinary'
|
AuthenticationCreds,
|
||||||
|
AuthenticationState,
|
||||||
|
KeyPair,
|
||||||
|
SignalIdentity,
|
||||||
|
SignalKeyStore,
|
||||||
|
SignedKeyPair
|
||||||
|
} from '../Types/Auth'
|
||||||
|
import {
|
||||||
|
assertNodeErrorFree,
|
||||||
|
BinaryNode,
|
||||||
|
getBinaryNodeChild,
|
||||||
|
getBinaryNodeChildBuffer,
|
||||||
|
getBinaryNodeChildren,
|
||||||
|
getBinaryNodeChildUInt,
|
||||||
|
jidDecode,
|
||||||
|
JidWithDevice,
|
||||||
|
S_WHATSAPP_NET
|
||||||
|
} from '../WABinary'
|
||||||
import { DeviceListData, ParsedDeviceInfo, USyncQueryResultList } from '../WAUSync'
|
import { DeviceListData, ParsedDeviceInfo, USyncQueryResultList } from '../WAUSync'
|
||||||
import { Curve, generateSignalPubKey } from './crypto'
|
import { Curve, generateSignalPubKey } from './crypto'
|
||||||
import { encodeBigEndian } from './generics'
|
import { encodeBigEndian } from './generics'
|
||||||
|
|
||||||
export const createSignalIdentity = (
|
export const createSignalIdentity = (wid: string, accountSignatureKey: Uint8Array): SignalIdentity => {
|
||||||
wid: string,
|
|
||||||
accountSignatureKey: Uint8Array
|
|
||||||
): SignalIdentity => {
|
|
||||||
return {
|
return {
|
||||||
identifier: { name: wid, deviceId: 0 },
|
identifier: { name: wid, deviceId: 0 },
|
||||||
identifierKey: generateSignalPubKey(accountSignatureKey)
|
identifierKey: generateSignalPubKey(accountSignatureKey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getPreKeys = async({ get }: SignalKeyStore, min: number, limit: number) => {
|
export const getPreKeys = async ({ get }: SignalKeyStore, min: number, limit: number) => {
|
||||||
const idList: string[] = []
|
const idList: string[] = []
|
||||||
for(let id = min; id < limit;id++) {
|
for (let id = min; id < limit; id++) {
|
||||||
idList.push(id.toString())
|
idList.push(id.toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,9 +44,9 @@ export const generateOrGetPreKeys = (creds: AuthenticationCreds, range: number)
|
|||||||
const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId
|
const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId
|
||||||
const remaining = range - avaliable
|
const remaining = range - avaliable
|
||||||
const lastPreKeyId = creds.nextPreKeyId + remaining - 1
|
const lastPreKeyId = creds.nextPreKeyId + remaining - 1
|
||||||
const newPreKeys: { [id: number]: KeyPair } = { }
|
const newPreKeys: { [id: number]: KeyPair } = {}
|
||||||
if(remaining > 0) {
|
if (remaining > 0) {
|
||||||
for(let i = creds.nextPreKeyId;i <= lastPreKeyId;i++) {
|
for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
|
||||||
newPreKeys[i] = Curve.generateKeyPair()
|
newPreKeys[i] = Curve.generateKeyPair()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,46 +54,40 @@ export const generateOrGetPreKeys = (creds: AuthenticationCreds, range: number)
|
|||||||
return {
|
return {
|
||||||
newPreKeys,
|
newPreKeys,
|
||||||
lastPreKeyId,
|
lastPreKeyId,
|
||||||
preKeysRange: [creds.firstUnuploadedPreKeyId, range] as const,
|
preKeysRange: [creds.firstUnuploadedPreKeyId, range] as const
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const xmppSignedPreKey = (key: SignedKeyPair): BinaryNode => (
|
export const xmppSignedPreKey = (key: SignedKeyPair): BinaryNode => ({
|
||||||
{
|
|
||||||
tag: 'skey',
|
tag: 'skey',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{ tag: 'id', attrs: { }, content: encodeBigEndian(key.keyId, 3) },
|
{ tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
|
||||||
{ tag: 'value', attrs: { }, content: key.keyPair.public },
|
{ tag: 'value', attrs: {}, content: key.keyPair.public },
|
||||||
{ tag: 'signature', attrs: { }, content: key.signature }
|
{ tag: 'signature', attrs: {}, content: key.signature }
|
||||||
]
|
]
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
export const xmppPreKey = (pair: KeyPair, id: number): BinaryNode => (
|
export const xmppPreKey = (pair: KeyPair, id: number): BinaryNode => ({
|
||||||
{
|
|
||||||
tag: 'key',
|
tag: 'key',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{ tag: 'id', attrs: { }, content: encodeBigEndian(id, 3) },
|
{ tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
|
||||||
{ tag: 'value', attrs: { }, content: pair.public }
|
{ tag: 'value', attrs: {}, content: pair.public }
|
||||||
]
|
]
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
export const parseAndInjectE2ESessions = async(
|
export const parseAndInjectE2ESessions = async (node: BinaryNode, repository: SignalRepository) => {
|
||||||
node: BinaryNode,
|
const extractKey = (key: BinaryNode) =>
|
||||||
repository: SignalRepository
|
key
|
||||||
) => {
|
? {
|
||||||
const extractKey = (key: BinaryNode) => (
|
|
||||||
key ? ({
|
|
||||||
keyId: getBinaryNodeChildUInt(key, 'id', 3)!,
|
keyId: getBinaryNodeChildUInt(key, 'id', 3)!,
|
||||||
publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')!),
|
publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')!),
|
||||||
signature: getBinaryNodeChildBuffer(key, 'signature')!,
|
signature: getBinaryNodeChildBuffer(key, 'signature')!
|
||||||
}) : undefined
|
}
|
||||||
)
|
: undefined
|
||||||
const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user')
|
const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user')
|
||||||
for(const node of nodes) {
|
for (const node of nodes) {
|
||||||
assertNodeErrorFree(node)
|
assertNodeErrorFree(node)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,10 +98,9 @@ export const parseAndInjectE2ESessions = async(
|
|||||||
// It's rare case when you need to E2E sessions for so many users, but it's possible
|
// It's rare case when you need to E2E sessions for so many users, but it's possible
|
||||||
const chunkSize = 100
|
const chunkSize = 100
|
||||||
const chunks = chunk(nodes, chunkSize)
|
const chunks = chunk(nodes, chunkSize)
|
||||||
for(const nodesChunk of chunks) {
|
for (const nodesChunk of chunks) {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
nodesChunk.map(
|
nodesChunk.map(async node => {
|
||||||
async node => {
|
|
||||||
const signedKey = getBinaryNodeChild(node, 'skey')!
|
const signedKey = getBinaryNodeChild(node, 'skey')!
|
||||||
const key = getBinaryNodeChild(node, 'key')!
|
const key = getBinaryNodeChild(node, 'key')!
|
||||||
const identity = getBinaryNodeChildBuffer(node, 'identity')!
|
const identity = getBinaryNodeChildBuffer(node, 'identity')!
|
||||||
@@ -109,8 +116,7 @@ export const parseAndInjectE2ESessions = async(
|
|||||||
preKey: extractKey(key)!
|
preKey: extractKey(key)!
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
})
|
||||||
)
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -120,14 +126,13 @@ export const extractDeviceJids = (result: USyncQueryResultList[], myJid: string,
|
|||||||
|
|
||||||
const extracted: JidWithDevice[] = []
|
const extracted: JidWithDevice[] = []
|
||||||
|
|
||||||
|
for (const userResult of result) {
|
||||||
for(const userResult of result) {
|
const { devices, id } = userResult as { devices: ParsedDeviceInfo; id: string }
|
||||||
const { devices, id } = userResult as { devices: ParsedDeviceInfo, id: string }
|
|
||||||
const { user } = jidDecode(id)!
|
const { user } = jidDecode(id)!
|
||||||
const deviceList = devices?.deviceList as DeviceListData[]
|
const deviceList = devices?.deviceList as DeviceListData[]
|
||||||
if(Array.isArray(deviceList)) {
|
if (Array.isArray(deviceList)) {
|
||||||
for(const { id: device, keyIndex } of deviceList) {
|
for (const { id: device, keyIndex } of deviceList) {
|
||||||
if(
|
if (
|
||||||
(!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
|
(!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
|
||||||
(myUser !== user || myDevice !== device) && // either different user or if me user, not this device
|
(myUser !== user || myDevice !== device) && // either different user or if me user, not this device
|
||||||
(device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
|
(device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
|
||||||
@@ -145,7 +150,7 @@ export const extractDeviceJids = (result: USyncQueryResultList[], myJid: string,
|
|||||||
* get the next N keys for upload or processing
|
* get the next N keys for upload or processing
|
||||||
* @param count number of pre-keys to get or generate
|
* @param count number of pre-keys to get or generate
|
||||||
*/
|
*/
|
||||||
export const getNextPreKeys = async({ creds, keys }: AuthenticationState, count: number) => {
|
export const getNextPreKeys = async ({ creds, keys }: AuthenticationState, count: number) => {
|
||||||
const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count)
|
const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count)
|
||||||
|
|
||||||
const update: Partial<AuthenticationCreds> = {
|
const update: Partial<AuthenticationCreds> = {
|
||||||
@@ -160,7 +165,7 @@ export const getNextPreKeys = async({ creds, keys }: AuthenticationState, count:
|
|||||||
return { update, preKeys }
|
return { update, preKeys }
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getNextPreKeysNode = async(state: AuthenticationState, count: number) => {
|
export const getNextPreKeysNode = async (state: AuthenticationState, count: number) => {
|
||||||
const { creds } = state
|
const { creds } = state
|
||||||
const { update, preKeys } = await getNextPreKeys(state, count)
|
const { update, preKeys } = await getNextPreKeys(state, count)
|
||||||
|
|
||||||
@@ -169,13 +174,13 @@ export const getNextPreKeysNode = async(state: AuthenticationState, count: numbe
|
|||||||
attrs: {
|
attrs: {
|
||||||
xmlns: 'encrypt',
|
xmlns: 'encrypt',
|
||||||
type: 'set',
|
type: 'set',
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{ tag: 'registration', attrs: { }, content: encodeBigEndian(creds.registrationId) },
|
{ tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
|
||||||
{ tag: 'type', attrs: { }, content: KEY_BUNDLE_TYPE },
|
{ tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
|
||||||
{ tag: 'identity', attrs: { }, content: creds.signedIdentityKey.public },
|
{ tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
|
||||||
{ tag: 'list', attrs: { }, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
|
{ tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
|
||||||
xmppSignedPreKey(creds.signedPreKey)
|
xmppSignedPreKey(creds.signedPreKey)
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ const fileLocks = new Map<string, Mutex>()
|
|||||||
// Get or create a mutex for a specific file path
|
// Get or create a mutex for a specific file path
|
||||||
const getFileLock = (path: string): Mutex => {
|
const getFileLock = (path: string): Mutex => {
|
||||||
let mutex = fileLocks.get(path)
|
let mutex = fileLocks.get(path)
|
||||||
if(!mutex) {
|
if (!mutex) {
|
||||||
mutex = new Mutex()
|
mutex = new Mutex()
|
||||||
fileLocks.set(path, mutex)
|
fileLocks.set(path, mutex)
|
||||||
}
|
}
|
||||||
@@ -30,13 +30,15 @@ const getFileLock = (path: string): Mutex => {
|
|||||||
* Again, I wouldn't endorse this for any production level use other than perhaps a bot.
|
* Again, I wouldn't endorse this for any production level use other than perhaps a bot.
|
||||||
* Would recommend writing an auth state for use with a proper SQL or No-SQL DB
|
* Would recommend writing an auth state for use with a proper SQL or No-SQL DB
|
||||||
* */
|
* */
|
||||||
export const useMultiFileAuthState = async(folder: string): Promise<{ state: AuthenticationState, saveCreds: () => Promise<void> }> => {
|
export const useMultiFileAuthState = async (
|
||||||
|
folder: string
|
||||||
|
): Promise<{ state: AuthenticationState; saveCreds: () => Promise<void> }> => {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const writeData = async(data: any, file: string) => {
|
const writeData = async (data: any, file: string) => {
|
||||||
const filePath = join(folder, fixFileName(file)!)
|
const filePath = join(folder, fixFileName(file)!)
|
||||||
const mutex = getFileLock(filePath)
|
const mutex = getFileLock(filePath)
|
||||||
|
|
||||||
return mutex.acquire().then(async(release) => {
|
return mutex.acquire().then(async release => {
|
||||||
try {
|
try {
|
||||||
await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer))
|
await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer))
|
||||||
} finally {
|
} finally {
|
||||||
@@ -45,12 +47,12 @@ export const useMultiFileAuthState = async(folder: string): Promise<{ state: Aut
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const readData = async(file: string) => {
|
const readData = async (file: string) => {
|
||||||
try {
|
try {
|
||||||
const filePath = join(folder, fixFileName(file)!)
|
const filePath = join(folder, fixFileName(file)!)
|
||||||
const mutex = getFileLock(filePath)
|
const mutex = getFileLock(filePath)
|
||||||
|
|
||||||
return await mutex.acquire().then(async(release) => {
|
return await mutex.acquire().then(async release => {
|
||||||
try {
|
try {
|
||||||
const data = await readFile(filePath, { encoding: 'utf-8' })
|
const data = await readFile(filePath, { encoding: 'utf-8' })
|
||||||
return JSON.parse(data, BufferJSON.reviver)
|
return JSON.parse(data, BufferJSON.reviver)
|
||||||
@@ -58,32 +60,33 @@ export const useMultiFileAuthState = async(folder: string): Promise<{ state: Aut
|
|||||||
release()
|
release()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeData = async(file: string) => {
|
const removeData = async (file: string) => {
|
||||||
try {
|
try {
|
||||||
const filePath = join(folder, fixFileName(file)!)
|
const filePath = join(folder, fixFileName(file)!)
|
||||||
const mutex = getFileLock(filePath)
|
const mutex = getFileLock(filePath)
|
||||||
|
|
||||||
return mutex.acquire().then(async(release) => {
|
return mutex.acquire().then(async release => {
|
||||||
try {
|
try {
|
||||||
await unlink(filePath)
|
await unlink(filePath)
|
||||||
} catch{
|
} catch {
|
||||||
} finally {
|
} finally {
|
||||||
release()
|
release()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch{
|
} catch {}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const folderInfo = await stat(folder).catch(() => { })
|
const folderInfo = await stat(folder).catch(() => {})
|
||||||
if(folderInfo) {
|
if (folderInfo) {
|
||||||
if(!folderInfo.isDirectory()) {
|
if (!folderInfo.isDirectory()) {
|
||||||
throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
|
throw new Error(
|
||||||
|
`found something that is not a directory at ${folder}, either delete it or specify a different location`
|
||||||
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
await mkdir(folder, { recursive: true })
|
await mkdir(folder, { recursive: true })
|
||||||
@@ -91,33 +94,31 @@ export const useMultiFileAuthState = async(folder: string): Promise<{ state: Aut
|
|||||||
|
|
||||||
const fixFileName = (file?: string) => file?.replace(/\//g, '__')?.replace(/:/g, '-')
|
const fixFileName = (file?: string) => file?.replace(/\//g, '__')?.replace(/:/g, '-')
|
||||||
|
|
||||||
const creds: AuthenticationCreds = await readData('creds.json') || initAuthCreds()
|
const creds: AuthenticationCreds = (await readData('creds.json')) || initAuthCreds()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state: {
|
state: {
|
||||||
creds,
|
creds,
|
||||||
keys: {
|
keys: {
|
||||||
get: async(type, ids) => {
|
get: async (type, ids) => {
|
||||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
ids.map(
|
ids.map(async id => {
|
||||||
async id => {
|
|
||||||
let value = await readData(`${type}-${id}.json`)
|
let value = await readData(`${type}-${id}.json`)
|
||||||
if(type === 'app-state-sync-key' && value) {
|
if (type === 'app-state-sync-key' && value) {
|
||||||
value = proto.Message.AppStateSyncKeyData.fromObject(value)
|
value = proto.Message.AppStateSyncKeyData.fromObject(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
data[id] = value
|
data[id] = value
|
||||||
}
|
})
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return data
|
return data
|
||||||
},
|
},
|
||||||
set: async(data) => {
|
set: async data => {
|
||||||
const tasks: Promise<void>[] = []
|
const tasks: Promise<void>[] = []
|
||||||
for(const category in data) {
|
for (const category in data) {
|
||||||
for(const id in data[category]) {
|
for (const id in data[category]) {
|
||||||
const value = data[category][id]
|
const value = data[category][id]
|
||||||
const file = `${category}-${id}.json`
|
const file = `${category}-${id}.json`
|
||||||
tasks.push(value ? writeData(value, file) : removeData(file))
|
tasks.push(value ? writeData(value, file) : removeData(file))
|
||||||
@@ -128,7 +129,7 @@ export const useMultiFileAuthState = async(folder: string): Promise<{ state: Aut
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
saveCreds: async() => {
|
saveCreds: async () => {
|
||||||
return writeData(creds, 'creds.json')
|
return writeData(creds, 'creds.json')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
|
|||||||
appVersion: {
|
appVersion: {
|
||||||
primary: config.version[0],
|
primary: config.version[0],
|
||||||
secondary: config.version[1],
|
secondary: config.version[1],
|
||||||
tertiary: config.version[2],
|
tertiary: config.version[2]
|
||||||
},
|
},
|
||||||
platform: proto.ClientPayload.UserAgent.Platform.WEB,
|
platform: proto.ClientPayload.UserAgent.Platform.WEB,
|
||||||
releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
|
releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
|
||||||
@@ -23,30 +23,29 @@ const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
|
|||||||
localeLanguageIso6391: 'en',
|
localeLanguageIso6391: 'en',
|
||||||
mnc: '000',
|
mnc: '000',
|
||||||
mcc: '000',
|
mcc: '000',
|
||||||
localeCountryIso31661Alpha2: config.countryCode,
|
localeCountryIso31661Alpha2: config.countryCode
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const PLATFORM_MAP = {
|
const PLATFORM_MAP = {
|
||||||
'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
|
'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
|
||||||
'Windows': proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
|
Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
|
||||||
}
|
}
|
||||||
|
|
||||||
const getWebInfo = (config: SocketConfig): proto.ClientPayload.IWebInfo => {
|
const getWebInfo = (config: SocketConfig): proto.ClientPayload.IWebInfo => {
|
||||||
let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
|
let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
|
||||||
if(config.syncFullHistory && PLATFORM_MAP[config.browser[0]]) {
|
if (config.syncFullHistory && PLATFORM_MAP[config.browser[0]]) {
|
||||||
webSubPlatform = PLATFORM_MAP[config.browser[0]]
|
webSubPlatform = PLATFORM_MAP[config.browser[0]]
|
||||||
}
|
}
|
||||||
|
|
||||||
return { webSubPlatform }
|
return { webSubPlatform }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const getClientPayload = (config: SocketConfig) => {
|
const getClientPayload = (config: SocketConfig) => {
|
||||||
const payload: proto.IClientPayload = {
|
const payload: proto.IClientPayload = {
|
||||||
connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
|
connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
|
||||||
connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
|
connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
|
||||||
userAgent: getUserAgent(config),
|
userAgent: getUserAgent(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
payload.webInfo = getWebInfo(config)
|
payload.webInfo = getWebInfo(config)
|
||||||
@@ -54,7 +53,6 @@ const getClientPayload = (config: SocketConfig) => {
|
|||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
|
export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
|
||||||
const { user, device } = jidDecode(userJid)!
|
const { user, device } = jidDecode(userJid)!
|
||||||
const payload: proto.IClientPayload = {
|
const payload: proto.IClientPayload = {
|
||||||
@@ -62,7 +60,7 @@ export const generateLoginNode = (userJid: string, config: SocketConfig): proto.
|
|||||||
passive: false,
|
passive: false,
|
||||||
pull: true,
|
pull: true,
|
||||||
username: +user,
|
username: +user,
|
||||||
device: device,
|
device: device
|
||||||
}
|
}
|
||||||
return proto.ClientPayload.fromObject(payload)
|
return proto.ClientPayload.fromObject(payload)
|
||||||
}
|
}
|
||||||
@@ -85,7 +83,7 @@ export const generateRegistrationNode = (
|
|||||||
const companion: proto.IDeviceProps = {
|
const companion: proto.IDeviceProps = {
|
||||||
os: config.browser[0],
|
os: config.browser[0],
|
||||||
platformType: getPlatformType(config.browser[1]),
|
platformType: getPlatformType(config.browser[1]),
|
||||||
requireFullSync: config.syncFullHistory,
|
requireFullSync: config.syncFullHistory
|
||||||
}
|
}
|
||||||
|
|
||||||
const companionProto = proto.DeviceProps.encode(companion).finish()
|
const companionProto = proto.DeviceProps.encode(companion).finish()
|
||||||
@@ -102,8 +100,8 @@ export const generateRegistrationNode = (
|
|||||||
eIdent: signedIdentityKey.public,
|
eIdent: signedIdentityKey.public,
|
||||||
eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
|
eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
|
||||||
eSkeyVal: signedPreKey.keyPair.public,
|
eSkeyVal: signedPreKey.keyPair.public,
|
||||||
eSkeySig: signedPreKey.signature,
|
eSkeySig: signedPreKey.signature
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return proto.ClientPayload.fromObject(registerPayload)
|
return proto.ClientPayload.fromObject(registerPayload)
|
||||||
@@ -111,7 +109,11 @@ export const generateRegistrationNode = (
|
|||||||
|
|
||||||
export const configureSuccessfulPairing = (
|
export const configureSuccessfulPairing = (
|
||||||
stanza: BinaryNode,
|
stanza: BinaryNode,
|
||||||
{ advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
{
|
||||||
|
advSecretKey,
|
||||||
|
signedIdentityKey,
|
||||||
|
signalIdentities
|
||||||
|
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
||||||
) => {
|
) => {
|
||||||
const msgId = stanza.attrs.id
|
const msgId = stanza.attrs.id
|
||||||
|
|
||||||
@@ -122,7 +124,7 @@ export const configureSuccessfulPairing = (
|
|||||||
const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device')
|
const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device')
|
||||||
const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz')
|
const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz')
|
||||||
|
|
||||||
if(!deviceIdentityNode || !deviceNode) {
|
if (!deviceIdentityNode || !deviceNode) {
|
||||||
throw new Boom('Missing device-identity or device in pair success node', { data: stanza })
|
throw new Boom('Missing device-identity or device in pair success node', { data: stanza })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,20 +134,20 @@ export const configureSuccessfulPairing = (
|
|||||||
const { details, hmac } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
|
const { details, hmac } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
|
||||||
// check HMAC matches
|
// check HMAC matches
|
||||||
const advSign = hmacSign(details!, Buffer.from(advSecretKey, 'base64'))
|
const advSign = hmacSign(details!, Buffer.from(advSecretKey, 'base64'))
|
||||||
if(Buffer.compare(hmac!, advSign) !== 0) {
|
if (Buffer.compare(hmac!, advSign) !== 0) {
|
||||||
throw new Boom('Invalid account signature')
|
throw new Boom('Invalid account signature')
|
||||||
}
|
}
|
||||||
|
|
||||||
const account = proto.ADVSignedDeviceIdentity.decode(details!)
|
const account = proto.ADVSignedDeviceIdentity.decode(details!)
|
||||||
const { accountSignatureKey, accountSignature, details: deviceDetails } = account
|
const { accountSignatureKey, accountSignature, details: deviceDetails } = account
|
||||||
// verify the device signature matches
|
// verify the device signature matches
|
||||||
const accountMsg = Buffer.concat([ Buffer.from([6, 0]), deviceDetails!, signedIdentityKey.public ])
|
const accountMsg = Buffer.concat([Buffer.from([6, 0]), deviceDetails!, signedIdentityKey.public])
|
||||||
if(!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
|
if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
|
||||||
throw new Boom('Failed to verify account signature')
|
throw new Boom('Failed to verify account signature')
|
||||||
}
|
}
|
||||||
|
|
||||||
// sign the details with our identity key
|
// sign the details with our identity key
|
||||||
const deviceMsg = Buffer.concat([ Buffer.from([6, 1]), deviceDetails!, signedIdentityKey.public, accountSignatureKey! ])
|
const deviceMsg = Buffer.concat([Buffer.from([6, 1]), deviceDetails!, signedIdentityKey.public, accountSignatureKey!])
|
||||||
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
|
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
|
||||||
|
|
||||||
const identity = createSignalIdentity(jid, accountSignatureKey!)
|
const identity = createSignalIdentity(jid, accountSignatureKey!)
|
||||||
@@ -158,12 +160,12 @@ export const configureSuccessfulPairing = (
|
|||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'result',
|
type: 'result',
|
||||||
id: msgId,
|
id: msgId
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'pair-device-sign',
|
tag: 'pair-device-sign',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'device-identity',
|
tag: 'device-identity',
|
||||||
@@ -178,10 +180,7 @@ export const configureSuccessfulPairing = (
|
|||||||
const authUpdate: Partial<AuthenticationCreds> = {
|
const authUpdate: Partial<AuthenticationCreds> = {
|
||||||
account,
|
account,
|
||||||
me: { id: jid, name: bizName },
|
me: { id: jid, name: bizName },
|
||||||
signalIdentities: [
|
signalIdentities: [...(signalIdentities || []), identity],
|
||||||
...(signalIdentities || []),
|
|
||||||
identity
|
|
||||||
],
|
|
||||||
platform: platformNode?.attrs.name
|
platform: platformNode?.attrs.name
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,18 +190,13 @@ export const configureSuccessfulPairing = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const encodeSignedDeviceIdentity = (
|
export const encodeSignedDeviceIdentity = (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => {
|
||||||
account: proto.IADVSignedDeviceIdentity,
|
|
||||||
includeSignatureKey: boolean
|
|
||||||
) => {
|
|
||||||
account = { ...account }
|
account = { ...account }
|
||||||
// set to null if we are not to include the signature key
|
// set to null if we are not to include the signature key
|
||||||
// or if we are including the signature key but it is empty
|
// or if we are including the signature key but it is empty
|
||||||
if(!includeSignatureKey || !account.accountSignatureKey?.length) {
|
if (!includeSignatureKey || !account.accountSignatureKey?.length) {
|
||||||
account.accountSignatureKey = null
|
account.accountSignatureKey = null
|
||||||
}
|
}
|
||||||
|
|
||||||
return proto.ADVSignedDeviceIdentity
|
return proto.ADVSignedDeviceIdentity.encode(account).finish()
|
||||||
.encode(account)
|
|
||||||
.finish()
|
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -6,10 +6,11 @@ import type { BinaryNode, BinaryNodeCodingOptions } from './types'
|
|||||||
|
|
||||||
const inflatePromise = promisify(inflate)
|
const inflatePromise = promisify(inflate)
|
||||||
|
|
||||||
export const decompressingIfRequired = async(buffer: Buffer) => {
|
export const decompressingIfRequired = async (buffer: Buffer) => {
|
||||||
if(2 & buffer.readUInt8()) {
|
if (2 & buffer.readUInt8()) {
|
||||||
buffer = await inflatePromise(buffer.slice(1))
|
buffer = await inflatePromise(buffer.slice(1))
|
||||||
} else { // nodes with no compression have a 0x00 prefix, we remove that
|
} else {
|
||||||
|
// nodes with no compression have a 0x00 prefix, we remove that
|
||||||
buffer = buffer.slice(1)
|
buffer = buffer.slice(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,7 +25,7 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts
|
const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts
|
||||||
|
|
||||||
const checkEOS = (length: number) => {
|
const checkEOS = (length: number) => {
|
||||||
if(indexRef.index + length > buffer.length) {
|
if (indexRef.index + length > buffer.length) {
|
||||||
throw new Error('end of stream')
|
throw new Error('end of stream')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -54,7 +55,7 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
const readInt = (n: number, littleEndian = false) => {
|
const readInt = (n: number, littleEndian = false) => {
|
||||||
checkEOS(n)
|
checkEOS(n)
|
||||||
let val = 0
|
let val = 0
|
||||||
for(let i = 0; i < n; i++) {
|
for (let i = 0; i < n; i++) {
|
||||||
const shift = littleEndian ? i : n - 1 - i
|
const shift = littleEndian ? i : n - 1 - i
|
||||||
val |= next() << (shift * 8)
|
val |= next() << (shift * 8)
|
||||||
}
|
}
|
||||||
@@ -68,7 +69,7 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const unpackHex = (value: number) => {
|
const unpackHex = (value: number) => {
|
||||||
if(value >= 0 && value < 16) {
|
if (value >= 0 && value < 16) {
|
||||||
return value < 10 ? '0'.charCodeAt(0) + value : 'A'.charCodeAt(0) + value - 10
|
return value < 10 ? '0'.charCodeAt(0) + value : 'A'.charCodeAt(0) + value - 10
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +77,7 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const unpackNibble = (value: number) => {
|
const unpackNibble = (value: number) => {
|
||||||
if(value >= 0 && value <= 9) {
|
if (value >= 0 && value <= 9) {
|
||||||
return '0'.charCodeAt(0) + value
|
return '0'.charCodeAt(0) + value
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,9 +94,9 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const unpackByte = (tag: number, value: number) => {
|
const unpackByte = (tag: number, value: number) => {
|
||||||
if(tag === TAGS.NIBBLE_8) {
|
if (tag === TAGS.NIBBLE_8) {
|
||||||
return unpackNibble(value)
|
return unpackNibble(value)
|
||||||
} else if(tag === TAGS.HEX_8) {
|
} else if (tag === TAGS.HEX_8) {
|
||||||
return unpackHex(value)
|
return unpackHex(value)
|
||||||
} else {
|
} else {
|
||||||
throw new Error('unknown tag: ' + tag)
|
throw new Error('unknown tag: ' + tag)
|
||||||
@@ -106,13 +107,13 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
const startByte = readByte()
|
const startByte = readByte()
|
||||||
let value = ''
|
let value = ''
|
||||||
|
|
||||||
for(let i = 0; i < (startByte & 127); i++) {
|
for (let i = 0; i < (startByte & 127); i++) {
|
||||||
const curByte = readByte()
|
const curByte = readByte()
|
||||||
value += String.fromCharCode(unpackByte(tag, (curByte & 0xf0) >> 4))
|
value += String.fromCharCode(unpackByte(tag, (curByte & 0xf0) >> 4))
|
||||||
value += String.fromCharCode(unpackByte(tag, curByte & 0x0f))
|
value += String.fromCharCode(unpackByte(tag, curByte & 0x0f))
|
||||||
}
|
}
|
||||||
|
|
||||||
if(startByte >> 7 !== 0) {
|
if (startByte >> 7 !== 0) {
|
||||||
value = value.slice(0, -1)
|
value = value.slice(0, -1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,7 +140,7 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
const readJidPair = () => {
|
const readJidPair = () => {
|
||||||
const i = readString(readByte())
|
const i = readString(readByte())
|
||||||
const j = readString(readByte())
|
const j = readString(readByte())
|
||||||
if(j) {
|
if (j) {
|
||||||
return (i || '') + '@' + j
|
return (i || '') + '@' + j
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,15 +154,11 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
const device = readByte()
|
const device = readByte()
|
||||||
const user = readString(readByte())
|
const user = readString(readByte())
|
||||||
|
|
||||||
return jidEncode(
|
return jidEncode(user, domainType === 0 || domainType === 128 ? 's.whatsapp.net' : 'lid', device)
|
||||||
user,
|
|
||||||
domainType === 0 || domainType === 128 ? 's.whatsapp.net' : 'lid',
|
|
||||||
device
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const readString = (tag: number): string => {
|
const readString = (tag: number): string => {
|
||||||
if(tag >= 1 && tag < SINGLE_BYTE_TOKENS.length) {
|
if (tag >= 1 && tag < SINGLE_BYTE_TOKENS.length) {
|
||||||
return SINGLE_BYTE_TOKENS[tag] || ''
|
return SINGLE_BYTE_TOKENS[tag] || ''
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,7 +191,7 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
const readList = (tag: number) => {
|
const readList = (tag: number) => {
|
||||||
const items: BinaryNode[] = []
|
const items: BinaryNode[] = []
|
||||||
const size = readListSize(tag)
|
const size = readListSize(tag)
|
||||||
for(let i = 0;i < size;i++) {
|
for (let i = 0; i < size; i++) {
|
||||||
items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef))
|
items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,12 +200,12 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
|
|
||||||
const getTokenDouble = (index1: number, index2: number) => {
|
const getTokenDouble = (index1: number, index2: number) => {
|
||||||
const dict = DOUBLE_BYTE_TOKENS[index1]
|
const dict = DOUBLE_BYTE_TOKENS[index1]
|
||||||
if(!dict) {
|
if (!dict) {
|
||||||
throw new Error(`Invalid double token dict (${index1})`)
|
throw new Error(`Invalid double token dict (${index1})`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const value = dict[index2]
|
const value = dict[index2]
|
||||||
if(typeof value === 'undefined') {
|
if (typeof value === 'undefined') {
|
||||||
throw new Error(`Invalid double token (${index2})`)
|
throw new Error(`Invalid double token (${index2})`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,28 +214,28 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
|
|
||||||
const listSize = readListSize(readByte())
|
const listSize = readListSize(readByte())
|
||||||
const header = readString(readByte())
|
const header = readString(readByte())
|
||||||
if(!listSize || !header.length) {
|
if (!listSize || !header.length) {
|
||||||
throw new Error('invalid node')
|
throw new Error('invalid node')
|
||||||
}
|
}
|
||||||
|
|
||||||
const attrs: BinaryNode['attrs'] = { }
|
const attrs: BinaryNode['attrs'] = {}
|
||||||
let data: BinaryNode['content']
|
let data: BinaryNode['content']
|
||||||
if(listSize === 0 || !header) {
|
if (listSize === 0 || !header) {
|
||||||
throw new Error('invalid node')
|
throw new Error('invalid node')
|
||||||
}
|
}
|
||||||
|
|
||||||
// read the attributes in
|
// read the attributes in
|
||||||
const attributesLength = (listSize - 1) >> 1
|
const attributesLength = (listSize - 1) >> 1
|
||||||
for(let i = 0; i < attributesLength; i++) {
|
for (let i = 0; i < attributesLength; i++) {
|
||||||
const key = readString(readByte())
|
const key = readString(readByte())
|
||||||
const value = readString(readByte())
|
const value = readString(readByte())
|
||||||
|
|
||||||
attrs[key] = value
|
attrs[key] = value
|
||||||
}
|
}
|
||||||
|
|
||||||
if(listSize % 2 === 0) {
|
if (listSize % 2 === 0) {
|
||||||
const tag = readByte()
|
const tag = readByte()
|
||||||
if(isListTag(tag)) {
|
if (isListTag(tag)) {
|
||||||
data = readList(tag)
|
data = readList(tag)
|
||||||
} else {
|
} else {
|
||||||
let decoded: Buffer | string
|
let decoded: Buffer | string
|
||||||
@@ -268,7 +265,7 @@ export const decodeDecompressedBinaryNode = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const decodeBinaryNode = async(buff: Buffer): Promise<BinaryNode> => {
|
export const decodeBinaryNode = async (buff: Buffer): Promise<BinaryNode> => {
|
||||||
const decompBuff = await decompressingIfRequired(buff)
|
const decompBuff = await decompressingIfRequired(buff)
|
||||||
return decodeDecompressedBinaryNode(decompBuff, constants)
|
return decodeDecompressedBinaryNode(decompBuff, constants)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
import * as constants from './constants'
|
import * as constants from './constants'
|
||||||
import { FullJid, jidDecode } from './jid-utils'
|
import { FullJid, jidDecode } from './jid-utils'
|
||||||
import type { BinaryNode, BinaryNodeCodingOptions } from './types'
|
import type { BinaryNode, BinaryNodeCodingOptions } from './types'
|
||||||
@@ -22,14 +21,14 @@ const encodeBinaryNodeInner = (
|
|||||||
const pushByte = (value: number) => buffer.push(value & 0xff)
|
const pushByte = (value: number) => buffer.push(value & 0xff)
|
||||||
|
|
||||||
const pushInt = (value: number, n: number, littleEndian = false) => {
|
const pushInt = (value: number, n: number, littleEndian = false) => {
|
||||||
for(let i = 0; i < n; i++) {
|
for (let i = 0; i < n; i++) {
|
||||||
const curShift = littleEndian ? i : n - 1 - i
|
const curShift = littleEndian ? i : n - 1 - i
|
||||||
buffer.push((value >> (curShift * 8)) & 0xff)
|
buffer.push((value >> (curShift * 8)) & 0xff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const pushBytes = (bytes: Uint8Array | Buffer | number[]) => {
|
const pushBytes = (bytes: Uint8Array | Buffer | number[]) => {
|
||||||
for(const b of bytes) {
|
for (const b of bytes) {
|
||||||
buffer.push(b)
|
buffer.push(b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,18 +37,16 @@ const encodeBinaryNodeInner = (
|
|||||||
pushBytes([(value >> 8) & 0xff, value & 0xff])
|
pushBytes([(value >> 8) & 0xff, value & 0xff])
|
||||||
}
|
}
|
||||||
|
|
||||||
const pushInt20 = (value: number) => (
|
const pushInt20 = (value: number) => pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff])
|
||||||
pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff])
|
|
||||||
)
|
|
||||||
const writeByteLength = (length: number) => {
|
const writeByteLength = (length: number) => {
|
||||||
if(length >= 4294967296) {
|
if (length >= 4294967296) {
|
||||||
throw new Error('string too large to encode: ' + length)
|
throw new Error('string too large to encode: ' + length)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(length >= 1 << 20) {
|
if (length >= 1 << 20) {
|
||||||
pushByte(TAGS.BINARY_32)
|
pushByte(TAGS.BINARY_32)
|
||||||
pushInt(length, 4) // 32 bit integer
|
pushInt(length, 4) // 32 bit integer
|
||||||
} else if(length >= 256) {
|
} else if (length >= 256) {
|
||||||
pushByte(TAGS.BINARY_20)
|
pushByte(TAGS.BINARY_20)
|
||||||
pushInt20(length)
|
pushInt20(length)
|
||||||
} else {
|
} else {
|
||||||
@@ -59,20 +56,20 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const writeStringRaw = (str: string) => {
|
const writeStringRaw = (str: string) => {
|
||||||
const bytes = Buffer.from (str, 'utf-8')
|
const bytes = Buffer.from(str, 'utf-8')
|
||||||
writeByteLength(bytes.length)
|
writeByteLength(bytes.length)
|
||||||
pushBytes(bytes)
|
pushBytes(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
const writeJid = ({ domainType, device, user, server }: FullJid) => {
|
const writeJid = ({ domainType, device, user, server }: FullJid) => {
|
||||||
if(typeof device !== 'undefined') {
|
if (typeof device !== 'undefined') {
|
||||||
pushByte(TAGS.AD_JID)
|
pushByte(TAGS.AD_JID)
|
||||||
pushByte(domainType || 0)
|
pushByte(domainType || 0)
|
||||||
pushByte(device || 0)
|
pushByte(device || 0)
|
||||||
writeString(user)
|
writeString(user)
|
||||||
} else {
|
} else {
|
||||||
pushByte(TAGS.JID_PAIR)
|
pushByte(TAGS.JID_PAIR)
|
||||||
if(user.length) {
|
if (user.length) {
|
||||||
writeString(user)
|
writeString(user)
|
||||||
} else {
|
} else {
|
||||||
pushByte(TAGS.LIST_EMPTY)
|
pushByte(TAGS.LIST_EMPTY)
|
||||||
@@ -91,7 +88,7 @@ const encodeBinaryNodeInner = (
|
|||||||
case '\0':
|
case '\0':
|
||||||
return 15
|
return 15
|
||||||
default:
|
default:
|
||||||
if(char >= '0' && char <= '9') {
|
if (char >= '0' && char <= '9') {
|
||||||
return char.charCodeAt(0) - '0'.charCodeAt(0)
|
return char.charCodeAt(0) - '0'.charCodeAt(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,19 +97,19 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const packHex = (char: string) => {
|
const packHex = (char: string) => {
|
||||||
if(char >= '0' && char <= '9') {
|
if (char >= '0' && char <= '9') {
|
||||||
return char.charCodeAt(0) - '0'.charCodeAt(0)
|
return char.charCodeAt(0) - '0'.charCodeAt(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(char >= 'A' && char <= 'F') {
|
if (char >= 'A' && char <= 'F') {
|
||||||
return 10 + char.charCodeAt(0) - 'A'.charCodeAt(0)
|
return 10 + char.charCodeAt(0) - 'A'.charCodeAt(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(char >= 'a' && char <= 'f') {
|
if (char >= 'a' && char <= 'f') {
|
||||||
return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0)
|
return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if(char === '\0') {
|
if (char === '\0') {
|
||||||
return 15
|
return 15
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,14 +117,14 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const writePackedBytes = (str: string, type: 'nibble' | 'hex') => {
|
const writePackedBytes = (str: string, type: 'nibble' | 'hex') => {
|
||||||
if(str.length > TAGS.PACKED_MAX) {
|
if (str.length > TAGS.PACKED_MAX) {
|
||||||
throw new Error('Too many bytes to pack')
|
throw new Error('Too many bytes to pack')
|
||||||
}
|
}
|
||||||
|
|
||||||
pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
|
pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
|
||||||
|
|
||||||
let roundedLength = Math.ceil(str.length / 2.0)
|
let roundedLength = Math.ceil(str.length / 2.0)
|
||||||
if(str.length % 2 !== 0) {
|
if (str.length % 2 !== 0) {
|
||||||
roundedLength |= 128
|
roundedLength |= 128
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,23 +137,23 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const strLengthHalf = Math.floor(str.length / 2)
|
const strLengthHalf = Math.floor(str.length / 2)
|
||||||
for(let i = 0; i < strLengthHalf;i++) {
|
for (let i = 0; i < strLengthHalf; i++) {
|
||||||
pushByte(packBytePair(str[2 * i], str[2 * i + 1]))
|
pushByte(packBytePair(str[2 * i], str[2 * i + 1]))
|
||||||
}
|
}
|
||||||
|
|
||||||
if(str.length % 2 !== 0) {
|
if (str.length % 2 !== 0) {
|
||||||
pushByte(packBytePair(str[str.length - 1], '\x00'))
|
pushByte(packBytePair(str[str.length - 1], '\x00'))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const isNibble = (str?: string) => {
|
const isNibble = (str?: string) => {
|
||||||
if(!str || str.length > TAGS.PACKED_MAX) {
|
if (!str || str.length > TAGS.PACKED_MAX) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const char of str) {
|
for (const char of str) {
|
||||||
const isInNibbleRange = char >= '0' && char <= '9'
|
const isInNibbleRange = char >= '0' && char <= '9'
|
||||||
if(!isInNibbleRange && char !== '-' && char !== '.') {
|
if (!isInNibbleRange && char !== '-' && char !== '.') {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -165,13 +162,13 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const isHex = (str?: string) => {
|
const isHex = (str?: string) => {
|
||||||
if(!str || str.length > TAGS.PACKED_MAX) {
|
if (!str || str.length > TAGS.PACKED_MAX) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const char of str) {
|
for (const char of str) {
|
||||||
const isInNibbleRange = char >= '0' && char <= '9'
|
const isInNibbleRange = char >= '0' && char <= '9'
|
||||||
if(!isInNibbleRange && !(char >= 'A' && char <= 'F')) {
|
if (!isInNibbleRange && !(char >= 'A' && char <= 'F')) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -180,25 +177,25 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const writeString = (str?: string) => {
|
const writeString = (str?: string) => {
|
||||||
if(str === undefined || str === null) {
|
if (str === undefined || str === null) {
|
||||||
pushByte(TAGS.LIST_EMPTY)
|
pushByte(TAGS.LIST_EMPTY)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokenIndex = TOKEN_MAP[str]
|
const tokenIndex = TOKEN_MAP[str]
|
||||||
if(tokenIndex) {
|
if (tokenIndex) {
|
||||||
if(typeof tokenIndex.dict === 'number') {
|
if (typeof tokenIndex.dict === 'number') {
|
||||||
pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
|
pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
|
||||||
}
|
}
|
||||||
|
|
||||||
pushByte(tokenIndex.index)
|
pushByte(tokenIndex.index)
|
||||||
} else if(isNibble(str)) {
|
} else if (isNibble(str)) {
|
||||||
writePackedBytes(str, 'nibble')
|
writePackedBytes(str, 'nibble')
|
||||||
} else if(isHex(str)) {
|
} else if (isHex(str)) {
|
||||||
writePackedBytes(str, 'hex')
|
writePackedBytes(str, 'hex')
|
||||||
} else if(str) {
|
} else if (str) {
|
||||||
const decodedJid = jidDecode(str)
|
const decodedJid = jidDecode(str)
|
||||||
if(decodedJid) {
|
if (decodedJid) {
|
||||||
writeJid(decodedJid)
|
writeJid(decodedJid)
|
||||||
} else {
|
} else {
|
||||||
writeStringRaw(str)
|
writeStringRaw(str)
|
||||||
@@ -207,9 +204,9 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const writeListStart = (listSize: number) => {
|
const writeListStart = (listSize: number) => {
|
||||||
if(listSize === 0) {
|
if (listSize === 0) {
|
||||||
pushByte(TAGS.LIST_EMPTY)
|
pushByte(TAGS.LIST_EMPTY)
|
||||||
} else if(listSize < 256) {
|
} else if (listSize < 256) {
|
||||||
pushBytes([TAGS.LIST_8, listSize])
|
pushBytes([TAGS.LIST_8, listSize])
|
||||||
} else {
|
} else {
|
||||||
pushByte(TAGS.LIST_16)
|
pushByte(TAGS.LIST_16)
|
||||||
@@ -217,37 +214,36 @@ const encodeBinaryNodeInner = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!tag) {
|
if (!tag) {
|
||||||
throw new Error('Invalid node: tag cannot be undefined')
|
throw new Error('Invalid node: tag cannot be undefined')
|
||||||
}
|
}
|
||||||
|
|
||||||
const validAttributes = Object.keys(attrs || {}).filter(k => (
|
const validAttributes = Object.keys(attrs || {}).filter(k => typeof attrs[k] !== 'undefined' && attrs[k] !== null)
|
||||||
typeof attrs[k] !== 'undefined' && attrs[k] !== null
|
|
||||||
))
|
|
||||||
|
|
||||||
writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0))
|
writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0))
|
||||||
writeString(tag)
|
writeString(tag)
|
||||||
|
|
||||||
for(const key of validAttributes) {
|
for (const key of validAttributes) {
|
||||||
if(typeof attrs[key] === 'string') {
|
if (typeof attrs[key] === 'string') {
|
||||||
writeString(key)
|
writeString(key)
|
||||||
writeString(attrs[key])
|
writeString(attrs[key])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof content === 'string') {
|
if (typeof content === 'string') {
|
||||||
writeString(content)
|
writeString(content)
|
||||||
} else if(Buffer.isBuffer(content) || content instanceof Uint8Array) {
|
} else if (Buffer.isBuffer(content) || content instanceof Uint8Array) {
|
||||||
writeByteLength(content.length)
|
writeByteLength(content.length)
|
||||||
pushBytes(content)
|
pushBytes(content)
|
||||||
} else if(Array.isArray(content)) {
|
} else if (Array.isArray(content)) {
|
||||||
const validContent = content.filter(item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string')
|
const validContent = content.filter(
|
||||||
|
item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string')
|
||||||
)
|
)
|
||||||
writeListStart(validContent.length)
|
writeListStart(validContent.length)
|
||||||
for(const item of validContent) {
|
for (const item of validContent) {
|
||||||
encodeBinaryNodeInner(item, opts, buffer)
|
encodeBinaryNodeInner(item, opts, buffer)
|
||||||
}
|
}
|
||||||
} else if(typeof content === 'undefined') {
|
} else if (typeof content === 'undefined') {
|
||||||
// do nothing
|
// do nothing
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
|
throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { BinaryNode } from './types'
|
|||||||
// some extra useful utilities
|
// some extra useful utilities
|
||||||
|
|
||||||
export const getBinaryNodeChildren = (node: BinaryNode | undefined, childTag: string) => {
|
export const getBinaryNodeChildren = (node: BinaryNode | undefined, childTag: string) => {
|
||||||
if(Array.isArray(node?.content)) {
|
if (Array.isArray(node?.content)) {
|
||||||
return node.content.filter(item => item.tag === childTag)
|
return node.content.filter(item => item.tag === childTag)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ export const getBinaryNodeChildren = (node: BinaryNode | undefined, childTag: st
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
|
export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
|
||||||
if(Array.isArray(content)) {
|
if (Array.isArray(content)) {
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,37 +21,37 @@ export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const getBinaryNodeChild = (node: BinaryNode | undefined, childTag: string) => {
|
export const getBinaryNodeChild = (node: BinaryNode | undefined, childTag: string) => {
|
||||||
if(Array.isArray(node?.content)) {
|
if (Array.isArray(node?.content)) {
|
||||||
return node?.content.find(item => item.tag === childTag)
|
return node?.content.find(item => item.tag === childTag)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getBinaryNodeChildBuffer = (node: BinaryNode | undefined, childTag: string) => {
|
export const getBinaryNodeChildBuffer = (node: BinaryNode | undefined, childTag: string) => {
|
||||||
const child = getBinaryNodeChild(node, childTag)?.content
|
const child = getBinaryNodeChild(node, childTag)?.content
|
||||||
if(Buffer.isBuffer(child) || child instanceof Uint8Array) {
|
if (Buffer.isBuffer(child) || child instanceof Uint8Array) {
|
||||||
return child
|
return child
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getBinaryNodeChildString = (node: BinaryNode | undefined, childTag: string) => {
|
export const getBinaryNodeChildString = (node: BinaryNode | undefined, childTag: string) => {
|
||||||
const child = getBinaryNodeChild(node, childTag)?.content
|
const child = getBinaryNodeChild(node, childTag)?.content
|
||||||
if(Buffer.isBuffer(child) || child instanceof Uint8Array) {
|
if (Buffer.isBuffer(child) || child instanceof Uint8Array) {
|
||||||
return Buffer.from(child).toString('utf-8')
|
return Buffer.from(child).toString('utf-8')
|
||||||
} else if(typeof child === 'string') {
|
} else if (typeof child === 'string') {
|
||||||
return child
|
return child
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getBinaryNodeChildUInt = (node: BinaryNode, childTag: string, length: number) => {
|
export const getBinaryNodeChildUInt = (node: BinaryNode, childTag: string, length: number) => {
|
||||||
const buff = getBinaryNodeChildBuffer(node, childTag)
|
const buff = getBinaryNodeChildBuffer(node, childTag)
|
||||||
if(buff) {
|
if (buff) {
|
||||||
return bufferToUInt(buff, length)
|
return bufferToUInt(buff, length)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const assertNodeErrorFree = (node: BinaryNode) => {
|
export const assertNodeErrorFree = (node: BinaryNode) => {
|
||||||
const errNode = getBinaryNodeChild(node, 'error')
|
const errNode = getBinaryNodeChild(node, 'error')
|
||||||
if(errNode) {
|
if (errNode) {
|
||||||
throw new Boom(errNode.attrs.text || 'Unknown error', { data: +errNode.attrs.code })
|
throw new Boom(errNode.attrs.text || 'Unknown error', { data: +errNode.attrs.code })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -62,16 +62,17 @@ export const reduceBinaryNodeToDictionary = (node: BinaryNode, tag: string) => {
|
|||||||
(dict, { attrs }) => {
|
(dict, { attrs }) => {
|
||||||
dict[attrs.name || attrs.config_code] = attrs.value || attrs.config_value
|
dict[attrs.name || attrs.config_code] = attrs.value || attrs.config_value
|
||||||
return dict
|
return dict
|
||||||
}, { } as { [_: string]: string }
|
},
|
||||||
|
{} as { [_: string]: string }
|
||||||
)
|
)
|
||||||
return dict
|
return dict
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getBinaryNodeMessages = ({ content }: BinaryNode) => {
|
export const getBinaryNodeMessages = ({ content }: BinaryNode) => {
|
||||||
const msgs: proto.WebMessageInfo[] = []
|
const msgs: proto.WebMessageInfo[] = []
|
||||||
if(Array.isArray(content)) {
|
if (Array.isArray(content)) {
|
||||||
for(const item of content) {
|
for (const item of content) {
|
||||||
if(item.tag === 'message') {
|
if (item.tag === 'message') {
|
||||||
msgs.push(proto.WebMessageInfo.decode(item.content as Buffer))
|
msgs.push(proto.WebMessageInfo.decode(item.content as Buffer))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,7 +83,7 @@ export const getBinaryNodeMessages = ({ content }: BinaryNode) => {
|
|||||||
|
|
||||||
function bufferToUInt(e: Uint8Array | Buffer, t: number) {
|
function bufferToUInt(e: Uint8Array | Buffer, t: number) {
|
||||||
let a = 0
|
let a = 0
|
||||||
for(let i = 0; i < t; i++) {
|
for (let i = 0; i < t; i++) {
|
||||||
a = 256 * a + e[i]
|
a = 256 * a + e[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,20 +93,20 @@ function bufferToUInt(e: Uint8Array | Buffer, t: number) {
|
|||||||
const tabs = (n: number) => '\t'.repeat(n)
|
const tabs = (n: number) => '\t'.repeat(n)
|
||||||
|
|
||||||
export function binaryNodeToString(node: BinaryNode | BinaryNode['content'], i = 0) {
|
export function binaryNodeToString(node: BinaryNode | BinaryNode['content'], i = 0) {
|
||||||
if(!node) {
|
if (!node) {
|
||||||
return node
|
return node
|
||||||
}
|
}
|
||||||
|
|
||||||
if(typeof node === 'string') {
|
if (typeof node === 'string') {
|
||||||
return tabs(i) + node
|
return tabs(i) + node
|
||||||
}
|
}
|
||||||
|
|
||||||
if(node instanceof Uint8Array) {
|
if (node instanceof Uint8Array) {
|
||||||
return tabs(i) + Buffer.from(node).toString('hex')
|
return tabs(i) + Buffer.from(node).toString('hex')
|
||||||
}
|
}
|
||||||
|
|
||||||
if(Array.isArray(node)) {
|
if (Array.isArray(node)) {
|
||||||
return node.map((x) => tabs(i + 1) + binaryNodeToString(x, i + 1)).join('\n')
|
return node.map(x => tabs(i + 1) + binaryNodeToString(x, i + 1)).join('\n')
|
||||||
}
|
}
|
||||||
|
|
||||||
const children = binaryNodeToString(node.content, i + 1)
|
const children = binaryNodeToString(node.content, i + 1)
|
||||||
|
|||||||
@@ -17,14 +17,13 @@ export type FullJid = JidWithDevice & {
|
|||||||
domainType?: number
|
domainType?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const jidEncode = (user: string | number | null, server: JidServer, device?: number, agent?: number) => {
|
export const jidEncode = (user: string | number | null, server: JidServer, device?: number, agent?: number) => {
|
||||||
return `${user || ''}${!!agent ? `_${agent}` : ''}${!!device ? `:${device}` : ''}@${server}`
|
return `${user || ''}${!!agent ? `_${agent}` : ''}${!!device ? `:${device}` : ''}@${server}`
|
||||||
}
|
}
|
||||||
|
|
||||||
export const jidDecode = (jid: string | undefined): FullJid | undefined => {
|
export const jidDecode = (jid: string | undefined): FullJid | undefined => {
|
||||||
const sepIdx = typeof jid === 'string' ? jid.indexOf('@') : -1
|
const sepIdx = typeof jid === 'string' ? jid.indexOf('@') : -1
|
||||||
if(sepIdx < 0) {
|
if (sepIdx < 0) {
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,34 +42,33 @@ export const jidDecode = (jid: string | undefined): FullJid | undefined => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** is the jid a user */
|
/** is the jid a user */
|
||||||
export const areJidsSameUser = (jid1: string | undefined, jid2: string | undefined) => (
|
export const areJidsSameUser = (jid1: string | undefined, jid2: string | undefined) =>
|
||||||
jidDecode(jid1)?.user === jidDecode(jid2)?.user
|
jidDecode(jid1)?.user === jidDecode(jid2)?.user
|
||||||
)
|
|
||||||
/** is the jid Meta IA */
|
/** is the jid Meta IA */
|
||||||
export const isJidMetaIa = (jid: string | undefined) => (jid?.endsWith('@bot'))
|
export const isJidMetaIa = (jid: string | undefined) => jid?.endsWith('@bot')
|
||||||
/** is the jid a user */
|
/** is the jid a user */
|
||||||
export const isJidUser = (jid: string | undefined) => (jid?.endsWith('@s.whatsapp.net'))
|
export const isJidUser = (jid: string | undefined) => jid?.endsWith('@s.whatsapp.net')
|
||||||
/** is the jid a group */
|
/** is the jid a group */
|
||||||
export const isLidUser = (jid: string | undefined) => (jid?.endsWith('@lid'))
|
export const isLidUser = (jid: string | undefined) => jid?.endsWith('@lid')
|
||||||
/** is the jid a broadcast */
|
/** is the jid a broadcast */
|
||||||
export const isJidBroadcast = (jid: string | undefined) => (jid?.endsWith('@broadcast'))
|
export const isJidBroadcast = (jid: string | undefined) => jid?.endsWith('@broadcast')
|
||||||
/** is the jid a group */
|
/** is the jid a group */
|
||||||
export const isJidGroup = (jid: string | undefined) => (jid?.endsWith('@g.us'))
|
export const isJidGroup = (jid: string | undefined) => jid?.endsWith('@g.us')
|
||||||
/** is the jid the status broadcast */
|
/** is the jid the status broadcast */
|
||||||
export const isJidStatusBroadcast = (jid: string) => jid === 'status@broadcast'
|
export const isJidStatusBroadcast = (jid: string) => jid === 'status@broadcast'
|
||||||
/** is the jid a newsletter */
|
/** is the jid a newsletter */
|
||||||
export const isJidNewsletter = (jid: string | undefined) => (jid?.endsWith('@newsletter'))
|
export const isJidNewsletter = (jid: string | undefined) => jid?.endsWith('@newsletter')
|
||||||
|
|
||||||
const botRegexp = /^1313555\d{4}$|^131655500\d{2}$/
|
const botRegexp = /^1313555\d{4}$|^131655500\d{2}$/
|
||||||
|
|
||||||
export const isJidBot = (jid: string | undefined) => (jid && botRegexp.test(jid.split('@')[0]) && jid.endsWith('@c.us'))
|
export const isJidBot = (jid: string | undefined) => jid && botRegexp.test(jid.split('@')[0]) && jid.endsWith('@c.us')
|
||||||
|
|
||||||
export const jidNormalizedUser = (jid: string | undefined) => {
|
export const jidNormalizedUser = (jid: string | undefined) => {
|
||||||
const result = jidDecode(jid)
|
const result = jidDecode(jid)
|
||||||
if(!result) {
|
if (!result) {
|
||||||
return ''
|
return ''
|
||||||
}
|
}
|
||||||
|
|
||||||
const { user, server } = result
|
const { user, server } = result
|
||||||
return jidEncode(user, server === 'c.us' ? 's.whatsapp.net' : server as JidServer)
|
return jidEncode(user, server === 'c.us' ? 's.whatsapp.net' : (server as JidServer))
|
||||||
}
|
}
|
||||||
|
|||||||
4431
src/WAM/constants.ts
4431
src/WAM/constants.ts
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,14 @@
|
|||||||
import { BinaryInfo } from './BinaryInfo'
|
import { BinaryInfo } from './BinaryInfo'
|
||||||
import { FLAG_BYTE, FLAG_EVENT, FLAG_EXTENDED, FLAG_FIELD, FLAG_GLOBAL, Value, WEB_EVENTS, WEB_GLOBALS } from './constants'
|
import {
|
||||||
|
FLAG_BYTE,
|
||||||
|
FLAG_EVENT,
|
||||||
|
FLAG_EXTENDED,
|
||||||
|
FLAG_FIELD,
|
||||||
|
FLAG_GLOBAL,
|
||||||
|
Value,
|
||||||
|
WEB_EVENTS,
|
||||||
|
WEB_GLOBALS
|
||||||
|
} from './constants'
|
||||||
|
|
||||||
const getHeaderBitLength = (key: number) => (key < 256 ? 2 : 3)
|
const getHeaderBitLength = (key: number) => (key < 256 ? 2 : 3)
|
||||||
|
|
||||||
@@ -10,12 +19,10 @@ export const encodeWAM = (binaryInfo: BinaryInfo) => {
|
|||||||
encodeEvents(binaryInfo)
|
encodeEvents(binaryInfo)
|
||||||
|
|
||||||
console.log(binaryInfo.buffer)
|
console.log(binaryInfo.buffer)
|
||||||
const totalSize = binaryInfo.buffer
|
const totalSize = binaryInfo.buffer.map(a => a.length).reduce((a, b) => a + b)
|
||||||
.map((a) => a.length)
|
|
||||||
.reduce((a, b) => a + b)
|
|
||||||
const buffer = Buffer.alloc(totalSize)
|
const buffer = Buffer.alloc(totalSize)
|
||||||
let offset = 0
|
let offset = 0
|
||||||
for(const buffer_ of binaryInfo.buffer) {
|
for (const buffer_ of binaryInfo.buffer) {
|
||||||
buffer_.copy(buffer, offset)
|
buffer_.copy(buffer, offset)
|
||||||
offset += buffer_.length
|
offset += buffer_.length
|
||||||
}
|
}
|
||||||
@@ -34,11 +41,11 @@ function encodeWAMHeader(binaryInfo: BinaryInfo) {
|
|||||||
binaryInfo.buffer.push(headerBuffer)
|
binaryInfo.buffer.push(headerBuffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
function encodeGlobalAttributes(binaryInfo: BinaryInfo, globals: {[key: string]: Value}) {
|
function encodeGlobalAttributes(binaryInfo: BinaryInfo, globals: { [key: string]: Value }) {
|
||||||
for(const [key, _value] of Object.entries(globals)) {
|
for (const [key, _value] of Object.entries(globals)) {
|
||||||
const id = WEB_GLOBALS.find(a => a?.name === key)!.id
|
const id = WEB_GLOBALS.find(a => a?.name === key)!.id
|
||||||
let value = _value
|
let value = _value
|
||||||
if(typeof value === 'boolean') {
|
if (typeof value === 'boolean') {
|
||||||
value = value ? 1 : 0
|
value = value ? 1 : 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,30 +54,27 @@ function encodeGlobalAttributes(binaryInfo: BinaryInfo, globals: {[key: string]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
function encodeEvents(binaryInfo: BinaryInfo) {
|
function encodeEvents(binaryInfo: BinaryInfo) {
|
||||||
for(const [
|
for (const [name, { props, globals }] of binaryInfo.events.map(a => Object.entries(a)[0])) {
|
||||||
name,
|
|
||||||
{ props, globals },
|
|
||||||
] of binaryInfo.events.map((a) => Object.entries(a)[0])) {
|
|
||||||
encodeGlobalAttributes(binaryInfo, globals)
|
encodeGlobalAttributes(binaryInfo, globals)
|
||||||
const event = WEB_EVENTS.find((a) => a.name === name)!
|
const event = WEB_EVENTS.find(a => a.name === name)!
|
||||||
|
|
||||||
const props_ = Object.entries(props)
|
const props_ = Object.entries(props)
|
||||||
|
|
||||||
let extended = false
|
let extended = false
|
||||||
|
|
||||||
for(const [, value] of props_) {
|
for (const [, value] of props_) {
|
||||||
extended ||= value !== null
|
extended ||= value !== null
|
||||||
}
|
}
|
||||||
|
|
||||||
const eventFlag = extended ? FLAG_EVENT : FLAG_EVENT | FLAG_EXTENDED
|
const eventFlag = extended ? FLAG_EVENT : FLAG_EVENT | FLAG_EXTENDED
|
||||||
binaryInfo.buffer.push(serializeData(event.id, -event.weight, eventFlag))
|
binaryInfo.buffer.push(serializeData(event.id, -event.weight, eventFlag))
|
||||||
|
|
||||||
for(let i = 0; i < props_.length; i++) {
|
for (let i = 0; i < props_.length; i++) {
|
||||||
const [key, _value] = props_[i]
|
const [key, _value] = props_[i]
|
||||||
const id = (event.props)[key][0]
|
const id = event.props[key][0]
|
||||||
extended = i < (props_.length - 1)
|
extended = i < props_.length - 1
|
||||||
let value = _value
|
let value = _value
|
||||||
if(typeof value === 'boolean') {
|
if (typeof value === 'boolean') {
|
||||||
value = value ? 1 : 0
|
value = value ? 1 : 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,34 +84,33 @@ function encodeEvents(binaryInfo: BinaryInfo) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function serializeData(key: number, value: Value, flag: number): Buffer {
|
function serializeData(key: number, value: Value, flag: number): Buffer {
|
||||||
const bufferLength = getHeaderBitLength(key)
|
const bufferLength = getHeaderBitLength(key)
|
||||||
let buffer: Buffer
|
let buffer: Buffer
|
||||||
let offset = 0
|
let offset = 0
|
||||||
if(value === null) {
|
if (value === null) {
|
||||||
if(flag === FLAG_GLOBAL) {
|
if (flag === FLAG_GLOBAL) {
|
||||||
buffer = Buffer.alloc(bufferLength)
|
buffer = Buffer.alloc(bufferLength)
|
||||||
offset = serializeHeader(buffer, offset, key, flag)
|
offset = serializeHeader(buffer, offset, key, flag)
|
||||||
return buffer
|
return buffer
|
||||||
}
|
}
|
||||||
} else if(typeof value === 'number' && Number.isInteger(value)) {
|
} else if (typeof value === 'number' && Number.isInteger(value)) {
|
||||||
// is number
|
// is number
|
||||||
if(value === 0 || value === 1) {
|
if (value === 0 || value === 1) {
|
||||||
buffer = Buffer.alloc(bufferLength)
|
buffer = Buffer.alloc(bufferLength)
|
||||||
offset = serializeHeader(buffer, offset, key, flag | ((value + 1) << 4))
|
offset = serializeHeader(buffer, offset, key, flag | ((value + 1) << 4))
|
||||||
return buffer
|
return buffer
|
||||||
} else if(-128 <= value && value < 128) {
|
} else if (-128 <= value && value < 128) {
|
||||||
buffer = Buffer.alloc(bufferLength + 1)
|
buffer = Buffer.alloc(bufferLength + 1)
|
||||||
offset = serializeHeader(buffer, offset, key, flag | (3 << 4))
|
offset = serializeHeader(buffer, offset, key, flag | (3 << 4))
|
||||||
buffer.writeInt8(value, offset)
|
buffer.writeInt8(value, offset)
|
||||||
return buffer
|
return buffer
|
||||||
} else if(-32768 <= value && value < 32768) {
|
} else if (-32768 <= value && value < 32768) {
|
||||||
buffer = Buffer.alloc(bufferLength + 2)
|
buffer = Buffer.alloc(bufferLength + 2)
|
||||||
offset = serializeHeader(buffer, offset, key, flag | (4 << 4))
|
offset = serializeHeader(buffer, offset, key, flag | (4 << 4))
|
||||||
buffer.writeInt16LE(value, offset)
|
buffer.writeInt16LE(value, offset)
|
||||||
return buffer
|
return buffer
|
||||||
} else if(-2147483648 <= value && value < 2147483648) {
|
} else if (-2147483648 <= value && value < 2147483648) {
|
||||||
buffer = Buffer.alloc(bufferLength + 4)
|
buffer = Buffer.alloc(bufferLength + 4)
|
||||||
offset = serializeHeader(buffer, offset, key, flag | (5 << 4))
|
offset = serializeHeader(buffer, offset, key, flag | (5 << 4))
|
||||||
buffer.writeInt32LE(value, offset)
|
buffer.writeInt32LE(value, offset)
|
||||||
@@ -118,20 +121,20 @@ function serializeData(key: number, value: Value, flag: number): Buffer {
|
|||||||
buffer.writeDoubleLE(value, offset)
|
buffer.writeDoubleLE(value, offset)
|
||||||
return buffer
|
return buffer
|
||||||
}
|
}
|
||||||
} else if(typeof value === 'number') {
|
} else if (typeof value === 'number') {
|
||||||
// is float
|
// is float
|
||||||
buffer = Buffer.alloc(bufferLength + 8)
|
buffer = Buffer.alloc(bufferLength + 8)
|
||||||
offset = serializeHeader(buffer, offset, key, flag | (7 << 4))
|
offset = serializeHeader(buffer, offset, key, flag | (7 << 4))
|
||||||
buffer.writeDoubleLE(value, offset)
|
buffer.writeDoubleLE(value, offset)
|
||||||
return buffer
|
return buffer
|
||||||
} else if(typeof value === 'string') {
|
} else if (typeof value === 'string') {
|
||||||
// is string
|
// is string
|
||||||
const utf8Bytes = Buffer.byteLength(value, 'utf8')
|
const utf8Bytes = Buffer.byteLength(value, 'utf8')
|
||||||
if(utf8Bytes < 256) {
|
if (utf8Bytes < 256) {
|
||||||
buffer = Buffer.alloc(bufferLength + 1 + utf8Bytes)
|
buffer = Buffer.alloc(bufferLength + 1 + utf8Bytes)
|
||||||
offset = serializeHeader(buffer, offset, key, flag | (8 << 4))
|
offset = serializeHeader(buffer, offset, key, flag | (8 << 4))
|
||||||
buffer.writeUint8(utf8Bytes, offset++)
|
buffer.writeUint8(utf8Bytes, offset++)
|
||||||
} else if(utf8Bytes < 65536) {
|
} else if (utf8Bytes < 65536) {
|
||||||
buffer = Buffer.alloc(bufferLength + 2 + utf8Bytes)
|
buffer = Buffer.alloc(bufferLength + 2 + utf8Bytes)
|
||||||
offset = serializeHeader(buffer, offset, key, flag | (9 << 4))
|
offset = serializeHeader(buffer, offset, key, flag | (9 << 4))
|
||||||
buffer.writeUInt16LE(utf8Bytes, offset)
|
buffer.writeUInt16LE(utf8Bytes, offset)
|
||||||
@@ -150,13 +153,8 @@ function serializeData(key: number, value: Value, flag: number): Buffer {
|
|||||||
throw 'missing'
|
throw 'missing'
|
||||||
}
|
}
|
||||||
|
|
||||||
function serializeHeader(
|
function serializeHeader(buffer: Buffer, offset: number, key: number, flag: number) {
|
||||||
buffer: Buffer,
|
if (key < 256) {
|
||||||
offset: number,
|
|
||||||
key: number,
|
|
||||||
flag: number
|
|
||||||
) {
|
|
||||||
if(key < 256) {
|
|
||||||
buffer.writeUInt8(flag, offset)
|
buffer.writeUInt8(flag, offset)
|
||||||
offset += 1
|
offset += 1
|
||||||
buffer.writeUInt8(key, offset)
|
buffer.writeUInt8(key, offset)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ export class USyncContactProtocol implements USyncQueryProtocol {
|
|||||||
getQueryElement(): BinaryNode {
|
getQueryElement(): BinaryNode {
|
||||||
return {
|
return {
|
||||||
tag: 'contact',
|
tag: 'contact',
|
||||||
attrs: {},
|
attrs: {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,12 +17,12 @@ export class USyncContactProtocol implements USyncQueryProtocol {
|
|||||||
return {
|
return {
|
||||||
tag: 'contact',
|
tag: 'contact',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: user.phone,
|
content: user.phone
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
parser(node: BinaryNode): boolean {
|
parser(node: BinaryNode): boolean {
|
||||||
if(node.tag === 'contact') {
|
if (node.tag === 'contact') {
|
||||||
assertNodeErrorFree(node)
|
assertNodeErrorFree(node)
|
||||||
return node?.attrs?.type === 'in'
|
return node?.attrs?.type === 'in'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,8 +26,8 @@ export class USyncDeviceProtocol implements USyncQueryProtocol {
|
|||||||
return {
|
return {
|
||||||
tag: 'devices',
|
tag: 'devices',
|
||||||
attrs: {
|
attrs: {
|
||||||
version: '2',
|
version: '2'
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,16 +42,16 @@ export class USyncDeviceProtocol implements USyncQueryProtocol {
|
|||||||
const deviceList: DeviceListData[] = []
|
const deviceList: DeviceListData[] = []
|
||||||
let keyIndex: KeyIndexData | undefined = undefined
|
let keyIndex: KeyIndexData | undefined = undefined
|
||||||
|
|
||||||
if(node.tag === 'devices') {
|
if (node.tag === 'devices') {
|
||||||
assertNodeErrorFree(node)
|
assertNodeErrorFree(node)
|
||||||
const deviceListNode = getBinaryNodeChild(node, 'device-list')
|
const deviceListNode = getBinaryNodeChild(node, 'device-list')
|
||||||
const keyIndexNode = getBinaryNodeChild(node, 'key-index-list')
|
const keyIndexNode = getBinaryNodeChild(node, 'key-index-list')
|
||||||
|
|
||||||
if(Array.isArray(deviceListNode?.content)) {
|
if (Array.isArray(deviceListNode?.content)) {
|
||||||
for(const { tag, attrs } of deviceListNode.content) {
|
for (const { tag, attrs } of deviceListNode.content) {
|
||||||
const id = +attrs.id
|
const id = +attrs.id
|
||||||
const keyIndex = +attrs['key-index']
|
const keyIndex = +attrs['key-index']
|
||||||
if(tag === 'device') {
|
if (tag === 'device') {
|
||||||
deviceList.push({
|
deviceList.push({
|
||||||
id,
|
id,
|
||||||
keyIndex,
|
keyIndex,
|
||||||
@@ -61,7 +61,7 @@ export class USyncDeviceProtocol implements USyncQueryProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(keyIndexNode?.tag === 'key-index-list') {
|
if (keyIndexNode?.tag === 'key-index-list') {
|
||||||
keyIndex = {
|
keyIndex = {
|
||||||
timestamp: +keyIndexNode.attrs['ts'],
|
timestamp: +keyIndexNode.attrs['ts'],
|
||||||
signedKeyIndex: keyIndexNode?.content as Uint8Array,
|
signedKeyIndex: keyIndexNode?.content as Uint8Array,
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export class USyncDisappearingModeProtocol implements USyncQueryProtocol {
|
|||||||
getQueryElement(): BinaryNode {
|
getQueryElement(): BinaryNode {
|
||||||
return {
|
return {
|
||||||
tag: 'disappearing_mode',
|
tag: 'disappearing_mode',
|
||||||
attrs: {},
|
attrs: {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,14 +21,14 @@ export class USyncDisappearingModeProtocol implements USyncQueryProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
parser(node: BinaryNode): DisappearingModeData | undefined {
|
parser(node: BinaryNode): DisappearingModeData | undefined {
|
||||||
if(node.tag === 'status') {
|
if (node.tag === 'status') {
|
||||||
assertNodeErrorFree(node)
|
assertNodeErrorFree(node)
|
||||||
const duration: number = +node?.attrs.duration
|
const duration: number = +node?.attrs.duration
|
||||||
const setAt = new Date(+(node?.attrs.t || 0) * 1000)
|
const setAt = new Date(+(node?.attrs.t || 0) * 1000)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
duration,
|
duration,
|
||||||
setAt,
|
setAt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export class USyncStatusProtocol implements USyncQueryProtocol {
|
|||||||
getQueryElement(): BinaryNode {
|
getQueryElement(): BinaryNode {
|
||||||
return {
|
return {
|
||||||
tag: 'status',
|
tag: 'status',
|
||||||
attrs: {},
|
attrs: {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,23 +21,23 @@ export class USyncStatusProtocol implements USyncQueryProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
parser(node: BinaryNode): StatusData | undefined {
|
parser(node: BinaryNode): StatusData | undefined {
|
||||||
if(node.tag === 'status') {
|
if (node.tag === 'status') {
|
||||||
assertNodeErrorFree(node)
|
assertNodeErrorFree(node)
|
||||||
let status: string | null = node?.content!.toString()
|
let status: string | null = node?.content!.toString()
|
||||||
const setAt = new Date(+(node?.attrs.t || 0) * 1000)
|
const setAt = new Date(+(node?.attrs.t || 0) * 1000)
|
||||||
if(!status) {
|
if (!status) {
|
||||||
if(+node.attrs?.code === 401) {
|
if (+node.attrs?.code === 401) {
|
||||||
status = ''
|
status = ''
|
||||||
} else {
|
} else {
|
||||||
status = null
|
status = null
|
||||||
}
|
}
|
||||||
} else if(typeof status === 'string' && status.length === 0) {
|
} else if (typeof status === 'string' && status.length === 0) {
|
||||||
status = null
|
status = null
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
status,
|
status,
|
||||||
setAt,
|
setAt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
|
|||||||
getQueryElement(): BinaryNode {
|
getQueryElement(): BinaryNode {
|
||||||
return {
|
return {
|
||||||
tag: 'bot',
|
tag: 'bot',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [{ tag: 'profile', attrs: { v: '1' } }]
|
content: [{ tag: 'profile', attrs: { v: '1' } }]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -34,8 +34,8 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
|
|||||||
getUserElement(user: USyncUser): BinaryNode {
|
getUserElement(user: USyncUser): BinaryNode {
|
||||||
return {
|
return {
|
||||||
tag: 'bot',
|
tag: 'bot',
|
||||||
attrs: { },
|
attrs: {},
|
||||||
content: [{ tag: 'profile', attrs: { 'persona_id': user.personaId } }]
|
content: [{ tag: 'profile', attrs: { persona_id: user.personaId } }]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,18 +49,17 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
|
|||||||
const commands: BotProfileCommand[] = []
|
const commands: BotProfileCommand[] = []
|
||||||
const prompts: string[] = []
|
const prompts: string[] = []
|
||||||
|
|
||||||
for(const command of getBinaryNodeChildren(commandsNode, 'command')) {
|
for (const command of getBinaryNodeChildren(commandsNode, 'command')) {
|
||||||
commands.push({
|
commands.push({
|
||||||
name: getBinaryNodeChildString(command, 'name')!,
|
name: getBinaryNodeChildString(command, 'name')!,
|
||||||
description: getBinaryNodeChildString(command, 'description')!
|
description: getBinaryNodeChildString(command, 'description')!
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const prompt of getBinaryNodeChildren(promptsNode, 'prompt')) {
|
for (const prompt of getBinaryNodeChildren(promptsNode, 'prompt')) {
|
||||||
prompts.push(`${getBinaryNodeChildString(prompt, 'emoji')!} ${getBinaryNodeChildString(prompt, 'text')!}`)
|
prompts.push(`${getBinaryNodeChildString(prompt, 'emoji')!} ${getBinaryNodeChildString(prompt, 'text')!}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isDefault: !!getBinaryNodeChild(profile, 'default'),
|
isDefault: !!getBinaryNodeChild(profile, 'default'),
|
||||||
jid: node.attrs.jid,
|
jid: node.attrs.jid,
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export class USyncLIDProtocol implements USyncQueryProtocol {
|
|||||||
getQueryElement(): BinaryNode {
|
getQueryElement(): BinaryNode {
|
||||||
return {
|
return {
|
||||||
tag: 'lid',
|
tag: 'lid',
|
||||||
attrs: {},
|
attrs: {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -16,7 +16,7 @@ export class USyncLIDProtocol implements USyncQueryProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
parser(node: BinaryNode): string | null {
|
parser(node: BinaryNode): string | null {
|
||||||
if(node.tag === 'lid') {
|
if (node.tag === 'lid') {
|
||||||
return node.attrs.val
|
return node.attrs.val
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,15 @@ import { USyncQueryProtocol } from '../Types/USync'
|
|||||||
import { BinaryNode, getBinaryNodeChild } from '../WABinary'
|
import { BinaryNode, getBinaryNodeChild } from '../WABinary'
|
||||||
import { USyncBotProfileProtocol } from './Protocols/UsyncBotProfileProtocol'
|
import { USyncBotProfileProtocol } from './Protocols/UsyncBotProfileProtocol'
|
||||||
import { USyncLIDProtocol } from './Protocols/UsyncLIDProtocol'
|
import { USyncLIDProtocol } from './Protocols/UsyncLIDProtocol'
|
||||||
import { USyncContactProtocol, USyncDeviceProtocol, USyncDisappearingModeProtocol, USyncStatusProtocol } from './Protocols'
|
import {
|
||||||
|
USyncContactProtocol,
|
||||||
|
USyncDeviceProtocol,
|
||||||
|
USyncDisappearingModeProtocol,
|
||||||
|
USyncStatusProtocol
|
||||||
|
} from './Protocols'
|
||||||
import { USyncUser } from './USyncUser'
|
import { USyncUser } from './USyncUser'
|
||||||
|
|
||||||
export type USyncQueryResultList = { [protocol: string]: unknown, id: string }
|
export type USyncQueryResultList = { [protocol: string]: unknown; id: string }
|
||||||
|
|
||||||
export type USyncQueryResult = {
|
export type USyncQueryResult = {
|
||||||
list: USyncQueryResultList[]
|
list: USyncQueryResultList[]
|
||||||
@@ -41,18 +46,20 @@ export class USyncQuery {
|
|||||||
}
|
}
|
||||||
|
|
||||||
parseUSyncQueryResult(result: BinaryNode): USyncQueryResult | undefined {
|
parseUSyncQueryResult(result: BinaryNode): USyncQueryResult | undefined {
|
||||||
if(result.attrs.type !== 'result') {
|
if (result.attrs.type !== 'result') {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const protocolMap = Object.fromEntries(this.protocols.map((protocol) => {
|
const protocolMap = Object.fromEntries(
|
||||||
|
this.protocols.map(protocol => {
|
||||||
return [protocol.name, protocol.parser]
|
return [protocol.name, protocol.parser]
|
||||||
}))
|
})
|
||||||
|
)
|
||||||
|
|
||||||
const queryResult: USyncQueryResult = {
|
const queryResult: USyncQueryResult = {
|
||||||
// TODO: implement errors etc.
|
// TODO: implement errors etc.
|
||||||
list: [],
|
list: [],
|
||||||
sideList: [],
|
sideList: []
|
||||||
}
|
}
|
||||||
|
|
||||||
const usyncNode = getBinaryNodeChild(result, 'usync')
|
const usyncNode = getBinaryNodeChild(result, 'usync')
|
||||||
@@ -62,18 +69,24 @@ export class USyncQuery {
|
|||||||
//const resultNode = getBinaryNodeChild(usyncNode, 'result')
|
//const resultNode = getBinaryNodeChild(usyncNode, 'result')
|
||||||
|
|
||||||
const listNode = getBinaryNodeChild(usyncNode, 'list')
|
const listNode = getBinaryNodeChild(usyncNode, 'list')
|
||||||
if(Array.isArray(listNode?.content) && typeof listNode !== 'undefined') {
|
if (Array.isArray(listNode?.content) && typeof listNode !== 'undefined') {
|
||||||
queryResult.list = listNode.content.map((node) => {
|
queryResult.list = listNode.content.map(node => {
|
||||||
const id = node?.attrs.jid
|
const id = node?.attrs.jid
|
||||||
const data = Array.isArray(node?.content) ? Object.fromEntries(node.content.map((content) => {
|
const data = Array.isArray(node?.content)
|
||||||
|
? Object.fromEntries(
|
||||||
|
node.content
|
||||||
|
.map(content => {
|
||||||
const protocol = content.tag
|
const protocol = content.tag
|
||||||
const parser = protocolMap[protocol]
|
const parser = protocolMap[protocol]
|
||||||
if(parser) {
|
if (parser) {
|
||||||
return [protocol, parser(content)]
|
return [protocol, parser(content)]
|
||||||
} else {
|
} else {
|
||||||
return [protocol, null]
|
return [protocol, null]
|
||||||
}
|
}
|
||||||
}).filter(([, b]) => b !== null) as [string, unknown][]) : {}
|
})
|
||||||
|
.filter(([, b]) => b !== null) as [string, unknown][]
|
||||||
|
)
|
||||||
|
: {}
|
||||||
return { ...data, id }
|
return { ...data, id }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user