mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
Merge pull request #1389 from WhiskeySockets/fix-eslint-prettier-editorconfig-rules
Fix eslint prettier editorconfig rules
This commit is contained in:
5
.editorconfig
Normal file
5
.editorconfig
Normal file
@@ -0,0 +1,5 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = tab
|
||||
indent_size = 2
|
||||
@@ -1,29 +1,39 @@
|
||||
{
|
||||
"extends": "@whiskeysockets",
|
||||
"extends": ["@whiskeysockets", "plugin:prettier/recommended"],
|
||||
"plugins": ["prettier"],
|
||||
"parserOptions": {
|
||||
"sourceType": "module",
|
||||
"project": "./tsconfig.json"
|
||||
},
|
||||
"ignorePatterns": ["src/Tests/*"],
|
||||
"rules": {
|
||||
"camelcase": "off",
|
||||
"indent": "off",
|
||||
"@typescript-eslint/no-explicit-any": [
|
||||
"warn",
|
||||
{
|
||||
"ignoreRestArgs": true
|
||||
}
|
||||
],
|
||||
"@typescript-eslint/no-inferrable-types": [
|
||||
"warn"
|
||||
],
|
||||
"@typescript-eslint/no-redundant-type-constituents": [
|
||||
"warn"
|
||||
],
|
||||
"@typescript-eslint/no-unnecessary-type-assertion": [
|
||||
"warn"
|
||||
],
|
||||
"@typescript-eslint/no-inferrable-types": ["warn"],
|
||||
"@typescript-eslint/no-redundant-type-constituents": ["warn"],
|
||||
"@typescript-eslint/no-unnecessary-type-assertion": ["warn"],
|
||||
"no-restricted-syntax": "off",
|
||||
"keyword-spacing": [
|
||||
"warn"
|
||||
"keyword-spacing": "off",
|
||||
"implicit-arrow-linebreak": ["off"],
|
||||
"space-before-function-paren": [
|
||||
"error",
|
||||
{
|
||||
"anonymous": "always",
|
||||
"named": "never",
|
||||
"asyncArrow": "always"
|
||||
}
|
||||
],
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
"caughtErrors": "none"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1 +1,9 @@
|
||||
*
|
||||
lib
|
||||
coverage
|
||||
*.lock
|
||||
*.json
|
||||
src/WABinary/index.ts
|
||||
WAProto
|
||||
WASignalGroup
|
||||
Example/Example.ts
|
||||
docs
|
||||
|
||||
11
.prettierrc
Normal file
11
.prettierrc
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"tabWidth": 2,
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": true,
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "avoid",
|
||||
"printWidth": 120,
|
||||
"trailingComma": "none"
|
||||
}
|
||||
11
package.json
11
package.json
@@ -30,8 +30,9 @@
|
||||
"changelog:update": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
|
||||
"example": "node --inspect -r ts-node/register Example/example.ts",
|
||||
"gen:protobuf": "sh WAProto/GenerateStatics.sh",
|
||||
"format": "prettier --write \"src/**/*.{ts,js,json,md}\"",
|
||||
"lint": "eslint src --ext .js,.ts",
|
||||
"lint:fix": "yarn lint --fix",
|
||||
"lint:fix": "yarn format && yarn lint --fix",
|
||||
"prepack": "tsc",
|
||||
"prepare": "tsc",
|
||||
"preinstall": "node ./engine-requirements.js",
|
||||
@@ -55,17 +56,21 @@
|
||||
"@types/jest": "^27.5.1",
|
||||
"@types/node": "^16.0.0",
|
||||
"@types/ws": "^8.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.32.0",
|
||||
"conventional-changelog-cli": "^2.2.2",
|
||||
"eslint": "^8.0.0",
|
||||
"jest": "^27.0.6",
|
||||
"eslint-config-prettier": "^10.1.2",
|
||||
"eslint-plugin-prettier": "^5.4.0",
|
||||
"jest": "^29.7.0",
|
||||
"jimp": "^0.16.1",
|
||||
"json": "^11.0.0",
|
||||
"link-preview-js": "^3.0.0",
|
||||
"open": "^8.4.2",
|
||||
"prettier": "^3.5.3",
|
||||
"protobufjs-cli": "^1.1.3",
|
||||
"release-it": "^15.10.3",
|
||||
"sharp": "^0.32.6",
|
||||
"ts-jest": "^27.0.3",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-node": "^10.8.1",
|
||||
"typedoc": "^0.27.9",
|
||||
"typedoc-plugin-markdown": "4.4.2",
|
||||
|
||||
@@ -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 DICT_VERSION = 2
|
||||
export const KEY_BUNDLE_TYPE = Buffer.from([5])
|
||||
export const NOISE_WA_HEADER = Buffer.from(
|
||||
[ 87, 65, 6, DICT_VERSION ]
|
||||
) // last is "DICT_VERSION"
|
||||
export const NOISE_WA_HEADER = Buffer.from([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 */
|
||||
export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g
|
||||
|
||||
export const WA_CERT_DETAILS = {
|
||||
SERIAL: 0,
|
||||
SERIAL: 0
|
||||
}
|
||||
|
||||
export const PROCESSABLE_HISTORY_TYPES = [
|
||||
@@ -32,7 +30,7 @@ export const PROCESSABLE_HISTORY_TYPES = [
|
||||
proto.Message.HistorySyncNotification.HistorySyncType.PUSH_NAME,
|
||||
proto.Message.HistorySyncNotification.HistorySyncType.RECENT,
|
||||
proto.Message.HistorySyncNotification.HistorySyncType.FULL,
|
||||
proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND,
|
||||
proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND
|
||||
]
|
||||
|
||||
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
||||
@@ -57,14 +55,14 @@ export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
||||
linkPreviewImageThumbnailWidth: 192,
|
||||
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
|
||||
generateHighQualityLinkPreview: false,
|
||||
options: { },
|
||||
options: {},
|
||||
appStateMacVerification: {
|
||||
patch: false,
|
||||
snapshot: false,
|
||||
snapshot: false
|
||||
},
|
||||
countryCode: 'US',
|
||||
getMessage: async() => undefined,
|
||||
cachedGroupMetadata: async() => undefined,
|
||||
getMessage: async () => undefined,
|
||||
cachedGroupMetadata: async () => undefined,
|
||||
makeSignalRepository: makeLibSignalRepository
|
||||
}
|
||||
|
||||
@@ -77,19 +75,19 @@ export const MEDIA_PATH_MAP: { [T in MediaType]?: string } = {
|
||||
'thumbnail-link': '/mms/image',
|
||||
'product-catalog-image': '/product/image',
|
||||
'md-app-state': '',
|
||||
'md-msg-hist': '/mms/md-app-state',
|
||||
'md-msg-hist': '/mms/md-app-state'
|
||||
}
|
||||
|
||||
export const MEDIA_HKDF_KEY_MAPPING = {
|
||||
'audio': 'Audio',
|
||||
'document': 'Document',
|
||||
'gif': 'Video',
|
||||
'image': 'Image',
|
||||
'ppic': '',
|
||||
'product': 'Image',
|
||||
'ptt': 'Audio',
|
||||
'sticker': 'Image',
|
||||
'video': 'Video',
|
||||
audio: 'Audio',
|
||||
document: 'Document',
|
||||
gif: 'Video',
|
||||
image: 'Image',
|
||||
ppic: '',
|
||||
product: 'Image',
|
||||
ptt: 'Audio',
|
||||
sticker: 'Image',
|
||||
video: 'Video',
|
||||
'thumbnail-document': 'Document Thumbnail',
|
||||
'thumbnail-image': 'Image Thumbnail',
|
||||
'thumbnail-video': 'Video Thumbnail',
|
||||
@@ -98,7 +96,7 @@ export const MEDIA_HKDF_KEY_MAPPING = {
|
||||
'md-app-state': 'App State',
|
||||
'product-catalog-image': '',
|
||||
'payment-bg-image': 'Payment Background',
|
||||
'ptv': 'Video'
|
||||
ptv: 'Video'
|
||||
}
|
||||
|
||||
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
|
||||
MSG_RETRY: 60 * 60, // 1 hour
|
||||
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 { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage, SenderKeyName, SenderKeyRecord } from '../../WASignalGroup'
|
||||
import {
|
||||
GroupCipher,
|
||||
GroupSessionBuilder,
|
||||
SenderKeyDistributionMessage,
|
||||
SenderKeyName,
|
||||
SenderKeyRecord
|
||||
} from '../../WASignalGroup'
|
||||
import { SignalAuthState } from '../Types'
|
||||
import { SignalRepository } from '../Types/Signal'
|
||||
import { generateSignalPubKey } from '../Utils'
|
||||
@@ -18,9 +24,15 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
||||
const builder = new GroupSessionBuilder(storage)
|
||||
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])
|
||||
if(!senderKey) {
|
||||
if (!senderKey) {
|
||||
await storage.storeSenderKey(senderName, new SenderKeyRecord())
|
||||
}
|
||||
|
||||
@@ -54,7 +66,7 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
||||
const builder = new GroupSessionBuilder(storage)
|
||||
|
||||
const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
|
||||
if(!senderKey) {
|
||||
if (!senderKey) {
|
||||
await storage.storeSenderKey(senderName, new SenderKeyRecord())
|
||||
}
|
||||
|
||||
@@ -64,7 +76,7 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
||||
|
||||
return {
|
||||
ciphertext,
|
||||
senderKeyDistributionMessage: senderKeyDistributionMessage.serialize(),
|
||||
senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
|
||||
}
|
||||
},
|
||||
async injectE2ESession({ jid, session }) {
|
||||
@@ -73,7 +85,7 @@ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
|
||||
},
|
||||
jidToSignalProtocolAddress(jid) {
|
||||
return jidToSignalProtocolAddress(jid).toString()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,22 +100,22 @@ const jidToSignalSenderKeyName = (group: string, user: string): string => {
|
||||
|
||||
function signalStorage({ creds, keys }: SignalAuthState) {
|
||||
return {
|
||||
loadSession: async(id: string) => {
|
||||
loadSession: async (id: string) => {
|
||||
const { [id]: sess } = await keys.get('session', [id])
|
||||
if(sess) {
|
||||
if (sess) {
|
||||
return libsignal.SessionRecord.deserialize(sess)
|
||||
}
|
||||
},
|
||||
storeSession: async(id, session) => {
|
||||
await keys.set({ 'session': { [id]: session.serialize() } })
|
||||
storeSession: async (id, session) => {
|
||||
await keys.set({ session: { [id]: session.serialize() } })
|
||||
},
|
||||
isTrustedIdentity: () => {
|
||||
return true
|
||||
},
|
||||
loadPreKey: async(id: number | string) => {
|
||||
loadPreKey: async (id: number | string) => {
|
||||
const keyId = id.toString()
|
||||
const { [keyId]: key } = await keys.get('pre-key', [keyId])
|
||||
if(key) {
|
||||
if (key) {
|
||||
return {
|
||||
privKey: Buffer.from(key.private),
|
||||
pubKey: Buffer.from(key.public)
|
||||
@@ -118,23 +130,21 @@ function signalStorage({ creds, keys }: SignalAuthState) {
|
||||
pubKey: Buffer.from(key.keyPair.public)
|
||||
}
|
||||
},
|
||||
loadSenderKey: async(keyId: string) => {
|
||||
loadSenderKey: async (keyId: string) => {
|
||||
const { [keyId]: key } = await keys.get('sender-key', [keyId])
|
||||
if(key) {
|
||||
if (key) {
|
||||
return new SenderKeyRecord(key)
|
||||
}
|
||||
},
|
||||
storeSenderKey: async(keyId, key) => {
|
||||
storeSenderKey: async (keyId, key) => {
|
||||
await keys.set({ 'sender-key': { [keyId]: key.serialize() } })
|
||||
},
|
||||
getOurRegistrationId: () => (
|
||||
creds.registrationId
|
||||
),
|
||||
getOurRegistrationId: () => creds.registrationId,
|
||||
getOurIdentity: () => {
|
||||
const { signedIdentityKey } = creds
|
||||
return {
|
||||
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 isConnecting(): boolean
|
||||
|
||||
constructor(public url: URL, public config: SocketConfig) {
|
||||
constructor(
|
||||
public url: URL,
|
||||
public config: SocketConfig
|
||||
) {
|
||||
super()
|
||||
this.setMaxListeners(0)
|
||||
}
|
||||
|
||||
abstract connect(): 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'
|
||||
|
||||
export class WebSocketClient extends AbstractSocketClient {
|
||||
|
||||
protected socket: WebSocket | null = null
|
||||
|
||||
get isOpen(): boolean {
|
||||
@@ -20,7 +19,7 @@ export class WebSocketClient extends AbstractSocketClient {
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
if(this.socket) {
|
||||
if (this.socket) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -29,20 +28,20 @@ export class WebSocketClient extends AbstractSocketClient {
|
||||
headers: this.config.options?.headers as {},
|
||||
handshakeTimeout: this.config.connectTimeoutMs,
|
||||
timeout: this.config.connectTimeoutMs,
|
||||
agent: this.config.agent,
|
||||
agent: this.config.agent
|
||||
})
|
||||
|
||||
this.socket.setMaxListeners(0)
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if(!this.socket) {
|
||||
if (!this.socket) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,43 +1,46 @@
|
||||
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 { getBinaryNodeChild } from '../WABinary/generic-utils'
|
||||
import { makeMessagesRecvSocket } from './messages-recv'
|
||||
|
||||
export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
const sock = makeMessagesRecvSocket(config)
|
||||
const {
|
||||
authState,
|
||||
query,
|
||||
waUploadToServer
|
||||
} = sock
|
||||
const { 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 = jidNormalizedUser(jid)
|
||||
|
||||
const queryParamNodes: BinaryNode[] = [
|
||||
{
|
||||
tag: 'limit',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from((limit || 10).toString())
|
||||
},
|
||||
{
|
||||
tag: 'width',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from('100')
|
||||
},
|
||||
{
|
||||
tag: 'height',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from('100')
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
if(cursor) {
|
||||
if (cursor) {
|
||||
queryParamNodes.push({
|
||||
tag: 'after',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: cursor
|
||||
})
|
||||
}
|
||||
@@ -54,7 +57,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
tag: 'product_catalog',
|
||||
attrs: {
|
||||
jid,
|
||||
'allow_shop_source': 'true'
|
||||
allow_shop_source: 'true'
|
||||
},
|
||||
content: queryParamNodes
|
||||
}
|
||||
@@ -63,7 +66,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
return parseCatalogNode(result)
|
||||
}
|
||||
|
||||
const getCollections = async(jid?: string, limit = 51) => {
|
||||
const getCollections = async (jid?: string, limit = 51) => {
|
||||
jid = jid || authState.creds.me?.id
|
||||
jid = jidNormalizedUser(jid)
|
||||
const result = await query({
|
||||
@@ -72,33 +75,33 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'get',
|
||||
xmlns: 'w:biz:catalog',
|
||||
'smax_id': '35'
|
||||
smax_id: '35'
|
||||
},
|
||||
content: [
|
||||
{
|
||||
tag: 'collections',
|
||||
attrs: {
|
||||
'biz_jid': jid,
|
||||
biz_jid: jid
|
||||
},
|
||||
content: [
|
||||
{
|
||||
tag: 'collection_limit',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(limit.toString())
|
||||
},
|
||||
{
|
||||
tag: 'item_limit',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(limit.toString())
|
||||
},
|
||||
{
|
||||
tag: 'width',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from('100')
|
||||
},
|
||||
{
|
||||
tag: 'height',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from('100')
|
||||
}
|
||||
]
|
||||
@@ -109,14 +112,14 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
return parseCollectionsNode(result)
|
||||
}
|
||||
|
||||
const getOrderDetails = async(orderId: string, tokenBase64: string) => {
|
||||
const getOrderDetails = async (orderId: string, tokenBase64: string) => {
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'get',
|
||||
xmlns: 'fb:thrift_iq',
|
||||
'smax_id': '5'
|
||||
smax_id: '5'
|
||||
},
|
||||
content: [
|
||||
{
|
||||
@@ -128,23 +131,23 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
content: [
|
||||
{
|
||||
tag: 'image_dimensions',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{
|
||||
tag: 'width',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from('100')
|
||||
},
|
||||
{
|
||||
tag: 'height',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from('100')
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'token',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(tokenBase64)
|
||||
}
|
||||
]
|
||||
@@ -155,7 +158,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
return parseOrderDetailsNode(result)
|
||||
}
|
||||
|
||||
const productUpdate = async(productId: string, update: ProductUpdate) => {
|
||||
const productUpdate = async (productId: string, update: ProductUpdate) => {
|
||||
update = await uploadingNecessaryImagesOfProduct(update, waUploadToServer)
|
||||
const editNode = toProductNode(productId, update)
|
||||
|
||||
@@ -174,12 +177,12 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
editNode,
|
||||
{
|
||||
tag: 'width',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: '100'
|
||||
},
|
||||
{
|
||||
tag: 'height',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: '100'
|
||||
}
|
||||
]
|
||||
@@ -193,7 +196,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
return parseProductNode(productNode!)
|
||||
}
|
||||
|
||||
const productCreate = async(create: ProductCreate) => {
|
||||
const productCreate = async (create: ProductCreate) => {
|
||||
// ensure isHidden is defined
|
||||
create.isHidden = !!create.isHidden
|
||||
create = await uploadingNecessaryImagesOfProduct(create, waUploadToServer)
|
||||
@@ -214,12 +217,12 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
createNode,
|
||||
{
|
||||
tag: 'width',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: '100'
|
||||
},
|
||||
{
|
||||
tag: 'height',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: '100'
|
||||
}
|
||||
]
|
||||
@@ -233,7 +236,7 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
return parseProductNode(productNode!)
|
||||
}
|
||||
|
||||
const productDelete = async(productIds: string[]) => {
|
||||
const productDelete = async (productIds: string[]) => {
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
@@ -245,19 +248,17 @@ export const makeBusinessSocket = (config: SocketConfig) => {
|
||||
{
|
||||
tag: 'product_catalog_delete',
|
||||
attrs: { v: '1' },
|
||||
content: productIds.map(
|
||||
id => ({
|
||||
content: productIds.map(id => ({
|
||||
tag: 'product',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{
|
||||
tag: 'id',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(id)
|
||||
}
|
||||
]
|
||||
})
|
||||
)
|
||||
}))
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,62 +1,70 @@
|
||||
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 { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, jidEncode, jidNormalizedUser } from '../WABinary'
|
||||
import {
|
||||
BinaryNode,
|
||||
getBinaryNodeChild,
|
||||
getBinaryNodeChildren,
|
||||
getBinaryNodeChildString,
|
||||
jidEncode,
|
||||
jidNormalizedUser
|
||||
} from '../WABinary'
|
||||
import { makeChatsSocket } from './chats'
|
||||
|
||||
export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
const sock = makeChatsSocket(config)
|
||||
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({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
type,
|
||||
xmlns: 'w:g2',
|
||||
to: jid,
|
||||
to: jid
|
||||
},
|
||||
content
|
||||
})
|
||||
)
|
||||
|
||||
const groupMetadata = async(jid: string) => {
|
||||
const result = await groupQuery(
|
||||
jid,
|
||||
'get',
|
||||
[ { tag: 'query', attrs: { request: 'interactive' } } ]
|
||||
)
|
||||
const groupMetadata = async (jid: string) => {
|
||||
const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
|
||||
return extractGroupMetadata(result)
|
||||
}
|
||||
|
||||
|
||||
const groupFetchAllParticipating = async() => {
|
||||
const groupFetchAllParticipating = async () => {
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
to: '@g.us',
|
||||
xmlns: 'w:g2',
|
||||
type: 'get',
|
||||
type: 'get'
|
||||
},
|
||||
content: [
|
||||
{
|
||||
tag: 'participating',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{ tag: 'participants', attrs: { } },
|
||||
{ tag: 'description', attrs: { } }
|
||||
{ tag: 'participants', attrs: {} },
|
||||
{ tag: 'description', attrs: {} }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
const data: { [_: string]: GroupMetadata } = { }
|
||||
const data: { [_: string]: GroupMetadata } = {}
|
||||
const groupsChild = getBinaryNodeChild(result, 'groups')
|
||||
if(groupsChild) {
|
||||
if (groupsChild) {
|
||||
const groups = getBinaryNodeChildren(groupsChild, 'group')
|
||||
for(const groupNode of groups) {
|
||||
for (const groupNode of groups) {
|
||||
const meta = extractGroupMetadata({
|
||||
tag: 'result',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [groupNode]
|
||||
})
|
||||
data[meta.id] = meta
|
||||
@@ -68,9 +76,9 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
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')!
|
||||
if(attrs.type !== 'groups') {
|
||||
if (attrs.type !== 'groups') {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -81,12 +89,9 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
return {
|
||||
...sock,
|
||||
groupMetadata,
|
||||
groupCreate: async(subject: string, participants: string[]) => {
|
||||
groupCreate: async (subject: string, participants: string[]) => {
|
||||
const key = generateMessageIDV2()
|
||||
const result = await groupQuery(
|
||||
'@g.us',
|
||||
'set',
|
||||
[
|
||||
const result = await groupQuery('@g.us', 'set', [
|
||||
{
|
||||
tag: 'create',
|
||||
attrs: {
|
||||
@@ -98,72 +103,55 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
attrs: { jid }
|
||||
}))
|
||||
}
|
||||
]
|
||||
)
|
||||
])
|
||||
return extractGroupMetadata(result)
|
||||
},
|
||||
groupLeave: async(id: string) => {
|
||||
await groupQuery(
|
||||
'@g.us',
|
||||
'set',
|
||||
[
|
||||
groupLeave: async (id: string) => {
|
||||
await groupQuery('@g.us', 'set', [
|
||||
{
|
||||
tag: 'leave',
|
||||
attrs: { },
|
||||
content: [
|
||||
{ tag: 'group', attrs: { id } }
|
||||
]
|
||||
attrs: {},
|
||||
content: [{ tag: 'group', attrs: { id } }]
|
||||
}
|
||||
]
|
||||
)
|
||||
])
|
||||
},
|
||||
groupUpdateSubject: async(jid: string, subject: string) => {
|
||||
await groupQuery(
|
||||
jid,
|
||||
'set',
|
||||
[
|
||||
groupUpdateSubject: async (jid: string, subject: string) => {
|
||||
await groupQuery(jid, 'set', [
|
||||
{
|
||||
tag: 'subject',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(subject, 'utf-8')
|
||||
}
|
||||
]
|
||||
)
|
||||
])
|
||||
},
|
||||
groupRequestParticipantsList: async(jid: string) => {
|
||||
const result = await groupQuery(
|
||||
jid,
|
||||
'get',
|
||||
[
|
||||
groupRequestParticipantsList: async (jid: string) => {
|
||||
const result = await groupQuery(jid, 'get', [
|
||||
{
|
||||
tag: 'membership_approval_requests',
|
||||
attrs: {}
|
||||
}
|
||||
]
|
||||
)
|
||||
])
|
||||
const node = getBinaryNodeChild(result, 'membership_approval_requests')
|
||||
const participants = getBinaryNodeChildren(node, 'membership_approval_request')
|
||||
return participants.map(v => v.attrs)
|
||||
},
|
||||
groupRequestParticipantsUpdate: async(jid: string, participants: string[], action: 'approve' | 'reject') => {
|
||||
const result = await groupQuery(
|
||||
jid,
|
||||
'set',
|
||||
[{
|
||||
groupRequestParticipantsUpdate: async (jid: string, participants: string[], action: 'approve' | 'reject') => {
|
||||
const result = await groupQuery(jid, 'set', [
|
||||
{
|
||||
tag: 'membership_requests_action',
|
||||
attrs: {},
|
||||
content: [
|
||||
{
|
||||
tag: action,
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: participants.map(jid => ({
|
||||
tag: 'participant',
|
||||
attrs: { jid }
|
||||
}))
|
||||
}
|
||||
]
|
||||
}]
|
||||
)
|
||||
}
|
||||
])
|
||||
const node = getBinaryNodeChild(result, 'membership_requests_action')
|
||||
const nodeAction = getBinaryNodeChild(node, action)
|
||||
const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant')
|
||||
@@ -171,63 +159,49 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
return { status: p.attrs.error || '200', jid: p.attrs.jid }
|
||||
})
|
||||
},
|
||||
groupParticipantsUpdate: async(
|
||||
jid: string,
|
||||
participants: string[],
|
||||
action: ParticipantAction
|
||||
) => {
|
||||
const result = await groupQuery(
|
||||
jid,
|
||||
'set',
|
||||
[
|
||||
groupParticipantsUpdate: async (jid: string, participants: string[], action: ParticipantAction) => {
|
||||
const result = await groupQuery(jid, 'set', [
|
||||
{
|
||||
tag: action,
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: participants.map(jid => ({
|
||||
tag: 'participant',
|
||||
attrs: { jid }
|
||||
}))
|
||||
}
|
||||
]
|
||||
)
|
||||
])
|
||||
const node = getBinaryNodeChild(result, action)
|
||||
const participantsAffected = getBinaryNodeChildren(node, 'participant')
|
||||
return participantsAffected.map(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 prev = metadata.descId ?? null
|
||||
|
||||
await groupQuery(
|
||||
jid,
|
||||
'set',
|
||||
[
|
||||
await groupQuery(jid, 'set', [
|
||||
{
|
||||
tag: 'description',
|
||||
attrs: {
|
||||
...(description ? { id: generateMessageIDV2() } : { delete: 'true' }),
|
||||
...(prev ? { prev } : {})
|
||||
},
|
||||
content: description ? [
|
||||
{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }
|
||||
] : undefined
|
||||
content: description ? [{ 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 inviteNode = getBinaryNodeChild(result, 'invite')
|
||||
return inviteNode?.attrs.code
|
||||
},
|
||||
groupRevokeInvite: async(jid: string) => {
|
||||
groupRevokeInvite: async (jid: string) => {
|
||||
const result = await groupQuery(jid, 'set', [{ tag: 'invite', attrs: {} }])
|
||||
const inviteNode = getBinaryNodeChild(result, 'invite')
|
||||
return inviteNode?.attrs.code
|
||||
},
|
||||
groupAcceptInvite: async(code: string) => {
|
||||
groupAcceptInvite: async (code: string) => {
|
||||
const results = await groupQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }])
|
||||
const result = getBinaryNodeChild(results, 'group')
|
||||
return result?.attrs.jid
|
||||
@@ -239,8 +213,10 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
* @param invitedJid jid of person you invited
|
||||
* @returns true if successful
|
||||
*/
|
||||
groupRevokeInviteV4: async(groupJid: string, invitedJid: string) => {
|
||||
const result = await groupQuery(groupJid, 'set', [{ tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }])
|
||||
groupRevokeInviteV4: async (groupJid: string, invitedJid: string) => {
|
||||
const result = await groupQuery(groupJid, 'set', [
|
||||
{ tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
|
||||
])
|
||||
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 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
|
||||
const results = await groupQuery(inviteMessage.groupJid!, 'set', [{
|
||||
const results = await groupQuery(inviteMessage.groupJid!, 'set', [
|
||||
{
|
||||
tag: 'accept',
|
||||
attrs: {
|
||||
code: inviteMessage.inviteCode!,
|
||||
expiration: inviteMessage.inviteExpiration!.toString(),
|
||||
admin: key.remoteJid!
|
||||
}
|
||||
}])
|
||||
}
|
||||
])
|
||||
|
||||
// if we have the full message key
|
||||
// update the invite message to be expired
|
||||
if(key.id) {
|
||||
if (key.id) {
|
||||
// create new invite message that is expired
|
||||
inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage)
|
||||
inviteMessage.inviteExpiration = 0
|
||||
@@ -286,12 +265,10 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
remoteJid: inviteMessage.groupJid,
|
||||
id: generateMessageIDV2(sock.user?.id),
|
||||
fromMe: false,
|
||||
participant: key.remoteJid,
|
||||
participant: key.remoteJid
|
||||
},
|
||||
messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
|
||||
messageStubParameters: [
|
||||
authState.creds.me!.id
|
||||
],
|
||||
messageStubParameters: [authState.creds.me!.id],
|
||||
participant: key.remoteJid,
|
||||
messageTimestamp: unixTimestampSeconds()
|
||||
},
|
||||
@@ -299,37 +276,39 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
||||
)
|
||||
|
||||
return results.attrs.from
|
||||
}),
|
||||
groupGetInviteInfo: async(code: string) => {
|
||||
}
|
||||
),
|
||||
groupGetInviteInfo: async (code: string) => {
|
||||
const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
|
||||
return extractGroupMetadata(results)
|
||||
},
|
||||
groupToggleEphemeral: async(jid: string, ephemeralExpiration: number) => {
|
||||
const content: BinaryNode = ephemeralExpiration ?
|
||||
{ tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } } :
|
||||
{ tag: 'not_ephemeral', attrs: { } }
|
||||
groupToggleEphemeral: async (jid: string, ephemeralExpiration: number) => {
|
||||
const content: BinaryNode = ephemeralExpiration
|
||||
? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
|
||||
: { tag: 'not_ephemeral', attrs: {} }
|
||||
await groupQuery(jid, 'set', [content])
|
||||
},
|
||||
groupSettingUpdate: async(jid: string, setting: 'announcement' | 'not_announcement' | 'locked' | 'unlocked') => {
|
||||
await groupQuery(jid, 'set', [ { tag: setting, attrs: { } } ])
|
||||
groupSettingUpdate: async (jid: string, setting: 'announcement' | 'not_announcement' | 'locked' | 'unlocked') => {
|
||||
await groupQuery(jid, 'set', [{ tag: setting, attrs: {} }])
|
||||
},
|
||||
groupMemberAddMode: async(jid: string, mode: 'admin_add' | 'all_member_add') => {
|
||||
await groupQuery(jid, 'set', [ { tag: 'member_add_mode', attrs: { }, content: mode } ])
|
||||
groupMemberAddMode: async (jid: string, mode: 'admin_add' | 'all_member_add') => {
|
||||
await groupQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }])
|
||||
},
|
||||
groupJoinApprovalMode: async(jid: string, mode: 'on' | 'off') => {
|
||||
await groupQuery(jid, 'set', [ { tag: 'membership_approval_mode', attrs: { }, content: [ { tag: 'group_join', attrs: { state: mode } } ] } ])
|
||||
groupJoinApprovalMode: async (jid: string, mode: 'on' | 'off') => {
|
||||
await groupQuery(jid, 'set', [
|
||||
{ tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'group_join', attrs: { state: mode } }] }
|
||||
])
|
||||
},
|
||||
groupFetchAllParticipating
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export const extractGroupMetadata = (result: BinaryNode) => {
|
||||
const group = getBinaryNodeChild(result, 'group')!
|
||||
const descChild = getBinaryNodeChild(group, 'description')
|
||||
let desc: string | undefined
|
||||
let descId: string | undefined
|
||||
if(descChild) {
|
||||
if (descChild) {
|
||||
desc = getBinaryNodeChildString(descChild, 'body')
|
||||
descId = descChild.attrs.id
|
||||
}
|
||||
@@ -339,7 +318,7 @@ export const extractGroupMetadata = (result: BinaryNode) => {
|
||||
const memberAddMode = getBinaryNodeChildString(group, 'member_add_mode') === 'all_member_add'
|
||||
const metadata: GroupMetadata = {
|
||||
id: groupId,
|
||||
addressingMode: group.attrs.addressing_mode as "pn" | "lid",
|
||||
addressingMode: group.attrs.addressing_mode as 'pn' | 'lid',
|
||||
subject: group.attrs.subject,
|
||||
subjectOwner: group.attrs.s_o,
|
||||
subjectTime: +group.attrs.s_t,
|
||||
@@ -355,14 +334,12 @@ export const extractGroupMetadata = (result: BinaryNode) => {
|
||||
isCommunityAnnounce: !!getBinaryNodeChild(group, 'default_sub_group'),
|
||||
joinApprovalMode: !!getBinaryNodeChild(group, 'membership_approval_mode'),
|
||||
memberAddMode,
|
||||
participants: getBinaryNodeChildren(group, 'participant').map(
|
||||
({ attrs }) => {
|
||||
participants: getBinaryNodeChildren(group, 'participant').map(({ attrs }) => {
|
||||
return {
|
||||
id: attrs.jid,
|
||||
admin: (attrs.type || null) as GroupParticipant['admin'],
|
||||
admin: (attrs.type || null) as GroupParticipant['admin']
|
||||
}
|
||||
}
|
||||
),
|
||||
}),
|
||||
ephemeralDuration: eph ? +eph : undefined
|
||||
}
|
||||
return metadata
|
||||
|
||||
@@ -3,11 +3,10 @@ import { UserFacingSocketConfig } from '../Types'
|
||||
import { makeBusinessSocket } from './business'
|
||||
|
||||
// export the last socket layer
|
||||
const makeWASocket = (config: UserFacingSocketConfig) => (
|
||||
const makeWASocket = (config: UserFacingSocketConfig) =>
|
||||
makeBusinessSocket({
|
||||
...DEFAULT_CONNECTION_CONFIG,
|
||||
...config
|
||||
})
|
||||
)
|
||||
|
||||
export default makeWASocket
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,49 @@
|
||||
|
||||
import NodeCache from '@cacheable/node-cache'
|
||||
import { Boom } from '@hapi/boom'
|
||||
import { proto } from '../../WAProto'
|
||||
import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults'
|
||||
import { 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 {
|
||||
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 { 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 { makeGroupsSocket } from './groups'
|
||||
|
||||
@@ -17,7 +54,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
generateHighQualityLinkPreview,
|
||||
options: axiosOptions,
|
||||
patchMessageBeforeSending,
|
||||
cachedGroupMetadata,
|
||||
cachedGroupMetadata
|
||||
} = config
|
||||
const sock = makeGroupsSocket(config)
|
||||
const {
|
||||
@@ -30,36 +67,36 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
fetchPrivacySettings,
|
||||
sendNode,
|
||||
groupMetadata,
|
||||
groupToggleEphemeral,
|
||||
groupToggleEphemeral
|
||||
} = sock
|
||||
|
||||
const userDevicesCache = config.userDevicesCache || new NodeCache({
|
||||
const userDevicesCache =
|
||||
config.userDevicesCache ||
|
||||
new NodeCache({
|
||||
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
||||
useClones: false
|
||||
})
|
||||
|
||||
let mediaConn: Promise<MediaConnInfo>
|
||||
const refreshMediaConn = async(forceGet = false) => {
|
||||
const refreshMediaConn = async (forceGet = false) => {
|
||||
const media = await mediaConn
|
||||
if(!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
|
||||
mediaConn = (async() => {
|
||||
if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
|
||||
mediaConn = (async () => {
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
type: 'set',
|
||||
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 node: MediaConnInfo = {
|
||||
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(
|
||||
({ attrs }) => ({
|
||||
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
|
||||
hostname: attrs.hostname,
|
||||
maxContentLengthBytes: +attrs.maxContentLengthBytes,
|
||||
})
|
||||
),
|
||||
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
||||
})),
|
||||
auth: mediaConnNode!.attrs.auth,
|
||||
ttl: +mediaConnNode!.attrs.ttl,
|
||||
fetchDate: new Date()
|
||||
@@ -76,38 +113,43 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
* generic send receipt function
|
||||
* 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 = {
|
||||
tag: 'receipt',
|
||||
attrs: {
|
||||
id: messageIds[0],
|
||||
},
|
||||
id: messageIds[0]
|
||||
}
|
||||
}
|
||||
const isReadReceipt = type === 'read' || type === 'read-self'
|
||||
if(isReadReceipt) {
|
||||
if (isReadReceipt) {
|
||||
node.attrs.t = unixTimestampSeconds().toString()
|
||||
}
|
||||
|
||||
if(type === 'sender' && isJidUser(jid)) {
|
||||
if (type === 'sender' && isJidUser(jid)) {
|
||||
node.attrs.recipient = jid
|
||||
node.attrs.to = participant!
|
||||
} else {
|
||||
node.attrs.to = jid
|
||||
if(participant) {
|
||||
if (participant) {
|
||||
node.attrs.participant = participant
|
||||
}
|
||||
}
|
||||
|
||||
if(type) {
|
||||
if (type) {
|
||||
node.attrs.type = type
|
||||
}
|
||||
|
||||
const remainingMessageIds = messageIds.slice(1)
|
||||
if(remainingMessageIds.length) {
|
||||
if (remainingMessageIds.length) {
|
||||
node.content = [
|
||||
{
|
||||
tag: 'list',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: remainingMessageIds.map(id => ({
|
||||
tag: 'item',
|
||||
attrs: { id }
|
||||
@@ -121,15 +163,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
/** 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)
|
||||
for(const { jid, participant, messageIds } of recps) {
|
||||
for (const { jid, participant, messageIds } of recps) {
|
||||
await sendReceipt(jid, participant, messageIds, type)
|
||||
}
|
||||
}
|
||||
|
||||
/** Bulk read messages. Keys can be from different chats & participants */
|
||||
const readMessages = async(keys: WAMessageKey[]) => {
|
||||
const readMessages = async (keys: WAMessageKey[]) => {
|
||||
const privacySettings = await fetchPrivacySettings()
|
||||
// based on privacy settings, we have to change the read type
|
||||
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 */
|
||||
const getUSyncDevices = async(jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => {
|
||||
const getUSyncDevices = async (jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => {
|
||||
const deviceResults: JidWithDevice[] = []
|
||||
|
||||
if(!useCache) {
|
||||
if (!useCache) {
|
||||
logger.debug('not using cache for devices')
|
||||
}
|
||||
|
||||
const toFetch: string[] = []
|
||||
jids = Array.from(new Set(jids))
|
||||
|
||||
for(let jid of jids) {
|
||||
for (let jid of jids) {
|
||||
const user = jidDecode(jid)?.user
|
||||
jid = jidNormalizedUser(jid)
|
||||
if(useCache) {
|
||||
if (useCache) {
|
||||
const devices = userDevicesCache.get<JidWithDevice[]>(user!)
|
||||
if(devices) {
|
||||
if (devices) {
|
||||
deviceResults.push(...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
|
||||
}
|
||||
|
||||
const query = new USyncQuery()
|
||||
.withContext('message')
|
||||
.withDeviceProtocol()
|
||||
const query = new USyncQuery().withContext('message').withDeviceProtocol()
|
||||
|
||||
for(const jid of toFetch) {
|
||||
for (const jid of toFetch) {
|
||||
query.withUser(new USyncUser().withId(jid))
|
||||
}
|
||||
|
||||
const result = await sock.executeUSyncQuery(query)
|
||||
|
||||
if(result) {
|
||||
if (result) {
|
||||
const extracted = extractDeviceJids(result?.list, authState.creds.me!.id, ignoreZeroDevices)
|
||||
const deviceMap: { [_: string]: JidWithDevice[] } = {}
|
||||
|
||||
for(const item of extracted) {
|
||||
for (const item of extracted) {
|
||||
deviceMap[item.user] = deviceMap[item.user] || []
|
||||
deviceMap[item.user].push(item)
|
||||
|
||||
deviceResults.push(item)
|
||||
}
|
||||
|
||||
for(const key in deviceMap) {
|
||||
for (const key in deviceMap) {
|
||||
userDevicesCache.set(key, deviceMap[key])
|
||||
}
|
||||
}
|
||||
@@ -197,45 +237,39 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
return deviceResults
|
||||
}
|
||||
|
||||
const assertSessions = async(jids: string[], force: boolean) => {
|
||||
const assertSessions = async (jids: string[], force: boolean) => {
|
||||
let didFetchNewSession = false
|
||||
let jidsRequiringFetch: string[] = []
|
||||
if(force) {
|
||||
if (force) {
|
||||
jidsRequiringFetch = jids
|
||||
} else {
|
||||
const addrs = jids.map(jid => (
|
||||
signalRepository
|
||||
.jidToSignalProtocolAddress(jid)
|
||||
))
|
||||
const addrs = jids.map(jid => signalRepository.jidToSignalProtocolAddress(jid))
|
||||
const sessions = await authState.keys.get('session', addrs)
|
||||
for(const jid of jids) {
|
||||
const signalId = signalRepository
|
||||
.jidToSignalProtocolAddress(jid)
|
||||
if(!sessions[signalId]) {
|
||||
for (const jid of jids) {
|
||||
const signalId = signalRepository.jidToSignalProtocolAddress(jid)
|
||||
if (!sessions[signalId]) {
|
||||
jidsRequiringFetch.push(jid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(jidsRequiringFetch.length) {
|
||||
if (jidsRequiringFetch.length) {
|
||||
logger.debug({ jidsRequiringFetch }, 'fetching sessions')
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
xmlns: 'encrypt',
|
||||
type: 'get',
|
||||
to: S_WHATSAPP_NET,
|
||||
to: S_WHATSAPP_NET
|
||||
},
|
||||
content: [
|
||||
{
|
||||
tag: 'key',
|
||||
attrs: { },
|
||||
content: jidsRequiringFetch.map(
|
||||
jid => ({
|
||||
attrs: {},
|
||||
content: jidsRequiringFetch.map(jid => ({
|
||||
tag: 'user',
|
||||
attrs: { jid },
|
||||
})
|
||||
)
|
||||
attrs: { jid }
|
||||
}))
|
||||
}
|
||||
]
|
||||
})
|
||||
@@ -247,11 +281,11 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
return didFetchNewSession
|
||||
}
|
||||
|
||||
const sendPeerDataOperationMessage = async(
|
||||
const sendPeerDataOperationMessage = async (
|
||||
pdoMessage: proto.Message.IPeerDataOperationRequestMessage
|
||||
): 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
|
||||
if(!authState.creds.me?.id) {
|
||||
if (!authState.creds.me?.id) {
|
||||
throw new Boom('Not authenticated')
|
||||
}
|
||||
|
||||
@@ -268,64 +302,67 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
additionalAttributes: {
|
||||
category: 'peer',
|
||||
// eslint-disable-next-line camelcase
|
||||
push_priority: 'high_force',
|
||||
},
|
||||
push_priority: 'high_force'
|
||||
}
|
||||
})
|
||||
|
||||
return msgId
|
||||
}
|
||||
|
||||
const createParticipantNodes = async(
|
||||
jids: string[],
|
||||
message: proto.IMessage,
|
||||
extraAttrs?: BinaryNode['attrs']
|
||||
) => {
|
||||
const createParticipantNodes = async (jids: string[], message: proto.IMessage, extraAttrs?: BinaryNode['attrs']) => {
|
||||
let patched = await patchMessageBeforeSending(message, jids)
|
||||
if(!Array.isArray(patched)) {
|
||||
if (!Array.isArray(patched)) {
|
||||
patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched]
|
||||
}
|
||||
|
||||
let shouldIncludeDeviceIdentity = false
|
||||
|
||||
const nodes = await Promise.all(
|
||||
patched.map(
|
||||
async patchedMessageWithJid => {
|
||||
patched.map(async patchedMessageWithJid => {
|
||||
const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid
|
||||
if(!jid) {
|
||||
if (!jid) {
|
||||
return {} as BinaryNode
|
||||
}
|
||||
|
||||
const bytes = encodeWAMessage(patchedMessage)
|
||||
const { type, ciphertext } = await signalRepository
|
||||
.encryptMessage({ jid, data: bytes })
|
||||
if(type === 'pkmsg') {
|
||||
const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
|
||||
if (type === 'pkmsg') {
|
||||
shouldIncludeDeviceIdentity = true
|
||||
}
|
||||
|
||||
const node: BinaryNode = {
|
||||
tag: 'to',
|
||||
attrs: { jid },
|
||||
content: [{
|
||||
content: [
|
||||
{
|
||||
tag: 'enc',
|
||||
attrs: {
|
||||
v: '2',
|
||||
type,
|
||||
...extraAttrs || {}
|
||||
...(extraAttrs || {})
|
||||
},
|
||||
content: ciphertext
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
return node
|
||||
}
|
||||
)
|
||||
})
|
||||
)
|
||||
return { nodes, shouldIncludeDeviceIdentity }
|
||||
}
|
||||
|
||||
const relayMessage = async(
|
||||
const relayMessage = async (
|
||||
jid: string,
|
||||
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
|
||||
|
||||
@@ -342,7 +379,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
|
||||
|
||||
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 devices: JidWithDevice[] = []
|
||||
|
||||
@@ -355,58 +392,57 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
|
||||
const extraAttrs = {}
|
||||
|
||||
if(participant) {
|
||||
if (participant) {
|
||||
// when the retry request is not for a group
|
||||
// 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
|
||||
if(!isGroup && !isStatus) {
|
||||
additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' }
|
||||
if (!isGroup && !isStatus) {
|
||||
additionalAttributes = { ...additionalAttributes, device_fanout: 'false' }
|
||||
}
|
||||
|
||||
const { user, device } = jidDecode(participant.jid)!
|
||||
devices.push({ user, device })
|
||||
}
|
||||
|
||||
await authState.keys.transaction(
|
||||
async() => {
|
||||
await authState.keys.transaction(async () => {
|
||||
const mediaType = getMediaType(message)
|
||||
if(mediaType) {
|
||||
if (mediaType) {
|
||||
extraAttrs['mediatype'] = mediaType
|
||||
}
|
||||
|
||||
if(normalizeMessageContent(message)?.pinInChatMessage) {
|
||||
if (normalizeMessageContent(message)?.pinInChatMessage) {
|
||||
extraAttrs['decrypt-fail'] = 'hide'
|
||||
}
|
||||
|
||||
if(isGroup || isStatus) {
|
||||
if (isGroup || isStatus) {
|
||||
const [groupData, senderKeyMap] = await Promise.all([
|
||||
(async() => {
|
||||
(async () => {
|
||||
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')
|
||||
} else if(!isStatus) {
|
||||
} else if (!isStatus) {
|
||||
groupData = await groupMetadata(jid)
|
||||
}
|
||||
|
||||
return groupData
|
||||
})(),
|
||||
(async() => {
|
||||
if(!participant && !isStatus) {
|
||||
(async () => {
|
||||
if (!participant && !isStatus) {
|
||||
const result = await authState.keys.get('sender-key-memory', [jid])
|
||||
return result[jid] || { }
|
||||
return result[jid] || {}
|
||||
}
|
||||
|
||||
return { }
|
||||
return {}
|
||||
})()
|
||||
])
|
||||
|
||||
if(!participant) {
|
||||
const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
|
||||
if(isStatus && statusJidList) {
|
||||
if (!participant) {
|
||||
const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : []
|
||||
if (isStatus && statusJidList) {
|
||||
participantsList.push(...statusJidList)
|
||||
}
|
||||
|
||||
if(!isStatus) {
|
||||
if (!isStatus) {
|
||||
additionalAttributes = {
|
||||
...additionalAttributes,
|
||||
addressing_mode: groupData?.addressingMode || 'pn'
|
||||
@@ -419,25 +455,23 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
|
||||
const patched = await patchMessageBeforeSending(message)
|
||||
|
||||
if(Array.isArray(patched)) {
|
||||
if (Array.isArray(patched)) {
|
||||
throw new Boom('Per-jid patching is not supported in groups')
|
||||
}
|
||||
|
||||
const bytes = encodeWAMessage(patched)
|
||||
|
||||
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage(
|
||||
{
|
||||
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
||||
group: destinationJid,
|
||||
data: bytes,
|
||||
meId,
|
||||
}
|
||||
)
|
||||
meId
|
||||
})
|
||||
|
||||
const senderKeyJids: string[] = []
|
||||
// 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)
|
||||
if(!senderKeyMap[jid] || !!participant) {
|
||||
if (!senderKeyMap[jid] || !!participant) {
|
||||
senderKeyJids.push(jid)
|
||||
// store that this person has had the sender keys sent to them
|
||||
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, we re-send the senderkey
|
||||
if(senderKeyJids.length) {
|
||||
if (senderKeyJids.length) {
|
||||
logger.debug({ senderKeyJids }, 'sending new sender key')
|
||||
|
||||
const senderKeyMsg: proto.IMessage = {
|
||||
@@ -474,14 +508,14 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
} else {
|
||||
const { user: meUser } = jidDecode(meId)!
|
||||
|
||||
if(!participant) {
|
||||
if (!participant) {
|
||||
devices.push({ user })
|
||||
if(user !== meUser) {
|
||||
if (user !== meUser) {
|
||||
devices.push({ user: meUser })
|
||||
}
|
||||
|
||||
if(additionalAttributes?.['category'] !== 'peer') {
|
||||
const additionalDevices = await getUSyncDevices([ meId, jid ], !!useUserDevicesCache, true)
|
||||
if (additionalAttributes?.['category'] !== 'peer') {
|
||||
const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
|
||||
devices.push(...additionalDevices)
|
||||
}
|
||||
}
|
||||
@@ -489,10 +523,14 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
const allJids: string[] = []
|
||||
const meJids: string[] = []
|
||||
const otherJids: string[] = []
|
||||
for(const { user, device } of devices) {
|
||||
for (const { user, device } of devices) {
|
||||
const isMe = user === meUser
|
||||
const jid = jidEncode(isMe && isLid ? authState.creds?.me?.lid!.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
|
||||
if(isMe) {
|
||||
const jid = jidEncode(
|
||||
isMe && isLid ? authState.creds?.me?.lid!.split(':')[0] || user : user,
|
||||
isLid ? 'lid' : 's.whatsapp.net',
|
||||
device
|
||||
)
|
||||
if (isMe) {
|
||||
meJids.push(jid)
|
||||
} else {
|
||||
otherJids.push(jid)
|
||||
@@ -516,16 +554,16 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
|
||||
}
|
||||
|
||||
if(participants.length) {
|
||||
if(additionalAttributes?.['category'] === 'peer') {
|
||||
if (participants.length) {
|
||||
if (additionalAttributes?.['category'] === 'peer') {
|
||||
const peerNode = participants[0]?.content?.[0] as BinaryNode
|
||||
if(peerNode) {
|
||||
if (peerNode) {
|
||||
binaryNodeContent.push(peerNode) // push only enc
|
||||
}
|
||||
} else {
|
||||
binaryNodeContent.push({
|
||||
tag: 'participants',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: participants
|
||||
})
|
||||
}
|
||||
@@ -543,11 +581,11 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
// if the participant to send to is explicitly specified (generally retry recp)
|
||||
// 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(participant) {
|
||||
if(isJidGroup(destinationJid)) {
|
||||
if (participant) {
|
||||
if (isJidGroup(destinationJid)) {
|
||||
stanza.attrs.to = destinationJid
|
||||
stanza.attrs.participant = participant.jid
|
||||
} else if(areJidsSameUser(participant.jid, meId)) {
|
||||
} else if (areJidsSameUser(participant.jid, meId)) {
|
||||
stanza.attrs.to = participant.jid
|
||||
stanza.attrs.recipient = destinationJid
|
||||
} else {
|
||||
@@ -557,32 +595,30 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
stanza.attrs.to = destinationJid
|
||||
}
|
||||
|
||||
if(shouldIncludeDeviceIdentity) {
|
||||
(stanza.content as BinaryNode[]).push({
|
||||
if (shouldIncludeDeviceIdentity) {
|
||||
;(stanza.content as BinaryNode[]).push({
|
||||
tag: 'device-identity',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: encodeSignedDeviceIdentity(authState.creds.account!, true)
|
||||
})
|
||||
|
||||
logger.debug({ jid }, 'adding device identity')
|
||||
}
|
||||
|
||||
if(additionalNodes && additionalNodes.length > 0) {
|
||||
(stanza.content as BinaryNode[]).push(...additionalNodes)
|
||||
if (additionalNodes && additionalNodes.length > 0) {
|
||||
;(stanza.content as BinaryNode[]).push(...additionalNodes)
|
||||
}
|
||||
|
||||
logger.debug({ msgId }, `sending message to ${participants.length} devices`)
|
||||
|
||||
await sendNode(stanza)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
return msgId
|
||||
}
|
||||
|
||||
|
||||
const getMessageType = (message: proto.IMessage) => {
|
||||
if(message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
|
||||
if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
|
||||
return 'poll'
|
||||
}
|
||||
|
||||
@@ -590,40 +626,40 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
const getMediaType = (message: proto.IMessage) => {
|
||||
if(message.imageMessage) {
|
||||
if (message.imageMessage) {
|
||||
return 'image'
|
||||
} else if(message.videoMessage) {
|
||||
} else if (message.videoMessage) {
|
||||
return message.videoMessage.gifPlayback ? 'gif' : 'video'
|
||||
} else if(message.audioMessage) {
|
||||
} else if (message.audioMessage) {
|
||||
return message.audioMessage.ptt ? 'ptt' : 'audio'
|
||||
} else if(message.contactMessage) {
|
||||
} else if (message.contactMessage) {
|
||||
return 'vcard'
|
||||
} else if(message.documentMessage) {
|
||||
} else if (message.documentMessage) {
|
||||
return 'document'
|
||||
} else if(message.contactsArrayMessage) {
|
||||
} else if (message.contactsArrayMessage) {
|
||||
return 'contact_array'
|
||||
} else if(message.liveLocationMessage) {
|
||||
} else if (message.liveLocationMessage) {
|
||||
return 'livelocation'
|
||||
} else if(message.stickerMessage) {
|
||||
} else if (message.stickerMessage) {
|
||||
return 'sticker'
|
||||
} else if(message.listMessage) {
|
||||
} else if (message.listMessage) {
|
||||
return 'list'
|
||||
} else if(message.listResponseMessage) {
|
||||
} else if (message.listResponseMessage) {
|
||||
return 'list_response'
|
||||
} else if(message.buttonsResponseMessage) {
|
||||
} else if (message.buttonsResponseMessage) {
|
||||
return 'buttons_response'
|
||||
} else if(message.orderMessage) {
|
||||
} else if (message.orderMessage) {
|
||||
return 'order'
|
||||
} else if(message.productMessage) {
|
||||
} else if (message.productMessage) {
|
||||
return 'product'
|
||||
} else if(message.interactiveResponseMessage) {
|
||||
} else if (message.interactiveResponseMessage) {
|
||||
return 'native_flow_response'
|
||||
} else if(message.groupInviteMessage) {
|
||||
} else if (message.groupInviteMessage) {
|
||||
return 'url'
|
||||
}
|
||||
}
|
||||
|
||||
const getPrivacyTokens = async(jids: string[]) => {
|
||||
const getPrivacyTokens = async (jids: string[]) => {
|
||||
const t = unixTimestampSeconds().toString()
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
@@ -635,17 +671,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
content: [
|
||||
{
|
||||
tag: 'tokens',
|
||||
attrs: { },
|
||||
content: jids.map(
|
||||
jid => ({
|
||||
attrs: {},
|
||||
content: jids.map(jid => ({
|
||||
tag: 'token',
|
||||
attrs: {
|
||||
jid: jidNormalizedUser(jid),
|
||||
t,
|
||||
type: 'trusted_contact'
|
||||
}
|
||||
})
|
||||
)
|
||||
}))
|
||||
}
|
||||
]
|
||||
})
|
||||
@@ -671,37 +705,36 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
sendPeerDataOperationMessage,
|
||||
createParticipantNodes,
|
||||
getUSyncDevices,
|
||||
updateMediaMessage: async(message: proto.IWebMessageInfo) => {
|
||||
updateMediaMessage: async (message: proto.IWebMessageInfo) => {
|
||||
const content = assertMediaContent(message.message)
|
||||
const mediaKey = content.mediaKey!
|
||||
const meId = authState.creds.me!.id
|
||||
const node = await encryptMediaRetryRequest(message.key, mediaKey, meId)
|
||||
|
||||
let error: Error | undefined = undefined
|
||||
await Promise.all(
|
||||
[
|
||||
await Promise.all([
|
||||
sendNode(node),
|
||||
waitForMsgMediaUpdate(async(update) => {
|
||||
waitForMsgMediaUpdate(async update => {
|
||||
const result = update.find(c => c.key.id === message.key.id)
|
||||
if(result) {
|
||||
if(result.error) {
|
||||
if (result) {
|
||||
if (result.error) {
|
||||
error = result.error
|
||||
} else {
|
||||
try {
|
||||
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!]
|
||||
throw new Boom(
|
||||
`Media re-upload failed by device (${resultStr})`,
|
||||
{ data: media, statusCode: getStatusCodeForMediaRetry(media.result!) || 404 }
|
||||
)
|
||||
throw new Boom(`Media re-upload failed by device (${resultStr})`, {
|
||||
data: media,
|
||||
statusCode: getStatusCodeForMediaRetry(media.result!) || 404
|
||||
})
|
||||
}
|
||||
|
||||
content.directPath = media.directPath
|
||||
content.url = getUrlFromDirectPath(content.directPath!)
|
||||
|
||||
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
error = err
|
||||
}
|
||||
}
|
||||
@@ -709,103 +742,97 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
||||
return true
|
||||
}
|
||||
})
|
||||
]
|
||||
)
|
||||
])
|
||||
|
||||
if(error) {
|
||||
if (error) {
|
||||
throw error
|
||||
}
|
||||
|
||||
ev.emit('messages.update', [
|
||||
{ key: message.key, update: { message: message.message } }
|
||||
])
|
||||
ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }])
|
||||
|
||||
return message
|
||||
},
|
||||
sendMessage: async(
|
||||
jid: string,
|
||||
content: AnyMessageContent,
|
||||
options: MiscMessageGenerationOptions = { }
|
||||
) => {
|
||||
sendMessage: async (jid: string, content: AnyMessageContent, options: MiscMessageGenerationOptions = {}) => {
|
||||
const userJid = authState.creds.me!.id
|
||||
if(
|
||||
if (
|
||||
typeof content === 'object' &&
|
||||
'disappearingMessagesInChat' in content &&
|
||||
typeof content['disappearingMessagesInChat'] !== 'undefined' &&
|
||||
isJidGroup(jid)
|
||||
) {
|
||||
const { disappearingMessagesInChat } = content
|
||||
const value = typeof disappearingMessagesInChat === 'boolean' ?
|
||||
(disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) :
|
||||
disappearingMessagesInChat
|
||||
const value =
|
||||
typeof disappearingMessagesInChat === 'boolean'
|
||||
? disappearingMessagesInChat
|
||||
? WA_DEFAULT_EPHEMERAL
|
||||
: 0
|
||||
: disappearingMessagesInChat
|
||||
await groupToggleEphemeral(jid, value)
|
||||
} else {
|
||||
const fullMsg = await generateWAMessage(
|
||||
jid,
|
||||
content,
|
||||
{
|
||||
const fullMsg = await generateWAMessage(jid, content, {
|
||||
logger,
|
||||
userJid,
|
||||
getUrlInfo: text => getUrlInfo(
|
||||
text,
|
||||
{
|
||||
getUrlInfo: text =>
|
||||
getUrlInfo(text, {
|
||||
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
||||
fetchOpts: {
|
||||
timeout: 3_000,
|
||||
...axiosOptions || { }
|
||||
...(axiosOptions || {})
|
||||
},
|
||||
logger,
|
||||
uploadImage: generateHighQualityLinkPreview
|
||||
? waUploadToServer
|
||||
: undefined
|
||||
},
|
||||
),
|
||||
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
||||
}),
|
||||
//TODO: CACHE
|
||||
getProfilePicUrl: sock.profilePictureUrl,
|
||||
upload: waUploadToServer,
|
||||
mediaCache: config.mediaCache,
|
||||
options: config.options,
|
||||
messageId: generateMessageIDV2(sock.user?.id),
|
||||
...options,
|
||||
}
|
||||
)
|
||||
...options
|
||||
})
|
||||
const isDeleteMsg = 'delete' in content && !!content.delete
|
||||
const isEditMsg = 'edit' in content && !!content.edit
|
||||
const isPinMsg = 'pin' in content && !!content.pin
|
||||
const isPollMessage = 'poll' in content && !!content.poll
|
||||
const additionalAttributes: BinaryNodeAttributes = { }
|
||||
const additionalAttributes: BinaryNodeAttributes = {}
|
||||
const additionalNodes: BinaryNode[] = []
|
||||
// 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(isJidGroup(content.delete?.remoteJid as string) && !content.delete?.fromMe) {
|
||||
if (isJidGroup(content.delete?.remoteJid as string) && !content.delete?.fromMe) {
|
||||
additionalAttributes.edit = '8'
|
||||
} else {
|
||||
additionalAttributes.edit = '7'
|
||||
}
|
||||
} else if(isEditMsg) {
|
||||
} else if (isEditMsg) {
|
||||
additionalAttributes.edit = '1'
|
||||
} else if(isPinMsg) {
|
||||
} else if (isPinMsg) {
|
||||
additionalAttributes.edit = '2'
|
||||
} else if(isPollMessage) {
|
||||
} else if (isPollMessage) {
|
||||
additionalNodes.push({
|
||||
tag: 'meta',
|
||||
attrs: {
|
||||
polltype: 'creation'
|
||||
},
|
||||
}
|
||||
} as BinaryNode)
|
||||
}
|
||||
|
||||
if('cachedGroupMetadata' in options) {
|
||||
console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.')
|
||||
if ('cachedGroupMetadata' in options) {
|
||||
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 })
|
||||
if(config.emitOwnEvents) {
|
||||
await relayMessage(jid, fullMsg.message!, {
|
||||
messageId: fullMsg.key.id!,
|
||||
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
||||
additionalAttributes,
|
||||
statusJidList: options.statusJidList,
|
||||
additionalNodes
|
||||
})
|
||||
if (config.emitOwnEvents) {
|
||||
process.nextTick(() => {
|
||||
processingMutex.mutex(() => (
|
||||
upsertMessage(fullMsg, 'append')
|
||||
))
|
||||
processingMutex.mutex(() => upsertMessage(fullMsg, 'append'))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
getPlatformId,
|
||||
makeEventBuffer,
|
||||
makeNoiseHandler,
|
||||
promiseTimeout,
|
||||
promiseTimeout
|
||||
} from '../Utils'
|
||||
import {
|
||||
assertNodeErrorFree,
|
||||
@@ -61,21 +61,22 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
defaultQueryTimeoutMs,
|
||||
transactionOpts,
|
||||
qrTimeout,
|
||||
makeSignalRepository,
|
||||
makeSignalRepository
|
||||
} = config
|
||||
|
||||
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.')
|
||||
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.'
|
||||
)
|
||||
}
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
if(url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
||||
if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
||||
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
|
||||
}
|
||||
|
||||
@@ -110,28 +111,25 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
|
||||
const sendPromise = promisify(ws.send)
|
||||
/** send a raw buffer */
|
||||
const sendRawMessage = async(data: Uint8Array | Buffer) => {
|
||||
if(!ws.isOpen) {
|
||||
const sendRawMessage = async (data: Uint8Array | Buffer) => {
|
||||
if (!ws.isOpen) {
|
||||
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
||||
}
|
||||
|
||||
const bytes = noise.encodeFrame(data)
|
||||
await promiseTimeout<void>(
|
||||
connectTimeoutMs,
|
||||
async(resolve, reject) => {
|
||||
await promiseTimeout<void>(connectTimeoutMs, async (resolve, reject) => {
|
||||
try {
|
||||
await sendPromise.call(ws, bytes)
|
||||
resolve()
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** send a binary node */
|
||||
const sendNode = (frame: BinaryNode) => {
|
||||
if(logger.level === 'trace') {
|
||||
if (logger.level === 'trace') {
|
||||
logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
|
||||
}
|
||||
|
||||
@@ -141,15 +139,12 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
|
||||
/** log & process any unexpected errors */
|
||||
const onUnexpectedError = (err: Error | Boom, msg: string) => {
|
||||
logger.error(
|
||||
{ err },
|
||||
`unexpected error in '${msg}'`
|
||||
)
|
||||
logger.error({ err }, `unexpected error in '${msg}'`)
|
||||
}
|
||||
|
||||
/** await the next incoming message */
|
||||
const awaitNextMessage = async<T>(sendMsg?: Uint8Array) => {
|
||||
if(!ws.isOpen) {
|
||||
const awaitNextMessage = async <T>(sendMsg?: Uint8Array) => {
|
||||
if (!ws.isOpen) {
|
||||
throw new Boom('Connection Closed', {
|
||||
statusCode: DisconnectReason.connectionClosed
|
||||
})
|
||||
@@ -164,14 +159,13 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ws.on('frame', onOpen)
|
||||
ws.on('close', onClose)
|
||||
ws.on('error', onClose)
|
||||
})
|
||||
.finally(() => {
|
||||
}).finally(() => {
|
||||
ws.off('frame', onOpen)
|
||||
ws.off('close', onClose)
|
||||
ws.off('error', onClose)
|
||||
})
|
||||
|
||||
if(sendMsg) {
|
||||
if (sendMsg) {
|
||||
sendRawMessage(sendMsg).catch(onClose!)
|
||||
}
|
||||
|
||||
@@ -183,12 +177,11 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
* @param msgId the message tag to await
|
||||
* @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 onErr: (err) => void
|
||||
try {
|
||||
const result = await promiseTimeout<T>(timeoutMs,
|
||||
(resolve, reject) => {
|
||||
const result = await promiseTimeout<T>(timeoutMs, (resolve, reject) => {
|
||||
onRecv = resolve
|
||||
onErr = err => {
|
||||
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('close', onErr) // if the socket closes, you'll never receive the message
|
||||
ws.off('error', onErr)
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
return result as any
|
||||
} 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 */
|
||||
const query = async(node: BinaryNode, timeoutMs?: number) => {
|
||||
if(!node.attrs.id) {
|
||||
const query = async (node: BinaryNode, timeoutMs?: number) => {
|
||||
if (!node.attrs.id) {
|
||||
node.attrs.id = generateMessageTag()
|
||||
}
|
||||
|
||||
const msgId = node.attrs.id
|
||||
|
||||
const [result] = await Promise.all([
|
||||
waitForMessage(msgId, timeoutMs),
|
||||
sendNode(node)
|
||||
])
|
||||
const [result] = await Promise.all([waitForMessage(msgId, timeoutMs), sendNode(node)])
|
||||
|
||||
if('tag' in result) {
|
||||
if ('tag' in result) {
|
||||
assertNodeErrorFree(result)
|
||||
}
|
||||
|
||||
@@ -229,7 +218,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
/** connection handshake */
|
||||
const validateConnection = async() => {
|
||||
const validateConnection = async () => {
|
||||
let helloMsg: proto.IHandshakeMessage = {
|
||||
clientHello: { ephemeral: ephemeralKeyPair.public }
|
||||
}
|
||||
@@ -247,7 +236,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey)
|
||||
|
||||
let node: proto.IClientPayload
|
||||
if(!creds.me) {
|
||||
if (!creds.me) {
|
||||
node = generateRegistrationNode(creds, config)
|
||||
logger.info({ node }, 'not logged in, attempting registration...')
|
||||
} else {
|
||||
@@ -255,22 +244,20 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
logger.info({ node }, 'logging in...')
|
||||
}
|
||||
|
||||
const payloadEnc = noise.encrypt(
|
||||
proto.ClientPayload.encode(node).finish()
|
||||
)
|
||||
const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish())
|
||||
await sendRawMessage(
|
||||
proto.HandshakeMessage.encode({
|
||||
clientFinish: {
|
||||
static: keyEnc,
|
||||
payload: payloadEnc,
|
||||
},
|
||||
payload: payloadEnc
|
||||
}
|
||||
}).finish()
|
||||
)
|
||||
noise.finishInit()
|
||||
startKeepAliveRequest()
|
||||
}
|
||||
|
||||
const getAvailablePreKeysOnServer = async() => {
|
||||
const getAvailablePreKeysOnServer = async () => {
|
||||
const result = await query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
@@ -279,18 +266,15 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
type: 'get',
|
||||
to: S_WHATSAPP_NET
|
||||
},
|
||||
content: [
|
||||
{ tag: 'count', attrs: {} }
|
||||
]
|
||||
content: [{ tag: 'count', attrs: {} }]
|
||||
})
|
||||
const countChild = getBinaryNodeChild(result, 'count')
|
||||
return +countChild!.attrs.value
|
||||
}
|
||||
|
||||
/** generates and uploads a set of pre-keys to the server */
|
||||
const uploadPreKeys = async(count = INITIAL_PREKEY_COUNT) => {
|
||||
await keys.transaction(
|
||||
async() => {
|
||||
const uploadPreKeys = async (count = INITIAL_PREKEY_COUNT) => {
|
||||
await keys.transaction(async () => {
|
||||
logger.info({ count }, 'uploading pre-keys')
|
||||
const { update, node } = await getNextPreKeysNode({ creds, keys }, count)
|
||||
|
||||
@@ -298,14 +282,13 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ev.emit('creds.update', update)
|
||||
|
||||
logger.info({ count }, 'uploaded pre-keys')
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const uploadPreKeysToServerIfRequired = async() => {
|
||||
const uploadPreKeysToServerIfRequired = async () => {
|
||||
const preKeyCount = await getAvailablePreKeysOnServer()
|
||||
logger.info(`${preKeyCount} pre-keys found on server`)
|
||||
if(preKeyCount <= MIN_PREKEY_COUNT) {
|
||||
if (preKeyCount <= MIN_PREKEY_COUNT) {
|
||||
await uploadPreKeys()
|
||||
}
|
||||
}
|
||||
@@ -319,10 +302,10 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
|
||||
anyTriggered = ws.emit('frame', frame)
|
||||
// if it's a binary node
|
||||
if(!(frame instanceof Uint8Array)) {
|
||||
if (!(frame instanceof Uint8Array)) {
|
||||
const msgId = frame.attrs.id
|
||||
|
||||
if(logger.level === 'trace') {
|
||||
if (logger.level === 'trace') {
|
||||
logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
|
||||
}
|
||||
|
||||
@@ -333,7 +316,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
const l1 = frame.attrs || {}
|
||||
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]}`, 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}`, frame) || anyTriggered
|
||||
|
||||
if(!anyTriggered && logger.level === 'debug') {
|
||||
if (!anyTriggered && logger.level === 'debug') {
|
||||
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
||||
}
|
||||
}
|
||||
@@ -350,16 +333,13 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
}
|
||||
|
||||
const end = (error: Error | undefined) => {
|
||||
if(closed) {
|
||||
if (closed) {
|
||||
logger.trace({ trace: error?.stack }, 'connection already closed')
|
||||
return
|
||||
}
|
||||
|
||||
closed = true
|
||||
logger.info(
|
||||
{ trace: error?.stack },
|
||||
error ? 'connection errored' : 'connection closed'
|
||||
)
|
||||
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
|
||||
|
||||
clearInterval(keepAliveReq)
|
||||
clearTimeout(qrTimer)
|
||||
@@ -369,10 +349,10 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ws.removeAllListeners('open')
|
||||
ws.removeAllListeners('message')
|
||||
|
||||
if(!ws.isClosed && !ws.isClosing) {
|
||||
if (!ws.isClosed && !ws.isClosing) {
|
||||
try {
|
||||
ws.close()
|
||||
} catch{ }
|
||||
} catch {}
|
||||
}
|
||||
|
||||
ev.emit('connection.update', {
|
||||
@@ -385,12 +365,12 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ev.removeAllListeners('connection.update')
|
||||
}
|
||||
|
||||
const waitForSocketOpen = async() => {
|
||||
if(ws.isOpen) {
|
||||
const waitForSocketOpen = async () => {
|
||||
if (ws.isOpen) {
|
||||
return
|
||||
}
|
||||
|
||||
if(ws.isClosed || ws.isClosing) {
|
||||
if (ws.isClosed || ws.isClosing) {
|
||||
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
||||
}
|
||||
|
||||
@@ -402,17 +382,16 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ws.on('open', onOpen)
|
||||
ws.on('close', onClose)
|
||||
ws.on('error', onClose)
|
||||
})
|
||||
.finally(() => {
|
||||
}).finally(() => {
|
||||
ws.off('open', onOpen)
|
||||
ws.off('close', onClose)
|
||||
ws.off('error', onClose)
|
||||
})
|
||||
}
|
||||
|
||||
const startKeepAliveRequest = () => (
|
||||
keepAliveReq = setInterval(() => {
|
||||
if(!lastDateRecv) {
|
||||
const startKeepAliveRequest = () =>
|
||||
(keepAliveReq = setInterval(() => {
|
||||
if (!lastDateRecv) {
|
||||
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
|
||||
it could be that the network is down
|
||||
*/
|
||||
if(diff > keepAliveIntervalMs + 5000) {
|
||||
if (diff > keepAliveIntervalMs + 5000) {
|
||||
end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
|
||||
} else if(ws.isOpen) {
|
||||
} else if (ws.isOpen) {
|
||||
// if its all good, send a keep alive request
|
||||
query(
|
||||
{
|
||||
query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
id: generateMessageTag(),
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'get',
|
||||
xmlns: 'w:p',
|
||||
xmlns: 'w:p'
|
||||
},
|
||||
content: [{ tag: 'ping', attrs: {} }]
|
||||
}
|
||||
)
|
||||
.catch(err => {
|
||||
}).catch(err => {
|
||||
logger.error({ trace: err.stack }, 'error in sending keep alive')
|
||||
})
|
||||
} else {
|
||||
logger.warn('keep alive called when WS not open')
|
||||
}
|
||||
}, keepAliveIntervalMs)
|
||||
)
|
||||
}, keepAliveIntervalMs))
|
||||
/** i have no idea why this exists. pls enlighten me */
|
||||
const sendPassiveIq = (tag: 'passive' | 'active') => (
|
||||
const sendPassiveIq = (tag: 'passive' | 'active') =>
|
||||
query({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
to: S_WHATSAPP_NET,
|
||||
xmlns: 'passive',
|
||||
type: 'set',
|
||||
type: 'set'
|
||||
},
|
||||
content: [
|
||||
{ tag, attrs: {} }
|
||||
]
|
||||
content: [{ tag, attrs: {} }]
|
||||
})
|
||||
)
|
||||
|
||||
/** logout & invalidate connection */
|
||||
const logout = async(msg?: string) => {
|
||||
const logout = async (msg?: string) => {
|
||||
const jid = authState.creds.me?.id
|
||||
if(jid) {
|
||||
if (jid) {
|
||||
await sendNode({
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
@@ -487,7 +459,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
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.me = {
|
||||
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
||||
@@ -572,10 +544,10 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
|
||||
ws.on('message', onMessageReceived)
|
||||
|
||||
ws.on('open', async() => {
|
||||
ws.on('open', async () => {
|
||||
try {
|
||||
await validateConnection()
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'error in validating connection')
|
||||
end(err)
|
||||
}
|
||||
@@ -583,15 +555,17 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ws.on('error', mapWebSocketError(end))
|
||||
ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
|
||||
// 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
|
||||
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 = {
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'result',
|
||||
id: stanza.attrs.id,
|
||||
id: stanza.attrs.id
|
||||
}
|
||||
}
|
||||
await sendNode(iq)
|
||||
@@ -604,12 +578,12 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
|
||||
let qrMs = qrTimeout || 60_000 // time to let a QR live
|
||||
const genPairQR = () => {
|
||||
if(!ws.isOpen) {
|
||||
if (!ws.isOpen) {
|
||||
return
|
||||
}
|
||||
|
||||
const refNode = refNodes.shift()
|
||||
if(!refNode) {
|
||||
if (!refNode) {
|
||||
end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
|
||||
return
|
||||
}
|
||||
@@ -627,7 +601,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
})
|
||||
// device paired for the first time
|
||||
// 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')
|
||||
try {
|
||||
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
|
||||
@@ -641,13 +615,13 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ev.emit('connection.update', { isNewLogin: true, qr: undefined })
|
||||
|
||||
await sendNode(reply)
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
logger.info({ trace: error.stack }, 'error in pairing')
|
||||
end(error)
|
||||
}
|
||||
})
|
||||
// login complete
|
||||
ws.on('CB:success', async(node: BinaryNode) => {
|
||||
ws.on('CB:success', async (node: BinaryNode) => {
|
||||
await uploadPreKeysToServerIfRequired()
|
||||
await sendPassiveIq('active')
|
||||
|
||||
@@ -688,7 +662,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ws.on('CB:ib,,edge_routing', (node: BinaryNode) => {
|
||||
const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
|
||||
const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
|
||||
if(routingInfo?.content) {
|
||||
if (routingInfo?.content) {
|
||||
authState.creds.routingInfo = Buffer.from(routingInfo?.content as Uint8Array)
|
||||
ev.emit('creds.update', authState.creds)
|
||||
}
|
||||
@@ -696,7 +670,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
|
||||
let didStartBuffer = false
|
||||
process.nextTick(() => {
|
||||
if(creds.me?.id) {
|
||||
if (creds.me?.id) {
|
||||
// start buffering important events
|
||||
// if we're logged in
|
||||
ev.buffer()
|
||||
@@ -712,7 +686,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
const offlineNotifs = +(child?.attrs.count || 0)
|
||||
|
||||
logger.info(`handled ${offlineNotifs} offline messages/notifications`)
|
||||
if(didStartBuffer) {
|
||||
if (didStartBuffer) {
|
||||
ev.flush()
|
||||
logger.trace('flushed events for initial buffer')
|
||||
}
|
||||
@@ -724,13 +698,12 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
ev.on('creds.update', update => {
|
||||
const name = update.me?.name
|
||||
// if name has just been received
|
||||
if(creds.me?.name !== name) {
|
||||
if (creds.me?.name !== name) {
|
||||
logger.debug({ name }, 'updated pushName')
|
||||
sendNode({
|
||||
tag: 'presence',
|
||||
attrs: { name: name! }
|
||||
})
|
||||
.catch(err => {
|
||||
}).catch(err => {
|
||||
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)
|
||||
})
|
||||
|
||||
|
||||
return {
|
||||
type: 'md' as 'md',
|
||||
ws,
|
||||
@@ -762,7 +734,7 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
requestPairingCode,
|
||||
/** Waits for the connection to WA to reach a state */
|
||||
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
||||
sendWAMBuffer,
|
||||
sendWAMBuffer
|
||||
}
|
||||
}
|
||||
|
||||
@@ -772,11 +744,6 @@ export const makeSocket = (config: SocketConfig) => {
|
||||
* */
|
||||
function mapWebSocketError(handler: (err: Error) => void) {
|
||||
return (error: Error) => {
|
||||
handler(
|
||||
new Boom(
|
||||
`WebSocket Error (${error?.message})`,
|
||||
{ statusCode: getCodeFromWSError(error), data: error }
|
||||
)
|
||||
)
|
||||
handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,10 @@ import { makeSocket } from './socket'
|
||||
export const makeUSyncSocket = (config: SocketConfig) => {
|
||||
const sock = makeSocket(config)
|
||||
|
||||
const {
|
||||
generateMessageTag,
|
||||
query,
|
||||
} = sock
|
||||
const { generateMessageTag, query } = sock
|
||||
|
||||
const executeUSyncQuery = async(usyncQuery: USyncQuery) => {
|
||||
if(usyncQuery.protocols.length === 0) {
|
||||
const executeUSyncQuery = async (usyncQuery: USyncQuery) => {
|
||||
if (usyncQuery.protocols.length === 0) {
|
||||
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
|
||||
const validUsers = usyncQuery.users
|
||||
|
||||
const userNodes = validUsers.map((user) => {
|
||||
const userNodes = validUsers.map(user => {
|
||||
return {
|
||||
tag: 'user',
|
||||
attrs: {
|
||||
jid: !user.phone ? user.id : undefined,
|
||||
jid: !user.phone ? user.id : undefined
|
||||
},
|
||||
content: usyncQuery.protocols
|
||||
.map((a) => a.getUserElement(user))
|
||||
.filter(a => a !== null)
|
||||
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
||||
} as BinaryNode
|
||||
})
|
||||
|
||||
@@ -42,14 +37,14 @@ export const makeUSyncSocket = (config: SocketConfig) => {
|
||||
const queryNode: BinaryNode = {
|
||||
tag: 'query',
|
||||
attrs: {},
|
||||
content: usyncQuery.protocols.map((a) => a.getQueryElement())
|
||||
content: usyncQuery.protocols.map(a => a.getQueryElement())
|
||||
}
|
||||
const iq = {
|
||||
tag: 'iq',
|
||||
attrs: {
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'get',
|
||||
xmlns: 'usync',
|
||||
xmlns: 'usync'
|
||||
},
|
||||
content: [
|
||||
{
|
||||
@@ -59,14 +54,11 @@ export const makeUSyncSocket = (config: SocketConfig) => {
|
||||
mode: usyncQuery.mode,
|
||||
sid: generateMessageTag(),
|
||||
last: 'true',
|
||||
index: '0',
|
||||
index: '0'
|
||||
},
|
||||
content: [
|
||||
queryNode,
|
||||
listNode
|
||||
]
|
||||
content: [queryNode, listNode]
|
||||
}
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
const result = await query(iq)
|
||||
@@ -76,6 +68,6 @@ export const makeUSyncSocket = (config: SocketConfig) => {
|
||||
|
||||
return {
|
||||
...sock,
|
||||
executeUSyncQuery,
|
||||
executeUSyncQuery
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { processSyncAction } from '../Utils/chat-utils'
|
||||
import logger from '../Utils/logger'
|
||||
|
||||
describe('App State Sync Tests', () => {
|
||||
|
||||
const me: Contact = { id: randomJid() }
|
||||
// case when initial sync is off
|
||||
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)
|
||||
expect(events['chats.update']).toHaveLength(1)
|
||||
const event = events['chats.update']?.[0]
|
||||
@@ -129,7 +128,7 @@ describe('App State Sync Tests', () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
]
|
||||
]
|
||||
|
||||
const ctx: InitialAppStateSyncOptions = {
|
||||
@@ -139,7 +138,7 @@ describe('App State Sync Tests', () => {
|
||||
accountSettings: { unarchiveChats: true }
|
||||
}
|
||||
|
||||
for(const mutations of CASES) {
|
||||
for (const mutations of CASES) {
|
||||
const events = processSyncActions(mutations, me, ctx, logger)
|
||||
expect(events['chats.update']?.length).toBeFalsy()
|
||||
}
|
||||
@@ -152,7 +151,7 @@ describe('App State Sync Tests', () => {
|
||||
const index = ['archive', jid]
|
||||
const now = unixTimestampSeconds()
|
||||
|
||||
const CASES: { settings: AccountSettings, mutations: ChatMutation[] }[] = [
|
||||
const CASES: { settings: AccountSettings; mutations: ChatMutation[] }[] = [
|
||||
{
|
||||
settings: { unarchiveChats: true },
|
||||
mutations: [
|
||||
@@ -169,7 +168,7 @@ describe('App State Sync Tests', () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
]
|
||||
},
|
||||
{
|
||||
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 = {
|
||||
recvChats: {
|
||||
[jid]: { lastMsgRecvTimestamp: now }
|
||||
|
||||
@@ -5,15 +5,14 @@ import logger from '../Utils/logger'
|
||||
import { randomJid } from './utils'
|
||||
|
||||
describe('Event Buffer Tests', () => {
|
||||
|
||||
let ev: ReturnType<typeof makeEventBuffer>
|
||||
beforeEach(() => {
|
||||
const _logger = logger.child({ })
|
||||
const _logger = logger.child({})
|
||||
_logger.level = 'trace'
|
||||
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 chats: Chat[] = []
|
||||
@@ -23,14 +22,14 @@ describe('Event Buffer Tests', () => {
|
||||
|
||||
ev.buffer()
|
||||
await Promise.all([
|
||||
(async() => {
|
||||
(async () => {
|
||||
ev.buffer()
|
||||
await delay(100)
|
||||
ev.emit('chats.upsert', [{ id: chatId, conversationTimestamp: 123, unreadCount: 1 }])
|
||||
const flushed = ev.flush()
|
||||
expect(flushed).toBeFalsy()
|
||||
})(),
|
||||
(async() => {
|
||||
(async () => {
|
||||
ev.buffer()
|
||||
await delay(200)
|
||||
ev.emit('chats.update', [{ id: chatId, conversationTimestamp: 124, unreadCount: 1 }])
|
||||
@@ -47,7 +46,7 @@ describe('Event Buffer Tests', () => {
|
||||
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 chats: Partial<Chat>[] = []
|
||||
|
||||
@@ -65,7 +64,7 @@ describe('Event Buffer Tests', () => {
|
||||
expect(chats).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should overwrite a chats.update event', async() => {
|
||||
it('should overwrite a chats.update event', async () => {
|
||||
const chatId = randomJid()
|
||||
const chatsDeleted: string[] = []
|
||||
|
||||
@@ -82,7 +81,7 @@ describe('Event Buffer Tests', () => {
|
||||
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 chatId2 = randomJid()
|
||||
const chatsUpserted: Chat[] = []
|
||||
@@ -93,41 +92,49 @@ describe('Event Buffer Tests', () => {
|
||||
ev.on('chats.update', () => fail('not should have emitted'))
|
||||
|
||||
ev.buffer()
|
||||
ev.emit('chats.update', [{
|
||||
ev.emit('chats.update', [
|
||||
{
|
||||
id: chatId,
|
||||
archived: true,
|
||||
conditional(buff) {
|
||||
if(buff.chatUpserts[chatId]) {
|
||||
if (buff.chatUpserts[chatId]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}])
|
||||
ev.emit('chats.update', [{
|
||||
}
|
||||
])
|
||||
ev.emit('chats.update', [
|
||||
{
|
||||
id: chatId2,
|
||||
archived: true,
|
||||
conditional(buff) {
|
||||
if(buff.historySets.chats[chatId2]) {
|
||||
if (buff.historySets.chats[chatId2]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}])
|
||||
}
|
||||
])
|
||||
|
||||
ev.flush()
|
||||
|
||||
ev.buffer()
|
||||
ev.emit('chats.upsert', [{
|
||||
ev.emit('chats.upsert', [
|
||||
{
|
||||
id: chatId,
|
||||
conversationTimestamp: 123,
|
||||
unreadCount: 1,
|
||||
muteEndTime: 123
|
||||
}])
|
||||
}
|
||||
])
|
||||
ev.emit('messaging-history.set', {
|
||||
chats: [{
|
||||
chats: [
|
||||
{
|
||||
id: chatId2,
|
||||
conversationTimestamp: 123,
|
||||
unreadCount: 1,
|
||||
muteEndTime: 123
|
||||
}],
|
||||
}
|
||||
],
|
||||
contacts: [],
|
||||
messages: [],
|
||||
isLatest: false
|
||||
@@ -144,7 +151,7 @@ describe('Event Buffer Tests', () => {
|
||||
expect(chatsSynced[0].archived).toEqual(true)
|
||||
})
|
||||
|
||||
it('should discard a conditional update', async() => {
|
||||
it('should discard a conditional update', async () => {
|
||||
const chatId = randomJid()
|
||||
const chatsUpserted: Chat[] = []
|
||||
|
||||
@@ -152,21 +159,25 @@ describe('Event Buffer Tests', () => {
|
||||
ev.on('chats.update', () => fail('not should have emitted'))
|
||||
|
||||
ev.buffer()
|
||||
ev.emit('chats.update', [{
|
||||
ev.emit('chats.update', [
|
||||
{
|
||||
id: chatId,
|
||||
archived: true,
|
||||
conditional(buff) {
|
||||
if(buff.chatUpserts[chatId]) {
|
||||
if (buff.chatUpserts[chatId]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}])
|
||||
ev.emit('chats.upsert', [{
|
||||
}
|
||||
])
|
||||
ev.emit('chats.upsert', [
|
||||
{
|
||||
id: chatId,
|
||||
conversationTimestamp: 123,
|
||||
unreadCount: 1,
|
||||
muteEndTime: 123
|
||||
}])
|
||||
}
|
||||
])
|
||||
|
||||
ev.flush()
|
||||
|
||||
@@ -174,7 +185,7 @@ describe('Event Buffer Tests', () => {
|
||||
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()
|
||||
let chatRecv: Chat | undefined
|
||||
|
||||
@@ -199,7 +210,7 @@ describe('Event Buffer Tests', () => {
|
||||
expect(chatRecv?.archived).toBeTruthy()
|
||||
})
|
||||
|
||||
it('should buffer message upsert events', async() => {
|
||||
it('should buffer message upsert events', async () => {
|
||||
const messageTimestamp = unixTimestampSeconds()
|
||||
const msg: proto.IWebMessageInfo = {
|
||||
key: {
|
||||
@@ -235,7 +246,7 @@ describe('Event Buffer Tests', () => {
|
||||
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 = {
|
||||
key: {
|
||||
remoteJid: randomJid(),
|
||||
@@ -269,7 +280,7 @@ describe('Event Buffer Tests', () => {
|
||||
expect(msgs[0].userReceipt).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should buffer multiple status updates', async() => {
|
||||
it('should buffer multiple status updates', async () => {
|
||||
const key: WAMessageKey = {
|
||||
remoteJid: randomJid(),
|
||||
id: generateMessageID(),
|
||||
@@ -290,7 +301,7 @@ describe('Event Buffer Tests', () => {
|
||||
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 = {
|
||||
key: {
|
||||
remoteJid: '12345@s.whatsapp.net',
|
||||
|
||||
@@ -5,24 +5,18 @@ import { makeMockSignalKeyStore } from './utils'
|
||||
logger.level = 'trace'
|
||||
|
||||
describe('Key Store w Transaction Tests', () => {
|
||||
|
||||
const rawStore = makeMockSignalKeyStore()
|
||||
const store = addTransactionCapability(
|
||||
rawStore,
|
||||
logger,
|
||||
{
|
||||
const store = addTransactionCapability(rawStore, logger, {
|
||||
maxCommitRetries: 1,
|
||||
delayBetweenTriesMs: 10
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('should use transaction cache when mutated', async() => {
|
||||
it('should use transaction cache when mutated', async () => {
|
||||
const key = '123'
|
||||
const value = new Uint8Array(1)
|
||||
const ogGet = rawStore.get
|
||||
await store.transaction(
|
||||
async() => {
|
||||
await store.set({ 'session': { [key]: value } })
|
||||
await store.transaction(async () => {
|
||||
await store.set({ session: { [key]: value } })
|
||||
|
||||
rawStore.get = () => {
|
||||
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])
|
||||
expect(stored).toEqual(new Uint8Array(1))
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
rawStore.get = ogGet
|
||||
})
|
||||
|
||||
it('should not commit a failed transaction', async() => {
|
||||
it('should not commit a failed transaction', async () => {
|
||||
const key = 'abcd'
|
||||
await expect(
|
||||
store.transaction(
|
||||
async() => {
|
||||
await store.set({ 'session': { [key]: new Uint8Array(1) } })
|
||||
store.transaction(async () => {
|
||||
await store.set({ session: { [key]: new Uint8Array(1) } })
|
||||
throw new Error('fail')
|
||||
}
|
||||
)
|
||||
).rejects.toThrowError(
|
||||
'fail'
|
||||
)
|
||||
})
|
||||
).rejects.toThrowError('fail')
|
||||
|
||||
const { [key]: stored } = await store.get('session', [key])
|
||||
expect(stored).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should handle overlapping transactions', async() => {
|
||||
it('should handle overlapping transactions', async () => {
|
||||
// promise to let transaction 2
|
||||
// know that transaction 1 has started
|
||||
let promiseResolve: () => void
|
||||
@@ -61,10 +50,9 @@ describe('Key Store w Transaction Tests', () => {
|
||||
promiseResolve = resolve
|
||||
})
|
||||
|
||||
store.transaction(
|
||||
async() => {
|
||||
store.transaction(async () => {
|
||||
await store.set({
|
||||
'session': {
|
||||
session: {
|
||||
'1': new Uint8Array(1)
|
||||
}
|
||||
})
|
||||
@@ -72,17 +60,14 @@ describe('Key Store w Transaction Tests', () => {
|
||||
await delay(5)
|
||||
// reolve the promise to let the other transaction continue
|
||||
promiseResolve()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
await store.transaction(
|
||||
async() => {
|
||||
await store.transaction(async () => {
|
||||
await promise
|
||||
await delay(5)
|
||||
|
||||
expect(store.isInTransaction()).toBe(true)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
expect(store.isInTransaction()).toBe(false)
|
||||
// ensure that the transaction were committed
|
||||
|
||||
@@ -3,8 +3,7 @@ import { SignalAuthState, SignalDataTypeMap } from '../Types'
|
||||
import { Curve, generateRegistrationId, generateSignalPubKey, signedKeyPair } from '../Utils'
|
||||
|
||||
describe('Signal Tests', () => {
|
||||
|
||||
it('should correctly encrypt/decrypt 1 message', async() => {
|
||||
it('should correctly encrypt/decrypt 1 message', async () => {
|
||||
const user1 = makeUser()
|
||||
const user2 = makeUser()
|
||||
|
||||
@@ -12,39 +11,31 @@ describe('Signal Tests', () => {
|
||||
|
||||
await prepareForSendingMessage(user1, user2)
|
||||
|
||||
const result = await user1.repository.encryptMessage(
|
||||
{ jid: user2.jid, data: msg }
|
||||
)
|
||||
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
|
||||
|
||||
const dec = await user2.repository.decryptMessage(
|
||||
{ jid: user1.jid, ...result }
|
||||
)
|
||||
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
|
||||
|
||||
expect(dec).toEqual(msg)
|
||||
})
|
||||
|
||||
it('should correctly override a session', async() => {
|
||||
it('should correctly override a session', async () => {
|
||||
const user1 = makeUser()
|
||||
const user2 = makeUser()
|
||||
|
||||
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)
|
||||
|
||||
const result = await user1.repository.encryptMessage(
|
||||
{ jid: user2.jid, data: msg }
|
||||
)
|
||||
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
|
||||
|
||||
const dec = await user2.repository.decryptMessage(
|
||||
{ jid: user1.jid, ...result }
|
||||
)
|
||||
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
|
||||
|
||||
expect(dec).toEqual(msg)
|
||||
}
|
||||
})
|
||||
|
||||
it('should correctly encrypt/decrypt multiple messages', async() => {
|
||||
it('should correctly encrypt/decrypt multiple messages', async () => {
|
||||
const user1 = makeUser()
|
||||
const user2 = makeUser()
|
||||
|
||||
@@ -52,56 +43,46 @@ describe('Signal Tests', () => {
|
||||
|
||||
await prepareForSendingMessage(user1, user2)
|
||||
|
||||
for(let i = 0;i < 10;i++) {
|
||||
const result = await user1.repository.encryptMessage(
|
||||
{ jid: user2.jid, data: msg }
|
||||
)
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
|
||||
|
||||
const dec = await user2.repository.decryptMessage(
|
||||
{ jid: user1.jid, ...result }
|
||||
)
|
||||
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
|
||||
|
||||
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 participants = [...Array(5)].map(makeUser)
|
||||
|
||||
const msg = Buffer.from('hello there!')
|
||||
|
||||
const sender = participants[0]
|
||||
const enc = await sender.repository.encryptGroupMessage(
|
||||
{
|
||||
const enc = await sender.repository.encryptGroupMessage({
|
||||
group: groupId,
|
||||
meId: sender.jid,
|
||||
data: msg
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
for(const participant of participants) {
|
||||
if(participant === sender) {
|
||||
for (const participant of participants) {
|
||||
if (participant === sender) {
|
||||
continue
|
||||
}
|
||||
|
||||
await participant.repository.processSenderKeyDistributionMessage(
|
||||
{
|
||||
await participant.repository.processSenderKeyDistributionMessage({
|
||||
item: {
|
||||
groupId,
|
||||
axolotlSenderKeyDistributionMessage: enc.senderKeyDistributionMessage
|
||||
},
|
||||
authorJid: sender.jid
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
const dec = await participant.repository.decryptGroupMessage(
|
||||
{
|
||||
const dec = await participant.repository.decryptGroupMessage({
|
||||
group: groupId,
|
||||
authorJid: sender.jid,
|
||||
msg: enc.ciphertext
|
||||
}
|
||||
)
|
||||
})
|
||||
expect(dec).toEqual(msg)
|
||||
}
|
||||
})
|
||||
@@ -116,14 +97,9 @@ function makeUser() {
|
||||
return { store, jid, repository }
|
||||
}
|
||||
|
||||
async function prepareForSendingMessage(
|
||||
sender: User,
|
||||
receiver: User,
|
||||
preKeyId = 2
|
||||
) {
|
||||
async function prepareForSendingMessage(sender: User, receiver: User, preKeyId = 2) {
|
||||
const preKey = Curve.generateKeyPair()
|
||||
await sender.repository.injectE2ESession(
|
||||
{
|
||||
await sender.repository.injectE2ESession({
|
||||
jid: receiver.jid,
|
||||
session: {
|
||||
registrationId: receiver.store.creds.registrationId,
|
||||
@@ -131,15 +107,14 @@ async function prepareForSendingMessage(
|
||||
signedPreKey: {
|
||||
keyId: receiver.store.creds.signedPreKey.keyId,
|
||||
publicKey: generateSignalPubKey(receiver.store.creds.signedPreKey.keyPair.public),
|
||||
signature: receiver.store.creds.signedPreKey.signature,
|
||||
signature: receiver.store.creds.signedPreKey.signature
|
||||
},
|
||||
preKey: {
|
||||
keyId: preKeyId,
|
||||
publicKey: generateSignalPubKey(preKey.public),
|
||||
publicKey: generateSignalPubKey(preKey.public)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
await receiver.store.keys.set({
|
||||
'pre-key': {
|
||||
@@ -156,14 +131,14 @@ function makeTestAuthState(): SignalAuthState {
|
||||
creds: {
|
||||
signedIdentityKey: identityKey,
|
||||
registrationId: generateRegistrationId(),
|
||||
signedPreKey: signedKeyPair(identityKey, 1),
|
||||
signedPreKey: signedKeyPair(identityKey, 1)
|
||||
},
|
||||
keys: {
|
||||
get(type, ids) {
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
||||
for(const id of ids) {
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||
for (const id of ids) {
|
||||
const item = store[getUniqueId(type, id)]
|
||||
if(typeof item !== 'undefined') {
|
||||
if (typeof item !== 'undefined') {
|
||||
data[id] = item
|
||||
}
|
||||
}
|
||||
@@ -171,12 +146,12 @@ function makeTestAuthState(): SignalAuthState {
|
||||
return data
|
||||
},
|
||||
set(data) {
|
||||
for(const type in data) {
|
||||
for(const id in data[type]) {
|
||||
for (const type in data) {
|
||||
for (const id in data[type]) {
|
||||
store[getUniqueId(type, id)] = data[type][id]
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,38 +31,37 @@ const TEST_VECTORS: TestVector[] = [
|
||||
)
|
||||
),
|
||||
plaintext: readFileSync('./Media/icon.png')
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
describe('Media Download Tests', () => {
|
||||
|
||||
it('should download a full encrypted media correctly', async() => {
|
||||
for(const { type, message, plaintext } of TEST_VECTORS) {
|
||||
it('should download a full encrypted media correctly', async () => {
|
||||
for (const { type, message, plaintext } of TEST_VECTORS) {
|
||||
const readPipe = await downloadContentFromMessage(message, type)
|
||||
|
||||
let buffer = Buffer.alloc(0)
|
||||
for await (const read of readPipe) {
|
||||
buffer = Buffer.concat([ buffer, read ])
|
||||
buffer = Buffer.concat([buffer, read])
|
||||
}
|
||||
|
||||
expect(buffer).toEqual(plaintext)
|
||||
}
|
||||
})
|
||||
|
||||
it('should download an encrypted media correctly piece', async() => {
|
||||
for(const { type, message, plaintext } of TEST_VECTORS) {
|
||||
it('should download an encrypted media correctly piece', async () => {
|
||||
for (const { type, message, plaintext } of TEST_VECTORS) {
|
||||
// check all edge cases
|
||||
const ranges = [
|
||||
{ startByte: 51, endByte: plaintext.length - 100 }, // random numbers
|
||||
{ startByte: 1024, endByte: 2038 }, // larger random multiples of 16
|
||||
{ startByte: 1, endByte: plaintext.length - 1 } // borders
|
||||
]
|
||||
for(const range of ranges) {
|
||||
for (const range of ranges) {
|
||||
const readPipe = await downloadContentFromMessage(message, type, range)
|
||||
|
||||
let buffer = Buffer.alloc(0)
|
||||
for await (const read of readPipe) {
|
||||
buffer = Buffer.concat([ buffer, read ])
|
||||
buffer = Buffer.concat([buffer, read])
|
||||
}
|
||||
|
||||
const hex = buffer.toString('hex')
|
||||
|
||||
@@ -2,9 +2,8 @@ import { WAMessageContent } from '../Types'
|
||||
import { normalizeMessageContent } from '../Utils'
|
||||
|
||||
describe('Messages Tests', () => {
|
||||
|
||||
it('should correctly unwrap messages', () => {
|
||||
const CONTENT = { imageMessage: { } }
|
||||
const CONTENT = { imageMessage: {} }
|
||||
expectRightContent(CONTENT)
|
||||
expectRightContent({
|
||||
ephemeralMessage: { message: CONTENT }
|
||||
@@ -29,9 +28,7 @@ describe('Messages Tests', () => {
|
||||
})
|
||||
|
||||
function expectRightContent(content: WAMessageContent) {
|
||||
expect(
|
||||
normalizeMessageContent(content)
|
||||
).toHaveProperty('imageMessage')
|
||||
expect(normalizeMessageContent(content)).toHaveProperty('imageMessage')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -11,10 +11,10 @@ export function makeMockSignalKeyStore(): SignalKeyStore {
|
||||
|
||||
return {
|
||||
get(type, ids) {
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
||||
for(const id of ids) {
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||
for (const id of ids) {
|
||||
const item = store[getUniqueId(type, id)]
|
||||
if(typeof item !== 'undefined') {
|
||||
if (typeof item !== 'undefined') {
|
||||
data[id] = item
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,12 @@ export function makeMockSignalKeyStore(): SignalKeyStore {
|
||||
return data
|
||||
},
|
||||
set(data) {
|
||||
for(const type in data) {
|
||||
for(const id in data[type]) {
|
||||
for (const type in data) {
|
||||
for (const id in data[type]) {
|
||||
store[getUniqueId(type, id)] = data[type][id]
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function getUniqueId(type: string, id: string) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { proto } from '../../WAProto'
|
||||
import type { Contact } from './Contact'
|
||||
import type { MinimalMessage } from './Message'
|
||||
|
||||
export type KeyPair = { public: Uint8Array, private: Uint8Array }
|
||||
export type KeyPair = { public: Uint8Array; private: Uint8Array }
|
||||
export type SignedKeyPair = {
|
||||
keyPair: KeyPair
|
||||
signature: Uint8Array
|
||||
@@ -67,7 +67,7 @@ export type AuthenticationCreds = SignalCreds & {
|
||||
|
||||
export type SignalDataTypeMap = {
|
||||
'pre-key': KeyPair
|
||||
'session': Uint8Array
|
||||
session: Uint8Array
|
||||
'sender-key': Uint8Array
|
||||
'sender-key-memory': { [jid: string]: boolean }
|
||||
'app-state-sync-key': proto.Message.IAppStateSyncKeyData
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate'
|
||||
|
||||
export type WACallEvent = {
|
||||
|
||||
@@ -22,9 +22,15 @@ export type WAPrivacyMessagesValue = 'all' | 'contacts'
|
||||
/** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
|
||||
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 {
|
||||
lastKnownPresence: WAPresence
|
||||
@@ -54,7 +60,8 @@ export type Chat = proto.IConversation & {
|
||||
lastMessageRecvTimestamp?: number
|
||||
}
|
||||
|
||||
export type ChatUpdate = Partial<Chat & {
|
||||
export type ChatUpdate = Partial<
|
||||
Chat & {
|
||||
/**
|
||||
* if specified in 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
|
||||
* */
|
||||
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
|
||||
@@ -74,7 +82,7 @@ export type ChatUpdate = Partial<Chat & {
|
||||
export type LastMessageList = MinimalMessage[] | proto.SyncActionValue.ISyncActionMessageRange
|
||||
|
||||
export type ChatModification =
|
||||
{
|
||||
| {
|
||||
archive: boolean
|
||||
lastMessages: LastMessageList
|
||||
}
|
||||
@@ -86,12 +94,13 @@ export type ChatModification =
|
||||
}
|
||||
| {
|
||||
clear: boolean
|
||||
} | {
|
||||
deleteForMe: { deleteMedia: boolean, key: WAMessageKey, timestamp: number }
|
||||
}
|
||||
| {
|
||||
deleteForMe: { deleteMedia: boolean; key: WAMessageKey; timestamp: number }
|
||||
}
|
||||
| {
|
||||
star: {
|
||||
messages: { id: string, fromMe?: boolean }[]
|
||||
messages: { id: string; fromMe?: boolean }[]
|
||||
star: boolean
|
||||
}
|
||||
}
|
||||
@@ -99,7 +108,7 @@ export type ChatModification =
|
||||
markRead: boolean
|
||||
lastMessages: LastMessageList
|
||||
}
|
||||
| { delete: true, lastMessages: LastMessageList }
|
||||
| { delete: true; lastMessages: LastMessageList }
|
||||
// Label
|
||||
| { addLabel: LabelActionBody }
|
||||
// Label assosiation
|
||||
|
||||
@@ -29,42 +29,48 @@ export type BaileysEventMap = {
|
||||
'chats.upsert': Chat[]
|
||||
/** update the given chats */
|
||||
'chats.update': ChatUpdate[]
|
||||
'chats.phoneNumberShare': {lid: string, jid: string}
|
||||
'chats.phoneNumberShare': { lid: string; jid: string }
|
||||
/** delete chats with given ID */
|
||||
'chats.delete': string[]
|
||||
/** 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.update': Partial<Contact>[]
|
||||
|
||||
'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
|
||||
'messages.delete': { keys: WAMessageKey[] } | { jid: string; all: true }
|
||||
'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,
|
||||
* the update will have type: "notify"
|
||||
* 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 */
|
||||
'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]
|
||||
'messages.reaction': { key: WAMessageKey; reaction: proto.IReaction }[]
|
||||
|
||||
'message-receipt.update': MessageUserReceiptUpdate[]
|
||||
|
||||
'groups.upsert': GroupMetadata[]
|
||||
'groups.update': Partial<GroupMetadata>[]
|
||||
/** apply an action to participants in a group */
|
||||
'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-participants.update': { id: string; author: string; participants: string[]; action: ParticipantAction }
|
||||
'group.join-request': {
|
||||
id: string
|
||||
author: string
|
||||
participant: string
|
||||
action: RequestJoinAction
|
||||
method: RequestJoinMethod
|
||||
}
|
||||
|
||||
'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 */
|
||||
'call': WACallEvent[]
|
||||
call: WACallEvent[]
|
||||
'labels.edit': Label
|
||||
'labels.association': { association: LabelAssociation, type: 'add' | 'remove' }
|
||||
'labels.association': { association: LabelAssociation; type: 'add' | 'remove' }
|
||||
}
|
||||
|
||||
export type BufferedEventData = {
|
||||
@@ -83,11 +89,11 @@ export type BufferedEventData = {
|
||||
chatDeletes: Set<string>
|
||||
contactUpserts: { [jid: string]: Contact }
|
||||
contactUpdates: { [jid: string]: Partial<Contact> }
|
||||
messageUpserts: { [key: string]: { type: MessageUpsertType, message: WAMessage } }
|
||||
messageUpserts: { [key: string]: { type: MessageUpsertType; message: WAMessage } }
|
||||
messageUpdates: { [key: string]: WAMessageUpdate }
|
||||
messageDeletes: { [key: string]: WAMessageKey }
|
||||
messageReactions: { [key: string]: { key: WAMessageKey, reactions: proto.IReaction[] } }
|
||||
messageReceipts: { [key: string]: { key: WAMessageKey, userReceipt: proto.IUserReceipt[] } }
|
||||
messageReactions: { [key: string]: { key: WAMessageKey; reactions: proto.IReaction[] } }
|
||||
messageReceipts: { [key: string]: { key: WAMessageKey; userReceipt: proto.IUserReceipt[] } }
|
||||
groupUpdates: { [jid: string]: Partial<GroupMetadata> }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
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'
|
||||
|
||||
@@ -11,7 +15,7 @@ export type RequestJoinMethod = 'invite_link' | 'linked_group_join' | 'non_admin
|
||||
export interface GroupMetadata {
|
||||
id: string
|
||||
/** group uses 'lid' or 'pn' to send messages */
|
||||
addressingMode: "pn" | "lid"
|
||||
addressingMode: 'pn' | 'lid'
|
||||
owner: string | undefined
|
||||
subject: string
|
||||
/** group subject owner */
|
||||
@@ -46,7 +50,6 @@ export interface GroupMetadata {
|
||||
author?: string
|
||||
}
|
||||
|
||||
|
||||
export interface WAGroupCreateResponse {
|
||||
status: number
|
||||
gid?: string
|
||||
|
||||
@@ -44,5 +44,5 @@ export enum LabelColor {
|
||||
Color17,
|
||||
Color18,
|
||||
Color19,
|
||||
Color20,
|
||||
Color20
|
||||
}
|
||||
@@ -17,7 +17,12 @@ export type WAMessageKey = proto.IMessageKey
|
||||
export type WATextMessage = proto.Message.IExtendedTextMessage
|
||||
export type WAContextInfo = proto.IContextInfo
|
||||
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 WAMessageStatus = proto.WebMessageInfo.Status
|
||||
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 */
|
||||
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 = {
|
||||
auth: string
|
||||
ttl: number
|
||||
hosts: { hostname: string, maxContentLengthBytes: number }[]
|
||||
hosts: { hostname: string; maxContentLengthBytes: number }[]
|
||||
fetchDate: Date
|
||||
}
|
||||
|
||||
@@ -88,11 +101,13 @@ type RequestPhoneNumber = {
|
||||
|
||||
export type MediaType = keyof typeof MEDIA_HKDF_KEY_MAPPING
|
||||
export type AnyMediaMessageContent = (
|
||||
({
|
||||
| ({
|
||||
image: WAMediaUpload
|
||||
caption?: string
|
||||
jpegThumbnail?: string
|
||||
} & Mentionable & Contextable & WithDimensions)
|
||||
} & Mentionable &
|
||||
Contextable &
|
||||
WithDimensions)
|
||||
| ({
|
||||
video: WAMediaUpload
|
||||
caption?: string
|
||||
@@ -100,7 +115,9 @@ export type AnyMediaMessageContent = (
|
||||
jpegThumbnail?: string
|
||||
/** if set to true, will send as a `video note` */
|
||||
ptv?: boolean
|
||||
} & Mentionable & Contextable & WithDimensions)
|
||||
} & Mentionable &
|
||||
Contextable &
|
||||
WithDimensions)
|
||||
| {
|
||||
audio: WAMediaUpload
|
||||
/** if set to true, will send as a `voice note` */
|
||||
@@ -111,13 +128,14 @@ export type AnyMediaMessageContent = (
|
||||
| ({
|
||||
sticker: WAMediaUpload
|
||||
isAnimated?: boolean
|
||||
} & WithDimensions) | ({
|
||||
} & WithDimensions)
|
||||
| ({
|
||||
document: WAMediaUpload
|
||||
mimetype: string
|
||||
fileName?: string
|
||||
caption?: string
|
||||
} & Contextable))
|
||||
& { mimetype?: string } & Editable
|
||||
} & Contextable)
|
||||
) & { mimetype?: string } & Editable
|
||||
|
||||
export type ButtonReplyInfo = {
|
||||
displayText: string
|
||||
@@ -138,15 +156,18 @@ export type WASendableProduct = Omit<proto.Message.ProductMessage.IProductSnapsh
|
||||
}
|
||||
|
||||
export type AnyRegularMessageContent = (
|
||||
({
|
||||
| ({
|
||||
text: string
|
||||
linkPreview?: WAUrlInfo | null
|
||||
}
|
||||
& Mentionable & Contextable & Editable)
|
||||
} & Mentionable &
|
||||
Contextable &
|
||||
Editable)
|
||||
| AnyMediaMessageContent
|
||||
| ({
|
||||
poll: PollMessageOptions
|
||||
} & Mentionable & Contextable & Editable)
|
||||
} & Mentionable &
|
||||
Contextable &
|
||||
Editable)
|
||||
| {
|
||||
contacts: {
|
||||
displayName?: string
|
||||
@@ -180,18 +201,25 @@ export type AnyRegularMessageContent = (
|
||||
businessOwnerJid?: string
|
||||
body?: string
|
||||
footer?: string
|
||||
} | SharePhoneNumber | RequestPhoneNumber
|
||||
) & ViewOnce
|
||||
}
|
||||
| SharePhoneNumber
|
||||
| RequestPhoneNumber
|
||||
) &
|
||||
ViewOnce
|
||||
|
||||
export type AnyMessageContent = AnyRegularMessageContent | {
|
||||
export type AnyMessageContent =
|
||||
| AnyRegularMessageContent
|
||||
| {
|
||||
forward: WAMessage
|
||||
force?: boolean
|
||||
} | {
|
||||
}
|
||||
| {
|
||||
/** Delete your message or anyone's message in a group (admin required) */
|
||||
delete: WAMessageKey
|
||||
} | {
|
||||
}
|
||||
| {
|
||||
disappearingMessagesInChat: boolean | number
|
||||
}
|
||||
}
|
||||
|
||||
export type GroupMetadataParticipants = Pick<GroupMetadata, 'participants'>
|
||||
|
||||
@@ -204,7 +232,7 @@ type MinimalRelayOptions = {
|
||||
|
||||
export type MessageRelayOptions = MinimalRelayOptions & {
|
||||
/** 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 */
|
||||
additionalAttributes?: { [_: string]: string }
|
||||
additionalNodes?: BinaryNode[]
|
||||
@@ -236,7 +264,10 @@ export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions &
|
||||
userJid: string
|
||||
}
|
||||
|
||||
export type WAMediaUploadFunction = (encFilePath: string, opts: { fileEncSha256B64: string, mediaType: MediaType, timeoutMs?: number }) => Promise<{ mediaUrl: string, directPath: string }>
|
||||
export type WAMediaUploadFunction = (
|
||||
encFilePath: string,
|
||||
opts: { fileEncSha256B64: string; mediaType: MediaType; timeoutMs?: number }
|
||||
) => Promise<{ mediaUrl: string; directPath: string }>
|
||||
|
||||
export type MediaGenerationOptions = {
|
||||
logger?: ILogger
|
||||
@@ -268,11 +299,11 @@ export type MessageUpsertType = 'append' | 'notify'
|
||||
|
||||
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 MessageUserReceiptUpdate = { key: proto.IMessageKey, receipt: MessageUserReceipt }
|
||||
export type MessageUserReceiptUpdate = { key: proto.IMessageKey; receipt: MessageUserReceipt }
|
||||
|
||||
export type MediaDecryptionKeyInfo = {
|
||||
iv: Buffer
|
||||
|
||||
@@ -2,7 +2,7 @@ import { WAMediaUpload } from './Message'
|
||||
|
||||
export type CatalogResult = {
|
||||
data: {
|
||||
paging: { cursors: { before: string, after: string } }
|
||||
paging: { cursors: { before: string; after: string } }
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
data: any[]
|
||||
}
|
||||
|
||||
@@ -51,9 +51,7 @@ type E2ESessionOpts = {
|
||||
|
||||
export type SignalRepository = {
|
||||
decryptGroupMessage(opts: DecryptGroupSignalOpts): Promise<Uint8Array>
|
||||
processSenderKeyDistributionMessage(
|
||||
opts: ProcessSenderKeyDistributionMessageOpts
|
||||
): Promise<void>
|
||||
processSenderKeyDistributionMessage(opts: ProcessSenderKeyDistributionMessageOpts): Promise<void>
|
||||
decryptMessage(opts: DecryptSignalProtoOpts): Promise<Uint8Array>
|
||||
encryptMessage(opts: EncryptMessageOpts): Promise<{
|
||||
type: 'pkmsg' | 'msg'
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import { AxiosRequestConfig } from 'axios'
|
||||
import type { Agent } from 'https'
|
||||
import type { URL } from 'url'
|
||||
@@ -23,7 +22,7 @@ export type CacheStore = {
|
||||
flushAll(): void
|
||||
}
|
||||
|
||||
export type PatchedMessageWithRecipientJID = proto.IMessage & {recipientJid?: string}
|
||||
export type PatchedMessageWithRecipientJID = proto.IMessage & { recipientJid?: string }
|
||||
|
||||
export type SocketConfig = {
|
||||
/** the WS url to connect to WA */
|
||||
@@ -108,8 +107,11 @@ export type SocketConfig = {
|
||||
* */
|
||||
patchMessageBeforeSending: (
|
||||
msg: proto.IMessage,
|
||||
recipientJids?: string[],
|
||||
) => Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> | PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID
|
||||
recipientJids?: string[]
|
||||
) =>
|
||||
| Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID>
|
||||
| PatchedMessageWithRecipientJID[]
|
||||
| PatchedMessageWithRecipientJID
|
||||
|
||||
/** verify app state MACs */
|
||||
appStateMacVerification: {
|
||||
|
||||
@@ -63,4 +63,4 @@ export type WABusinessProfile = {
|
||||
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 { randomBytes } from 'crypto'
|
||||
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 { delay, generateRegistrationId } from './generics'
|
||||
import { ILogger } from './logger'
|
||||
@@ -17,10 +25,12 @@ export function makeCacheableSignalKeyStore(
|
||||
logger?: ILogger,
|
||||
_cache?: CacheStore
|
||||
): SignalKeyStore {
|
||||
const cache = _cache || new NodeCache({
|
||||
const cache =
|
||||
_cache ||
|
||||
new NodeCache({
|
||||
stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
|
||||
useClones: false,
|
||||
deleteOnExpire: true,
|
||||
deleteOnExpire: true
|
||||
})
|
||||
|
||||
function getUniqueId(type: string, id: string) {
|
||||
@@ -29,23 +39,23 @@ export function makeCacheableSignalKeyStore(
|
||||
|
||||
return {
|
||||
async get(type, ids) {
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||
const idsToFetch: string[] = []
|
||||
for(const id of ids) {
|
||||
for (const id of ids) {
|
||||
const item = cache.get<SignalDataTypeMap[typeof type]>(getUniqueId(type, id))
|
||||
if(typeof item !== 'undefined') {
|
||||
if (typeof item !== 'undefined') {
|
||||
data[id] = item
|
||||
} else {
|
||||
idsToFetch.push(id)
|
||||
}
|
||||
}
|
||||
|
||||
if(idsToFetch.length) {
|
||||
if (idsToFetch.length) {
|
||||
logger?.trace({ items: idsToFetch.length }, 'loading from store')
|
||||
const fetched = await store.get(type, idsToFetch)
|
||||
for(const id of idsToFetch) {
|
||||
for (const id of idsToFetch) {
|
||||
const item = fetched[id]
|
||||
if(item) {
|
||||
if (item) {
|
||||
data[id] = item
|
||||
cache.set(getUniqueId(type, id), item)
|
||||
}
|
||||
@@ -56,8 +66,8 @@ export function makeCacheableSignalKeyStore(
|
||||
},
|
||||
async set(data) {
|
||||
let keys = 0
|
||||
for(const type in data) {
|
||||
for(const id in data[type]) {
|
||||
for (const type in data) {
|
||||
for (const id in data[type]) {
|
||||
cache.set(getUniqueId(type, id), data[type][id])
|
||||
keys += 1
|
||||
}
|
||||
@@ -89,52 +99,45 @@ export const addTransactionCapability = (
|
||||
// number of queries made to the DB during the transaction
|
||||
// only there for logging purposes
|
||||
let dbQueriesInTransaction = 0
|
||||
let transactionCache: SignalDataSet = { }
|
||||
let mutations: SignalDataSet = { }
|
||||
let transactionCache: SignalDataSet = {}
|
||||
let mutations: SignalDataSet = {}
|
||||
|
||||
let transactionsInProgress = 0
|
||||
|
||||
return {
|
||||
get: async(type, ids) => {
|
||||
if(isInTransaction()) {
|
||||
get: async (type, ids) => {
|
||||
if (isInTransaction()) {
|
||||
const dict = transactionCache[type]
|
||||
const idsRequiringFetch = dict
|
||||
? ids.filter(item => typeof dict[item] === 'undefined')
|
||||
: ids
|
||||
const idsRequiringFetch = dict ? ids.filter(item => typeof dict[item] === 'undefined') : ids
|
||||
// only fetch if there are any items to fetch
|
||||
if(idsRequiringFetch.length) {
|
||||
if (idsRequiringFetch.length) {
|
||||
dbQueriesInTransaction += 1
|
||||
const result = await state.get(type, idsRequiringFetch)
|
||||
|
||||
transactionCache[type] ||= {}
|
||||
Object.assign(
|
||||
transactionCache[type]!,
|
||||
result
|
||||
)
|
||||
Object.assign(transactionCache[type]!, result)
|
||||
}
|
||||
|
||||
return ids.reduce(
|
||||
(dict, id) => {
|
||||
return ids.reduce((dict, id) => {
|
||||
const value = transactionCache[type]?.[id]
|
||||
if(value) {
|
||||
if (value) {
|
||||
dict[id] = value
|
||||
}
|
||||
|
||||
return dict
|
||||
}, { }
|
||||
)
|
||||
}, {})
|
||||
} else {
|
||||
return state.get(type, ids)
|
||||
}
|
||||
},
|
||||
set: data => {
|
||||
if(isInTransaction()) {
|
||||
if (isInTransaction()) {
|
||||
logger.trace({ types: Object.keys(data) }, 'caching in transaction')
|
||||
for(const key in data) {
|
||||
transactionCache[key] = transactionCache[key] || { }
|
||||
for (const key in data) {
|
||||
transactionCache[key] = transactionCache[key] || {}
|
||||
Object.assign(transactionCache[key], data[key])
|
||||
|
||||
mutations[key] = mutations[key] || { }
|
||||
mutations[key] = mutations[key] || {}
|
||||
Object.assign(mutations[key], data[key])
|
||||
}
|
||||
} else {
|
||||
@@ -145,27 +148,27 @@ export const addTransactionCapability = (
|
||||
async transaction(work) {
|
||||
let result: Awaited<ReturnType<typeof work>>
|
||||
transactionsInProgress += 1
|
||||
if(transactionsInProgress === 1) {
|
||||
if (transactionsInProgress === 1) {
|
||||
logger.trace('entering transaction')
|
||||
}
|
||||
|
||||
try {
|
||||
result = await work()
|
||||
// commit if this is the outermost transaction
|
||||
if(transactionsInProgress === 1) {
|
||||
if(Object.keys(mutations).length) {
|
||||
if (transactionsInProgress === 1) {
|
||||
if (Object.keys(mutations).length) {
|
||||
logger.trace('committing transaction')
|
||||
// retry mechanism to ensure we've some recovery
|
||||
// in case a transaction fails in the first attempt
|
||||
let tries = maxCommitRetries
|
||||
while(tries) {
|
||||
while (tries) {
|
||||
tries -= 1
|
||||
//eslint-disable-next-line max-depth
|
||||
try {
|
||||
await state.set(mutations)
|
||||
logger.trace({ dbQueriesInTransaction }, 'committed transaction')
|
||||
break
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`)
|
||||
await delay(delayBetweenTriesMs)
|
||||
}
|
||||
@@ -176,9 +179,9 @@ export const addTransactionCapability = (
|
||||
}
|
||||
} finally {
|
||||
transactionsInProgress -= 1
|
||||
if(transactionsInProgress === 0) {
|
||||
transactionCache = { }
|
||||
mutations = { }
|
||||
if (transactionsInProgress === 0) {
|
||||
transactionCache = {}
|
||||
mutations = {}
|
||||
dbQueriesInTransaction = 0
|
||||
}
|
||||
}
|
||||
@@ -211,6 +214,6 @@ export const initAuthCreds = (): AuthenticationCreds => {
|
||||
registered: false,
|
||||
pairingCode: 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
|
||||
const writeMutex = makeMutex()
|
||||
// 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 result = oldEmit.apply(ev, args)
|
||||
|
||||
writeMutex.mutex(
|
||||
async() => {
|
||||
writeMutex.mutex(async () => {
|
||||
await writeFile(filename, content, { flag: 'a' })
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -38,7 +36,7 @@ export const captureEventStream = (ev: BaileysEventEmitter, filename: string) =>
|
||||
export const readAndEmitEventStream = (filename: string, delayIntervalMs = 0) => {
|
||||
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
|
||||
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
|
||||
// ('\r\n') in input.txt as a single line break.
|
||||
for await (const line of rl) {
|
||||
if(line) {
|
||||
if (line) {
|
||||
const { event, data } = JSON.parse(line)
|
||||
ev.emit(event, data)
|
||||
delayIntervalMs && await delay(delayIntervalMs)
|
||||
delayIntervalMs && (await delay(delayIntervalMs))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,17 @@ import { createHash } from 'crypto'
|
||||
import { createWriteStream, promises as fs } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
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 { generateMessageIDV2 } from './generics'
|
||||
import { getStream, getUrlFromDirectPath } from './messages-media'
|
||||
@@ -15,16 +25,13 @@ export const parseCatalogNode = (node: BinaryNode) => {
|
||||
|
||||
return {
|
||||
products,
|
||||
nextPageCursor: paging
|
||||
? getBinaryNodeChildString(paging, 'after')
|
||||
: undefined
|
||||
nextPageCursor: paging ? getBinaryNodeChildString(paging, 'after') : undefined
|
||||
}
|
||||
}
|
||||
|
||||
export const parseCollectionsNode = (node: BinaryNode) => {
|
||||
const collectionsNode = getBinaryNodeChild(node, 'collections')
|
||||
const collections = getBinaryNodeChildren(collectionsNode, 'collection').map<CatalogCollection>(
|
||||
collectionNode => {
|
||||
const collections = getBinaryNodeChildren(collectionsNode, 'collection').map<CatalogCollection>(collectionNode => {
|
||||
const id = getBinaryNodeChildString(collectionNode, 'id')!
|
||||
const name = getBinaryNodeChildString(collectionNode, 'name')!
|
||||
|
||||
@@ -35,8 +42,7 @@ export const parseCollectionsNode = (node: BinaryNode) => {
|
||||
products,
|
||||
status: parseStatusInfo(collectionNode)
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
collections
|
||||
@@ -45,8 +51,7 @@ export const parseCollectionsNode = (node: BinaryNode) => {
|
||||
|
||||
export const parseOrderDetailsNode = (node: BinaryNode) => {
|
||||
const orderNode = getBinaryNodeChild(node, 'order')
|
||||
const products = getBinaryNodeChildren(orderNode, 'product').map<OrderProduct>(
|
||||
productNode => {
|
||||
const products = getBinaryNodeChildren(orderNode, 'product').map<OrderProduct>(productNode => {
|
||||
const imageNode = getBinaryNodeChild(productNode, 'image')!
|
||||
return {
|
||||
id: getBinaryNodeChildString(productNode, 'id')!,
|
||||
@@ -56,15 +61,14 @@ export const parseOrderDetailsNode = (node: BinaryNode) => {
|
||||
currency: getBinaryNodeChildString(productNode, 'currency')!,
|
||||
quantity: +getBinaryNodeChildString(productNode, 'quantity')!
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
const priceNode = getBinaryNodeChild(orderNode, 'price')
|
||||
|
||||
const orderDetails: OrderDetails = {
|
||||
price: {
|
||||
total: +getBinaryNodeChildString(priceNode, 'total')!,
|
||||
currency: getBinaryNodeChildString(priceNode, 'currency')!,
|
||||
currency: getBinaryNodeChildString(priceNode, 'currency')!
|
||||
},
|
||||
products
|
||||
}
|
||||
@@ -73,94 +77,92 @@ export const parseOrderDetailsNode = (node: BinaryNode) => {
|
||||
}
|
||||
|
||||
export const toProductNode = (productId: string | undefined, product: ProductCreate | ProductUpdate) => {
|
||||
const attrs: BinaryNode['attrs'] = { }
|
||||
const content: BinaryNode[] = [ ]
|
||||
const attrs: BinaryNode['attrs'] = {}
|
||||
const content: BinaryNode[] = []
|
||||
|
||||
if(typeof productId !== 'undefined') {
|
||||
if (typeof productId !== 'undefined') {
|
||||
content.push({
|
||||
tag: 'id',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(productId)
|
||||
})
|
||||
}
|
||||
|
||||
if(typeof product.name !== 'undefined') {
|
||||
if (typeof product.name !== 'undefined') {
|
||||
content.push({
|
||||
tag: 'name',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(product.name)
|
||||
})
|
||||
}
|
||||
|
||||
if(typeof product.description !== 'undefined') {
|
||||
if (typeof product.description !== 'undefined') {
|
||||
content.push({
|
||||
tag: 'description',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(product.description)
|
||||
})
|
||||
}
|
||||
|
||||
if(typeof product.retailerId !== 'undefined') {
|
||||
if (typeof product.retailerId !== 'undefined') {
|
||||
content.push({
|
||||
tag: 'retailer_id',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(product.retailerId)
|
||||
})
|
||||
}
|
||||
|
||||
if(product.images.length) {
|
||||
if (product.images.length) {
|
||||
content.push({
|
||||
tag: 'media',
|
||||
attrs: { },
|
||||
content: product.images.map(
|
||||
img => {
|
||||
if(!('url' in img)) {
|
||||
attrs: {},
|
||||
content: product.images.map(img => {
|
||||
if (!('url' in img)) {
|
||||
throw new Boom('Expected img for product to already be uploaded', { statusCode: 400 })
|
||||
}
|
||||
|
||||
return {
|
||||
tag: 'image',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{
|
||||
tag: 'url',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(img.url.toString())
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if(typeof product.price !== 'undefined') {
|
||||
if (typeof product.price !== 'undefined') {
|
||||
content.push({
|
||||
tag: 'price',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(product.price.toString())
|
||||
})
|
||||
}
|
||||
|
||||
if(typeof product.currency !== 'undefined') {
|
||||
if (typeof product.currency !== 'undefined') {
|
||||
content.push({
|
||||
tag: 'currency',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(product.currency)
|
||||
})
|
||||
}
|
||||
|
||||
if('originCountryCode' in product) {
|
||||
if(typeof product.originCountryCode === 'undefined') {
|
||||
if ('originCountryCode' in product) {
|
||||
if (typeof product.originCountryCode === 'undefined') {
|
||||
attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT'
|
||||
} else {
|
||||
content.push({
|
||||
tag: 'compliance_info',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{
|
||||
tag: 'country_code_origin',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: Buffer.from(product.originCountryCode)
|
||||
}
|
||||
]
|
||||
@@ -168,8 +170,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()
|
||||
}
|
||||
|
||||
@@ -192,7 +193,7 @@ export const parseProductNode = (productNode: BinaryNode) => {
|
||||
id,
|
||||
imageUrls: parseImageUrls(mediaNode),
|
||||
reviewStatus: {
|
||||
whatsapp: getBinaryNodeChildString(statusInfoNode, 'status')!,
|
||||
whatsapp: getBinaryNodeChildString(statusInfoNode, 'status')!
|
||||
},
|
||||
availability: 'in stock',
|
||||
name: getBinaryNodeChildString(productNode, 'name')!,
|
||||
@@ -201,7 +202,7 @@ export const parseProductNode = (productNode: BinaryNode) => {
|
||||
description: getBinaryNodeChildString(productNode, 'description')!,
|
||||
price: +getBinaryNodeChildString(productNode, 'price')!,
|
||||
currency: getBinaryNodeChildString(productNode, 'currency')!,
|
||||
isHidden,
|
||||
isHidden
|
||||
}
|
||||
|
||||
return product
|
||||
@@ -210,10 +211,16 @@ export const parseProductNode = (productNode: BinaryNode) => {
|
||||
/**
|
||||
* 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,
|
||||
images: product.images ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs) : product.images
|
||||
images: product.images
|
||||
? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs)
|
||||
: product.images
|
||||
}
|
||||
return product
|
||||
}
|
||||
@@ -221,18 +228,16 @@ export async function uploadingNecessaryImagesOfProduct<T extends ProductUpdate
|
||||
/**
|
||||
* Uploads images not already uploaded to WA's servers
|
||||
*/
|
||||
export const uploadingNecessaryImages = async(
|
||||
export const uploadingNecessaryImages = async (
|
||||
images: WAMediaUpload[],
|
||||
waUploadToServer: WAMediaUploadFunction,
|
||||
timeoutMs = 30_000
|
||||
) => {
|
||||
const results = await Promise.all(
|
||||
images.map<Promise<{ url: string }>>(
|
||||
async img => {
|
||||
|
||||
if('url' in img) {
|
||||
images.map<Promise<{ url: string }>>(async img => {
|
||||
if ('url' in img) {
|
||||
const url = img.url.toString()
|
||||
if(url.includes('.whatsapp.net')) {
|
||||
if (url.includes('.whatsapp.net')) {
|
||||
return { url }
|
||||
}
|
||||
}
|
||||
@@ -250,22 +255,16 @@ export const uploadingNecessaryImages = async(
|
||||
|
||||
const sha = hasher.digest('base64')
|
||||
|
||||
const { directPath } = await waUploadToServer(
|
||||
filePath,
|
||||
{
|
||||
const { directPath } = await waUploadToServer(filePath, {
|
||||
mediaType: 'product-catalog-image',
|
||||
fileEncSha256B64: sha,
|
||||
timeoutMs
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
await fs
|
||||
.unlink(filePath)
|
||||
.catch(err => console.log('Error deleting temp file ', err))
|
||||
await fs.unlink(filePath).catch(err => console.log('Error deleting temp file ', err))
|
||||
|
||||
return { url: getUrlFromDirectPath(directPath) }
|
||||
}
|
||||
)
|
||||
})
|
||||
)
|
||||
return results
|
||||
}
|
||||
@@ -282,6 +281,6 @@ const parseStatusInfo = (mediaNode: BinaryNode): CatalogStatus => {
|
||||
const node = getBinaryNodeChild(mediaNode, 'status_info')
|
||||
return {
|
||||
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 { AxiosRequestConfig } from 'axios'
|
||||
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 { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary'
|
||||
import { aesDecrypt, aesEncrypt, hkdf, hmacSign } from './crypto'
|
||||
import { toNumber } from './generics'
|
||||
import { ILogger } from './logger'
|
||||
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>
|
||||
|
||||
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' })
|
||||
return {
|
||||
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 = () => {
|
||||
let r: number
|
||||
switch (operation) {
|
||||
@@ -58,7 +75,7 @@ const to64BitNetworkOrder = (e: number) => {
|
||||
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'>) => {
|
||||
indexValueMap = { ...indexValueMap }
|
||||
@@ -69,8 +86,8 @@ const makeLtHashGenerator = ({ indexValueMap, hash }: Pick<LTHashState, 'hash' |
|
||||
mix: ({ indexMac, valueMac, operation }: Mac) => {
|
||||
const indexMacBase64 = Buffer.from(indexMac).toString('base64')
|
||||
const prevOp = indexValueMap[indexMacBase64]
|
||||
if(operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
|
||||
if(!prevOp) {
|
||||
if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
|
||||
if (!prevOp) {
|
||||
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 }
|
||||
}
|
||||
|
||||
if(prevOp) {
|
||||
if (prevOp) {
|
||||
subBuffs.push(new Uint8Array(prevOp.valueMac).buffer)
|
||||
}
|
||||
},
|
||||
finish: async() => {
|
||||
finish: async () => {
|
||||
const hashArrayBuffer = new Uint8Array(hash).buffer
|
||||
const result = await LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs)
|
||||
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 total = Buffer.concat([
|
||||
lthash,
|
||||
to64BitNetworkOrder(version),
|
||||
Buffer.from(name, 'utf-8')
|
||||
])
|
||||
const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')])
|
||||
return hmacSign(total, key, 'sha256')
|
||||
}
|
||||
|
||||
const generatePatchMac = (snapshotMac: Uint8Array, valueMacs: Uint8Array[], version: number, type: WAPatchName, key: Buffer) => {
|
||||
const total = Buffer.concat([
|
||||
snapshotMac,
|
||||
...valueMacs,
|
||||
to64BitNetworkOrder(version),
|
||||
Buffer.from(type, 'utf-8')
|
||||
])
|
||||
const generatePatchMac = (
|
||||
snapshotMac: Uint8Array,
|
||||
valueMacs: Uint8Array[],
|
||||
version: number,
|
||||
type: WAPatchName,
|
||||
key: Buffer
|
||||
) => {
|
||||
const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')])
|
||||
return hmacSign(total, key)
|
||||
}
|
||||
|
||||
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,
|
||||
myAppStateKeyId: string,
|
||||
state: LTHashState,
|
||||
getAppStateSyncKey: FetchAppStateSyncKey
|
||||
) => {
|
||||
const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined
|
||||
if(!key) {
|
||||
if (!key) {
|
||||
throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 })
|
||||
}
|
||||
|
||||
@@ -185,7 +199,7 @@ export const encodeSyncdPatch = async(
|
||||
return { patch, state }
|
||||
}
|
||||
|
||||
export const decodeSyncdMutations = async(
|
||||
export const decodeSyncdMutations = async (
|
||||
msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[],
|
||||
initialState: LTHashState,
|
||||
getAppStateSyncKey: FetchAppStateSyncKey,
|
||||
@@ -196,19 +210,20 @@ export const decodeSyncdMutations = async(
|
||||
// indexKey used to HMAC sign record.index.blob
|
||||
// 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
|
||||
for(const msgMutation of msgMutations) {
|
||||
for (const msgMutation of msgMutations) {
|
||||
// if it's a syncdmutation, get the operation property
|
||||
// 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 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 content = Buffer.from(record.value!.blob!)
|
||||
const encContent = content.slice(0, -32)
|
||||
const ogValueMac = content.slice(-32)
|
||||
if(validateMacs) {
|
||||
if (validateMacs) {
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -216,9 +231,9 @@ export const decodeSyncdMutations = async(
|
||||
const result = aesDecrypt(encContent, key.valueEncryptionKey)
|
||||
const syncAction = proto.SyncActionData.decode(result)
|
||||
|
||||
if(validateMacs) {
|
||||
if (validateMacs) {
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -238,15 +253,18 @@ export const decodeSyncdMutations = async(
|
||||
async function getKey(keyId: Uint8Array) {
|
||||
const base64Key = Buffer.from(keyId).toString('base64')
|
||||
const keyEnc = await getAppStateSyncKey(base64Key)
|
||||
if(!keyEnc) {
|
||||
throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { statusCode: 404, data: { msgMutations } })
|
||||
if (!keyEnc) {
|
||||
throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
|
||||
statusCode: 404,
|
||||
data: { msgMutations }
|
||||
})
|
||||
}
|
||||
|
||||
return mutationKeys(keyEnc.keyData!)
|
||||
}
|
||||
}
|
||||
|
||||
export const decodeSyncdPatch = async(
|
||||
export const decodeSyncdPatch = async (
|
||||
msg: proto.ISyncdPatch,
|
||||
name: WAPatchName,
|
||||
initialState: LTHashState,
|
||||
@@ -254,18 +272,24 @@ export const decodeSyncdPatch = async(
|
||||
onMutation: (mutation: ChatMutation) => void,
|
||||
validateMacs: boolean
|
||||
) => {
|
||||
if(validateMacs) {
|
||||
if (validateMacs) {
|
||||
const base64Key = Buffer.from(msg.keyId!.id!).toString('base64')
|
||||
const mainKeyObj = await getAppStateSyncKey(base64Key)
|
||||
if(!mainKeyObj) {
|
||||
if (!mainKeyObj) {
|
||||
throw new Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } })
|
||||
}
|
||||
|
||||
const mainKey = await mutationKeys(mainKeyObj.keyData!)
|
||||
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)
|
||||
if(Buffer.compare(patchMac, msg.patchMac!) !== 0) {
|
||||
const patchMac = generatePatchMac(
|
||||
msg.snapshotMac!,
|
||||
mutationmacs,
|
||||
toNumber(msg.version!.version),
|
||||
name,
|
||||
mainKey.patchMacKey
|
||||
)
|
||||
if (Buffer.compare(patchMac, msg.patchMac!) !== 0) {
|
||||
throw new Boom('Invalid patch mac')
|
||||
}
|
||||
}
|
||||
@@ -274,17 +298,15 @@ export const decodeSyncdPatch = async(
|
||||
return result
|
||||
}
|
||||
|
||||
export const extractSyncdPatches = async(
|
||||
result: BinaryNode,
|
||||
options: AxiosRequestConfig<{}>
|
||||
) => {
|
||||
export const extractSyncdPatches = async (result: BinaryNode, options: AxiosRequestConfig<{}>) => {
|
||||
const syncNode = getBinaryNodeChild(result, 'sync')
|
||||
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(
|
||||
collectionNodes.map(
|
||||
async collectionNode => {
|
||||
collectionNodes.map(async collectionNode => {
|
||||
const patchesNode = getBinaryNodeChild(collectionNode, 'patches')
|
||||
|
||||
const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch')
|
||||
@@ -296,26 +318,24 @@ export const extractSyncdPatches = async(
|
||||
const hasMorePatches = collectionNode.attrs.has_more_patches === 'true'
|
||||
|
||||
let snapshot: proto.ISyncdSnapshot | undefined = undefined
|
||||
if(snapshotNode && !!snapshotNode.content) {
|
||||
if(!Buffer.isBuffer(snapshotNode)) {
|
||||
if (snapshotNode && !!snapshotNode.content) {
|
||||
if (!Buffer.isBuffer(snapshotNode)) {
|
||||
snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
|
||||
}
|
||||
|
||||
const blobRef = proto.ExternalBlobReference.decode(
|
||||
snapshotNode.content as Buffer
|
||||
)
|
||||
const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content as Buffer)
|
||||
const data = await downloadExternalBlob(blobRef, options)
|
||||
snapshot = proto.SyncdSnapshot.decode(data)
|
||||
}
|
||||
|
||||
for(let { content } of patches) {
|
||||
if(content) {
|
||||
if(!Buffer.isBuffer(content)) {
|
||||
for (let { content } of patches) {
|
||||
if (content) {
|
||||
if (!Buffer.isBuffer(content)) {
|
||||
content = Buffer.from(Object.values(content))
|
||||
}
|
||||
|
||||
const syncd = proto.SyncdPatch.decode(content as Uint8Array)
|
||||
if(!syncd.version) {
|
||||
if (!syncd.version) {
|
||||
syncd.version = { version: +collectionNode.attrs.version + 1 }
|
||||
}
|
||||
|
||||
@@ -324,18 +344,13 @@ export const extractSyncdPatches = async(
|
||||
}
|
||||
|
||||
final[name] = { patches: syncds, hasMorePatches, snapshot }
|
||||
}
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
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 bufferArray: Buffer[] = []
|
||||
for await (const chunk of stream) {
|
||||
@@ -345,16 +360,13 @@ export const downloadExternalBlob = async(
|
||||
return Buffer.concat(bufferArray)
|
||||
}
|
||||
|
||||
export const downloadExternalPatch = async(
|
||||
blob: proto.IExternalBlobReference,
|
||||
options: AxiosRequestConfig<{}>
|
||||
) => {
|
||||
export const downloadExternalPatch = async (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => {
|
||||
const buffer = await downloadExternalBlob(blob, options)
|
||||
const syncData = proto.SyncdMutations.decode(buffer)
|
||||
return syncData
|
||||
}
|
||||
|
||||
export const decodeSyncdSnapshot = async(
|
||||
export const decodeSyncdSnapshot = async (
|
||||
name: WAPatchName,
|
||||
snapshot: proto.ISyncdSnapshot,
|
||||
getAppStateSyncKey: FetchAppStateSyncKey,
|
||||
@@ -365,34 +377,33 @@ export const decodeSyncdSnapshot = async(
|
||||
newState.version = toNumber(snapshot.version!.version)
|
||||
|
||||
const mutationMap: ChatMutationMap = {}
|
||||
const areMutationsRequired = typeof minimumVersionNumber === 'undefined'
|
||||
|| newState.version > minimumVersionNumber
|
||||
const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber
|
||||
|
||||
const { hash, indexValueMap } = await decodeSyncdMutations(
|
||||
snapshot.records!,
|
||||
newState,
|
||||
getAppStateSyncKey,
|
||||
areMutationsRequired
|
||||
? (mutation) => {
|
||||
? mutation => {
|
||||
const index = mutation.syncAction.index?.toString()
|
||||
mutationMap[index!] = mutation
|
||||
}
|
||||
: () => { },
|
||||
: () => {},
|
||||
validateMacs
|
||||
)
|
||||
newState.hash = hash
|
||||
newState.indexValueMap = indexValueMap
|
||||
|
||||
if(validateMacs) {
|
||||
if (validateMacs) {
|
||||
const base64Key = Buffer.from(snapshot.keyId!.id!).toString('base64')
|
||||
const keyEnc = await getAppStateSyncKey(base64Key)
|
||||
if(!keyEnc) {
|
||||
if (!keyEnc) {
|
||||
throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
|
||||
}
|
||||
|
||||
const result = await mutationKeys(keyEnc.keyData!)
|
||||
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`)
|
||||
}
|
||||
}
|
||||
@@ -403,7 +414,7 @@ export const decodeSyncdSnapshot = async(
|
||||
}
|
||||
}
|
||||
|
||||
export const decodePatches = async(
|
||||
export const decodePatches = async (
|
||||
name: WAPatchName,
|
||||
syncds: proto.ISyncdPatch[],
|
||||
initial: LTHashState,
|
||||
@@ -420,9 +431,9 @@ export const decodePatches = async(
|
||||
|
||||
const mutationMap: ChatMutationMap = {}
|
||||
|
||||
for(const syncd of syncds) {
|
||||
for (const syncd of syncds) {
|
||||
const { version, keyId, snapshotMac } = syncd
|
||||
if(syncd.externalMutations) {
|
||||
if (syncd.externalMutations) {
|
||||
logger?.trace({ name, version }, 'downloading external patch')
|
||||
const ref = await downloadExternalPatch(syncd.externalMutations, options)
|
||||
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()
|
||||
mutationMap[index!] = mutation
|
||||
}
|
||||
: (() => { }),
|
||||
: () => {},
|
||||
true
|
||||
)
|
||||
|
||||
newState.hash = decodeResult.hash
|
||||
newState.indexValueMap = decodeResult.indexValueMap
|
||||
|
||||
if(validateMacs) {
|
||||
if (validateMacs) {
|
||||
const base64Key = Buffer.from(keyId!.id!).toString('base64')
|
||||
const keyEnc = await getAppStateSyncKey(base64Key)
|
||||
if(!keyEnc) {
|
||||
if (!keyEnc) {
|
||||
throw new Boom(`failed to find key "${base64Key}" to decode mutation`)
|
||||
}
|
||||
|
||||
const result = await mutationKeys(keyEnc.keyData!)
|
||||
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}`)
|
||||
}
|
||||
}
|
||||
@@ -472,38 +483,35 @@ export const decodePatches = async(
|
||||
return { state: newState, mutationMap }
|
||||
}
|
||||
|
||||
export const chatModificationToAppPatch = (
|
||||
mod: ChatModification,
|
||||
jid: string
|
||||
) => {
|
||||
export const chatModificationToAppPatch = (mod: ChatModification, jid: string) => {
|
||||
const OP = proto.SyncdMutation.SyncdOperation
|
||||
const getMessageRange = (lastMessages: LastMessageList) => {
|
||||
let messageRange: proto.SyncActionValue.ISyncActionMessageRange
|
||||
if(Array.isArray(lastMessages)) {
|
||||
if (Array.isArray(lastMessages)) {
|
||||
const lastMsg = lastMessages[lastMessages.length - 1]
|
||||
messageRange = {
|
||||
lastMessageTimestamp: lastMsg?.messageTimestamp,
|
||||
messages: lastMessages?.length ? lastMessages.map(
|
||||
m => {
|
||||
if(!m.key?.id || !m.key?.remoteJid) {
|
||||
messages: lastMessages?.length
|
||||
? lastMessages.map(m => {
|
||||
if (!m.key?.id || !m.key?.remoteJid) {
|
||||
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 })
|
||||
}
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
if(m.key.participant) {
|
||||
if (m.key.participant) {
|
||||
m.key.participant = jidNormalizedUser(m.key.participant)
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
) : undefined
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
} else {
|
||||
messageRange = lastMessages
|
||||
@@ -513,7 +521,7 @@ export const chatModificationToAppPatch = (
|
||||
}
|
||||
|
||||
let patch: WAPatchCreate
|
||||
if('mute' in mod) {
|
||||
if ('mute' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
muteAction: {
|
||||
@@ -526,7 +534,7 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 2,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('archive' in mod) {
|
||||
} else if ('archive' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
archiveChatAction: {
|
||||
@@ -539,7 +547,7 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 3,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('markRead' in mod) {
|
||||
} else if ('markRead' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
markChatAsReadAction: {
|
||||
@@ -552,7 +560,7 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 3,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('deleteForMe' in mod) {
|
||||
} else if ('deleteForMe' in mod) {
|
||||
const { timestamp, key, deleteMedia } = mod.deleteForMe
|
||||
patch = {
|
||||
syncAction: {
|
||||
@@ -566,7 +574,7 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 3,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('clear' in mod) {
|
||||
} else if ('clear' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
clearChatAction: {} // add message range later
|
||||
@@ -576,7 +584,7 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 6,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('pin' in mod) {
|
||||
} else if ('pin' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
pinAction: {
|
||||
@@ -588,7 +596,7 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 5,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('star' in mod) {
|
||||
} else if ('star' in mod) {
|
||||
const key = mod.star.messages[0]
|
||||
patch = {
|
||||
syncAction: {
|
||||
@@ -601,11 +609,11 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 2,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('delete' in mod) {
|
||||
} else if ('delete' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
deleteChatAction: {
|
||||
messageRange: getMessageRange(mod.lastMessages),
|
||||
messageRange: getMessageRange(mod.lastMessages)
|
||||
}
|
||||
},
|
||||
index: ['deleteChat', jid, '1'],
|
||||
@@ -613,7 +621,7 @@ export const chatModificationToAppPatch = (
|
||||
apiVersion: 6,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('pushNameSetting' in mod) {
|
||||
} else if ('pushNameSetting' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
pushNameSetting: {
|
||||
@@ -623,71 +631,64 @@ export const chatModificationToAppPatch = (
|
||||
index: ['setting_pushName'],
|
||||
type: 'critical_block',
|
||||
apiVersion: 1,
|
||||
operation: OP.SET,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('addLabel' in mod) {
|
||||
} else if ('addLabel' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
labelEditAction: {
|
||||
name: mod.addLabel.name,
|
||||
color: mod.addLabel.color,
|
||||
predefinedId : mod.addLabel.predefinedId,
|
||||
predefinedId: mod.addLabel.predefinedId,
|
||||
deleted: mod.addLabel.deleted
|
||||
}
|
||||
},
|
||||
index: ['label_edit', mod.addLabel.id],
|
||||
type: 'regular',
|
||||
apiVersion: 3,
|
||||
operation: OP.SET,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('addChatLabel' in mod) {
|
||||
} else if ('addChatLabel' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
labelAssociationAction: {
|
||||
labeled: true,
|
||||
labeled: true
|
||||
}
|
||||
},
|
||||
index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
|
||||
type: 'regular',
|
||||
apiVersion: 3,
|
||||
operation: OP.SET,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('removeChatLabel' in mod) {
|
||||
} else if ('removeChatLabel' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
labelAssociationAction: {
|
||||
labeled: false,
|
||||
labeled: false
|
||||
}
|
||||
},
|
||||
index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
|
||||
type: 'regular',
|
||||
apiVersion: 3,
|
||||
operation: OP.SET,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('addMessageLabel' in mod) {
|
||||
} else if ('addMessageLabel' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
labelAssociationAction: {
|
||||
labeled: true,
|
||||
labeled: true
|
||||
}
|
||||
},
|
||||
index: [
|
||||
LabelAssociationType.Message,
|
||||
mod.addMessageLabel.labelId,
|
||||
jid,
|
||||
mod.addMessageLabel.messageId,
|
||||
'0',
|
||||
'0'
|
||||
],
|
||||
index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
|
||||
type: 'regular',
|
||||
apiVersion: 3,
|
||||
operation: OP.SET,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else if('removeMessageLabel' in mod) {
|
||||
} else if ('removeMessageLabel' in mod) {
|
||||
patch = {
|
||||
syncAction: {
|
||||
labelAssociationAction: {
|
||||
labeled: false,
|
||||
labeled: false
|
||||
}
|
||||
},
|
||||
index: [
|
||||
@@ -700,7 +701,7 @@ export const chatModificationToAppPatch = (
|
||||
],
|
||||
type: 'regular',
|
||||
apiVersion: 3,
|
||||
operation: OP.SET,
|
||||
operation: OP.SET
|
||||
}
|
||||
} else {
|
||||
throw new Boom('not supported')
|
||||
@@ -716,7 +717,7 @@ export const processSyncAction = (
|
||||
ev: BaileysEventEmitter,
|
||||
me: Contact,
|
||||
initialSyncOpts?: InitialAppStateSyncOptions,
|
||||
logger?: ILogger,
|
||||
logger?: ILogger
|
||||
) => {
|
||||
const isInitialSync = !!initialSyncOpts
|
||||
const accountSettings = initialSyncOpts?.accountSettings
|
||||
@@ -728,20 +729,15 @@ export const processSyncAction = (
|
||||
index: [type, id, msgId, fromMe]
|
||||
} = syncAction
|
||||
|
||||
if(action?.muteAction) {
|
||||
ev.emit(
|
||||
'chats.update',
|
||||
[
|
||||
if (action?.muteAction) {
|
||||
ev.emit('chats.update', [
|
||||
{
|
||||
id,
|
||||
muteEndTime: action.muteAction?.muted
|
||||
? toNumber(action.muteAction.muteEndTimestamp)
|
||||
: null,
|
||||
muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
|
||||
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
|
||||
// when we're initially syncing the app state
|
||||
// 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,
|
||||
// it'll always take an app state action to mark in unarchived -- which we'll get anyway
|
||||
const archiveAction = action?.archiveChatAction
|
||||
const isArchived = archiveAction
|
||||
? archiveAction.archived
|
||||
: type === 'archive'
|
||||
const isArchived = archiveAction ? archiveAction.archived : type === 'archive'
|
||||
// // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
|
||||
// // this only applies for the initial sync
|
||||
// if(isInitialSync && !isArchived) {
|
||||
@@ -765,24 +759,28 @@ export const processSyncAction = (
|
||||
const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange
|
||||
// logger?.debug({ chat: id, syncAction }, 'message range archive')
|
||||
|
||||
ev.emit('chats.update', [{
|
||||
ev.emit('chats.update', [
|
||||
{
|
||||
id,
|
||||
archived: isArchived,
|
||||
conditional: getChatUpdateConditional(id, msgRange)
|
||||
}])
|
||||
} else if(action?.markChatAsReadAction) {
|
||||
}
|
||||
])
|
||||
} else if (action?.markChatAsReadAction) {
|
||||
const markReadAction = action.markChatAsReadAction
|
||||
// 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
|
||||
// this only applies for the initial sync
|
||||
const isNullUpdate = isInitialSync && markReadAction.read
|
||||
|
||||
ev.emit('chats.update', [{
|
||||
ev.emit('chats.update', [
|
||||
{
|
||||
id,
|
||||
unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
|
||||
conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
|
||||
}])
|
||||
} else if(action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
|
||||
}
|
||||
])
|
||||
} else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
|
||||
ev.emit('messages.delete', {
|
||||
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! }])
|
||||
} else if(action?.pushNameSetting) {
|
||||
} else if (action?.pushNameSetting) {
|
||||
const name = action?.pushNameSetting?.name
|
||||
if(name && me?.name !== name) {
|
||||
if (name && me?.name !== name) {
|
||||
ev.emit('creds.update', { me: { ...me, name } })
|
||||
}
|
||||
} else if(action?.pinAction) {
|
||||
ev.emit('chats.update', [{
|
||||
} else if (action?.pinAction) {
|
||||
ev.emit('chats.update', [
|
||||
{
|
||||
id,
|
||||
pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
|
||||
conditional: getChatUpdateConditional(id, undefined)
|
||||
}])
|
||||
} else if(action?.unarchiveChatsSetting) {
|
||||
}
|
||||
])
|
||||
} else if (action?.unarchiveChatsSetting) {
|
||||
const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats
|
||||
ev.emit('creds.update', { accountSettings: { unarchiveChats } })
|
||||
|
||||
logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`)
|
||||
if(accountSettings) {
|
||||
if (accountSettings) {
|
||||
accountSettings.unarchiveChats = unarchiveChats
|
||||
}
|
||||
} else if(action?.starAction || type === 'star') {
|
||||
} else if (action?.starAction || type === 'star') {
|
||||
let starred = action?.starAction?.starred
|
||||
if(typeof starred !== 'boolean') {
|
||||
if (typeof starred !== 'boolean') {
|
||||
starred = syncAction.index[syncAction.index.length - 1] === '1'
|
||||
}
|
||||
|
||||
@@ -825,11 +825,11 @@ export const processSyncAction = (
|
||||
update: { starred }
|
||||
}
|
||||
])
|
||||
} else if(action?.deleteChatAction || type === 'deleteChat') {
|
||||
if(!isInitialSync) {
|
||||
} else if (action?.deleteChatAction || type === 'deleteChat') {
|
||||
if (!isInitialSync) {
|
||||
ev.emit('chats.delete', [id])
|
||||
}
|
||||
} else if(action?.labelEditAction) {
|
||||
} else if (action?.labelEditAction) {
|
||||
const { name, color, deleted, predefinedId } = action.labelEditAction
|
||||
|
||||
ev.emit('labels.edit', {
|
||||
@@ -839,40 +839,45 @@ export const processSyncAction = (
|
||||
deleted: deleted!,
|
||||
predefinedId: predefinedId ? String(predefinedId) : undefined
|
||||
})
|
||||
} else if(action?.labelAssociationAction) {
|
||||
} else if (action?.labelAssociationAction) {
|
||||
ev.emit('labels.association', {
|
||||
type: action.labelAssociationAction.labeled
|
||||
? 'add'
|
||||
: 'remove',
|
||||
association: type === LabelAssociationType.Chat
|
||||
? {
|
||||
type: action.labelAssociationAction.labeled ? 'add' : 'remove',
|
||||
association:
|
||||
type === LabelAssociationType.Chat
|
||||
? ({
|
||||
type: LabelAssociationType.Chat,
|
||||
chatId: syncAction.index[2],
|
||||
labelId: syncAction.index[1]
|
||||
} as ChatLabelAssociation
|
||||
: {
|
||||
} as ChatLabelAssociation)
|
||||
: ({
|
||||
type: LabelAssociationType.Message,
|
||||
chatId: syncAction.index[2],
|
||||
messageId: syncAction.index[3],
|
||||
labelId: syncAction.index[1]
|
||||
} as MessageLabelAssociation
|
||||
} as MessageLabelAssociation)
|
||||
})
|
||||
} else {
|
||||
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
|
||||
? (data) => {
|
||||
? data => {
|
||||
const chat = data.historySets.chats[id] || data.chatUpserts[id]
|
||||
if(chat) {
|
||||
if (chat) {
|
||||
return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true
|
||||
}
|
||||
}
|
||||
: 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 chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0)
|
||||
return lastMsgTimestamp >= chatLastMsgTimestamp
|
||||
|
||||
@@ -7,11 +7,8 @@ import { KeyPair } from '../Types'
|
||||
const { subtle } = globalThis.crypto
|
||||
|
||||
/** prefix version byte to the pub keys, required for some curve crypto functions */
|
||||
export const generateSignalPubKey = (pubKey: Uint8Array | Buffer) => (
|
||||
pubKey.length === 33
|
||||
? pubKey
|
||||
: Buffer.concat([ KEY_BUNDLE_TYPE, pubKey ])
|
||||
)
|
||||
export const generateSignalPubKey = (pubKey: Uint8Array | Buffer) =>
|
||||
pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey])
|
||||
|
||||
export const Curve = {
|
||||
generateKeyPair: (): KeyPair => {
|
||||
@@ -26,14 +23,12 @@ export const Curve = {
|
||||
const shared = libsignal.curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey)
|
||||
return Buffer.from(shared)
|
||||
},
|
||||
sign: (privateKey: Uint8Array, buf: Uint8Array) => (
|
||||
libsignal.curve.calculateSignature(privateKey, buf)
|
||||
),
|
||||
sign: (privateKey: Uint8Array, buf: Uint8Array) => libsignal.curve.calculateSignature(privateKey, buf),
|
||||
verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => {
|
||||
try {
|
||||
libsignal.curve.verifySignature(generateSignalPubKey(pubKey), message, signature)
|
||||
return true
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -73,7 +68,7 @@ export function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8
|
||||
decipher.setAAD(additionalData)
|
||||
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) {
|
||||
@@ -111,7 +106,11 @@ export function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer) {
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
|
||||
@@ -127,27 +126,17 @@ export function md5(buffer: Buffer) {
|
||||
export async function hkdf(
|
||||
buffer: Uint8Array | Buffer,
|
||||
expandedLength: number,
|
||||
info: { salt?: Buffer, info?: string }
|
||||
info: { salt?: Buffer; info?: string }
|
||||
): Promise<Buffer> {
|
||||
// Ensure we have a Uint8Array for the key material
|
||||
const inputKeyMaterial = buffer instanceof Uint8Array
|
||||
? buffer
|
||||
: new Uint8Array(buffer)
|
||||
const inputKeyMaterial = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)
|
||||
|
||||
// Set default values if not provided
|
||||
const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0)
|
||||
const infoBytes = info.info
|
||||
? new TextEncoder().encode(info.info)
|
||||
: new Uint8Array(0)
|
||||
const infoBytes = info.info ? new TextEncoder().encode(info.info) : new Uint8Array(0)
|
||||
|
||||
// Import the input key material
|
||||
const importedKey = await subtle.importKey(
|
||||
'raw',
|
||||
inputKeyMaterial,
|
||||
{ name: 'HKDF' },
|
||||
false,
|
||||
['deriveBits']
|
||||
)
|
||||
const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits'])
|
||||
|
||||
// Derive bits using HKDF
|
||||
const derivedBits = await subtle.deriveBits(
|
||||
@@ -164,7 +153,6 @@ export async function hkdf(
|
||||
return Buffer.from(derivedBits)
|
||||
}
|
||||
|
||||
|
||||
export async function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer> {
|
||||
// Convert inputs to formats Web Crypto API can work with
|
||||
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)
|
||||
|
||||
// Import the pairing code as key material
|
||||
const keyMaterial = await subtle.importKey(
|
||||
'raw',
|
||||
pairingCodeBuffer,
|
||||
{ name: 'PBKDF2' },
|
||||
false,
|
||||
['deriveBits']
|
||||
)
|
||||
const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits'])
|
||||
|
||||
// Derive bits using PBKDF2 with the same parameters
|
||||
// 2 << 16 = 131,072 iterations
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
import { Boom } from '@hapi/boom'
|
||||
import { proto } from '../../WAProto'
|
||||
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 { ILogger } from './logger'
|
||||
|
||||
@@ -24,17 +34,20 @@ export const NACK_REASONS = {
|
||||
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.
|
||||
* @note this will only parse the message, not decrypt it
|
||||
*/
|
||||
export function decodeMessageNode(
|
||||
stanza: BinaryNode,
|
||||
meId: string,
|
||||
meLid: string
|
||||
) {
|
||||
export function decodeMessageNode(stanza: BinaryNode, meId: string, meLid: string) {
|
||||
let msgType: MessageType
|
||||
let chatId: string
|
||||
let author: string
|
||||
@@ -47,9 +60,9 @@ export function decodeMessageNode(
|
||||
const isMe = (jid: string) => areJidsSameUser(jid, meId)
|
||||
const isMeLid = (jid: string) => areJidsSameUser(jid, meLid)
|
||||
|
||||
if(isJidUser(from) || isLidUser(from)) {
|
||||
if(recipient && !isJidMetaIa(recipient)) {
|
||||
if(!isMe(from) && !isMeLid(from)) {
|
||||
if (isJidUser(from) || isLidUser(from)) {
|
||||
if (recipient && !isJidMetaIa(recipient)) {
|
||||
if (!isMe(from) && !isMeLid(from)) {
|
||||
throw new Boom('receipient present, but msg not from me', { data: stanza })
|
||||
}
|
||||
|
||||
@@ -60,21 +73,21 @@ export function decodeMessageNode(
|
||||
|
||||
msgType = 'chat'
|
||||
author = from
|
||||
} else if(isJidGroup(from)) {
|
||||
if(!participant) {
|
||||
} else if (isJidGroup(from)) {
|
||||
if (!participant) {
|
||||
throw new Boom('No participant in group message')
|
||||
}
|
||||
|
||||
msgType = 'group'
|
||||
author = participant
|
||||
chatId = from
|
||||
} else if(isJidBroadcast(from)) {
|
||||
if(!participant) {
|
||||
} else if (isJidBroadcast(from)) {
|
||||
if (!participant) {
|
||||
throw new Boom('No participant in group message')
|
||||
}
|
||||
|
||||
const isParticipantMe = isMe(participant)
|
||||
if(isJidStatusBroadcast(from)) {
|
||||
if (isJidStatusBroadcast(from)) {
|
||||
msgType = isParticipantMe ? 'direct_peer_status' : 'other_status'
|
||||
} else {
|
||||
msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast'
|
||||
@@ -82,7 +95,7 @@ export function decodeMessageNode(
|
||||
|
||||
chatId = from
|
||||
author = participant
|
||||
} else if(isJidNewsletter(from)) {
|
||||
} else if (isJidNewsletter(from)) {
|
||||
msgType = 'newsletter'
|
||||
chatId = from
|
||||
author = from
|
||||
@@ -107,7 +120,7 @@ export function decodeMessageNode(
|
||||
broadcast: isJidBroadcast(from)
|
||||
}
|
||||
|
||||
if(key.fromMe) {
|
||||
if (key.fromMe) {
|
||||
fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK
|
||||
}
|
||||
|
||||
@@ -132,19 +145,19 @@ export const decryptMessageNode = (
|
||||
author,
|
||||
async decrypt() {
|
||||
let decryptables = 0
|
||||
if(Array.isArray(stanza.content)) {
|
||||
for(const { tag, attrs, content } of stanza.content) {
|
||||
if(tag === 'verified_name' && content instanceof Uint8Array) {
|
||||
if (Array.isArray(stanza.content)) {
|
||||
for (const { tag, attrs, content } of stanza.content) {
|
||||
if (tag === 'verified_name' && content instanceof Uint8Array) {
|
||||
const cert = proto.VerifiedNameCertificate.decode(content)
|
||||
const details = proto.VerifiedNameCertificate.Details.decode(cert.details!)
|
||||
fullMessage.verifiedBizName = details.verifiedName
|
||||
}
|
||||
|
||||
if(tag !== 'enc' && tag !== 'plaintext') {
|
||||
if (tag !== 'enc' && tag !== 'plaintext') {
|
||||
continue
|
||||
}
|
||||
|
||||
if(!(content instanceof Uint8Array)) {
|
||||
if (!(content instanceof Uint8Array)) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -178,30 +191,29 @@ export const decryptMessageNode = (
|
||||
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
|
||||
if(msg.senderKeyDistributionMessage) {
|
||||
if (msg.senderKeyDistributionMessage) {
|
||||
//eslint-disable-next-line max-depth
|
||||
try {
|
||||
await repository.processSenderKeyDistributionMessage({
|
||||
authorJid: author,
|
||||
item: msg.senderKeyDistributionMessage
|
||||
})
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
|
||||
}
|
||||
}
|
||||
|
||||
if(fullMessage.message) {
|
||||
if (fullMessage.message) {
|
||||
Object.assign(fullMessage.message, msg)
|
||||
} else {
|
||||
fullMessage.message = msg
|
||||
}
|
||||
} catch(err) {
|
||||
logger.error(
|
||||
{ key: fullMessage.key, err },
|
||||
'failed to decrypt message'
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
|
||||
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
||||
fullMessage.messageStubParameters = [err.message]
|
||||
}
|
||||
@@ -209,7 +221,7 @@ export const decryptMessageNode = (
|
||||
}
|
||||
|
||||
// if nothing was found to decrypt
|
||||
if(!decryptables) {
|
||||
if (!decryptables) {
|
||||
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
||||
fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import EventEmitter from 'events'
|
||||
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 { ILogger } from './logger'
|
||||
import { updateMessageWithReaction, updateMessageWithReceipt } from './messages'
|
||||
@@ -18,10 +28,10 @@ const BUFFERABLE_EVENT = [
|
||||
'messages.delete',
|
||||
'messages.reaction',
|
||||
'message-receipt.update',
|
||||
'groups.update',
|
||||
'groups.update'
|
||||
] 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
|
||||
@@ -36,14 +46,14 @@ const BUFFERABLE_EVENT_SET = new Set<BaileysEvent>(BUFFERABLE_EVENT)
|
||||
|
||||
type BaileysBufferableEventEmitter = BaileysEventEmitter & {
|
||||
/** 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
|
||||
* */
|
||||
buffer(): void
|
||||
/** buffers all events till the promise completes */
|
||||
// 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
|
||||
* @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
|
||||
ev.on('event', (map: BaileysEventData) => {
|
||||
for(const event in map) {
|
||||
for (const event in map) {
|
||||
ev.emit(event, map[event])
|
||||
}
|
||||
})
|
||||
@@ -79,16 +89,16 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
||||
|
||||
function flush(force = false) {
|
||||
// no buffer going on
|
||||
if(!buffersInProgress) {
|
||||
if (!buffersInProgress) {
|
||||
return false
|
||||
}
|
||||
|
||||
if(!force) {
|
||||
if (!force) {
|
||||
// reduce the number of buffers in progress
|
||||
buffersInProgress -= 1
|
||||
// if there are still some buffers going on
|
||||
// then we don't flush now
|
||||
if(buffersInProgress) {
|
||||
if (buffersInProgress) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -97,8 +107,8 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
||||
const chatUpdates = Object.values(data.chatUpdates)
|
||||
// gather the remaining conditional events so we re-queue them
|
||||
let conditionalChatUpdatesLeft = 0
|
||||
for(const update of chatUpdates) {
|
||||
if(update.conditional) {
|
||||
for (const update of chatUpdates) {
|
||||
if (update.conditional) {
|
||||
conditionalChatUpdatesLeft += 1
|
||||
newData.chatUpdates[update.id!] = update
|
||||
delete data.chatUpdates[update.id!]
|
||||
@@ -106,16 +116,13 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
||||
}
|
||||
|
||||
const consolidatedData = consolidateEvents(data)
|
||||
if(Object.keys(consolidatedData).length) {
|
||||
if (Object.keys(consolidatedData).length) {
|
||||
ev.emit('event', consolidatedData)
|
||||
}
|
||||
|
||||
data = newData
|
||||
|
||||
logger.trace(
|
||||
{ conditionalChatUpdatesLeft },
|
||||
'released buffered events'
|
||||
)
|
||||
logger.trace({ conditionalChatUpdatesLeft }, 'released buffered events')
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -132,7 +139,7 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
||||
}
|
||||
},
|
||||
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)
|
||||
return true
|
||||
}
|
||||
@@ -145,7 +152,7 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
||||
buffer,
|
||||
flush,
|
||||
createBufferedFunction(work) {
|
||||
return async(...args) => {
|
||||
return async (...args) => {
|
||||
buffer()
|
||||
try {
|
||||
const result = await work(...args)
|
||||
@@ -157,30 +164,30 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
|
||||
},
|
||||
on: (...args) => ev.on(...args),
|
||||
off: (...args) => ev.off(...args),
|
||||
removeAllListeners: (...args) => ev.removeAllListeners(...args),
|
||||
removeAllListeners: (...args) => ev.removeAllListeners(...args)
|
||||
}
|
||||
}
|
||||
|
||||
const makeBufferData = (): BufferedEventData => {
|
||||
return {
|
||||
historySets: {
|
||||
chats: { },
|
||||
messages: { },
|
||||
contacts: { },
|
||||
chats: {},
|
||||
messages: {},
|
||||
contacts: {},
|
||||
isLatest: false,
|
||||
empty: true
|
||||
},
|
||||
chatUpserts: { },
|
||||
chatUpdates: { },
|
||||
chatUpserts: {},
|
||||
chatUpdates: {},
|
||||
chatDeletes: new Set(),
|
||||
contactUpserts: { },
|
||||
contactUpdates: { },
|
||||
messageUpserts: { },
|
||||
messageUpdates: { },
|
||||
messageReactions: { },
|
||||
messageDeletes: { },
|
||||
messageReceipts: { },
|
||||
groupUpdates: { }
|
||||
contactUpserts: {},
|
||||
contactUpdates: {},
|
||||
messageUpserts: {},
|
||||
messageUpdates: {},
|
||||
messageReactions: {},
|
||||
messageDeletes: {},
|
||||
messageReceipts: {},
|
||||
groupUpdates: {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,13 +201,13 @@ function append<E extends BufferableEvent>(
|
||||
) {
|
||||
switch (event) {
|
||||
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]
|
||||
if(existingChat) {
|
||||
if (existingChat) {
|
||||
existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType
|
||||
}
|
||||
|
||||
if(!existingChat && !historyCache.has(chat.id)) {
|
||||
if (!existingChat && !historyCache.has(chat.id)) {
|
||||
data.historySets.chats[chat.id] = chat
|
||||
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]
|
||||
if(existingContact) {
|
||||
if (existingContact) {
|
||||
Object.assign(existingContact, trimUndefined(contact))
|
||||
} else {
|
||||
const historyContactId = `c:${contact.id}`
|
||||
const hasAnyName = contact.notify || contact.name || contact.verifiedName
|
||||
if(!historyCache.has(historyContactId) || hasAnyName) {
|
||||
if (!historyCache.has(historyContactId) || hasAnyName) {
|
||||
data.historySets.contacts[contact.id] = contact
|
||||
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 existingMsg = data.historySets.messages[key]
|
||||
if(!existingMsg && !historyCache.has(key)) {
|
||||
if (!existingMsg && !historyCache.has(key)) {
|
||||
data.historySets.messages[key] = message
|
||||
historyCache.add(key)
|
||||
}
|
||||
@@ -239,16 +246,16 @@ function append<E extends BufferableEvent>(
|
||||
|
||||
break
|
||||
case 'chats.upsert':
|
||||
for(const chat of eventData as Chat[]) {
|
||||
for (const chat of eventData as Chat[]) {
|
||||
let upsert = data.chatUpserts[chat.id]
|
||||
if(!upsert) {
|
||||
if (!upsert) {
|
||||
upsert = data.historySets[chat.id]
|
||||
if(upsert) {
|
||||
if (upsert) {
|
||||
logger.debug({ chatId: chat.id }, 'absorbed chat upsert in chat set')
|
||||
}
|
||||
}
|
||||
|
||||
if(upsert) {
|
||||
if (upsert) {
|
||||
upsert = concatChats(upsert, chat)
|
||||
} else {
|
||||
upsert = chat
|
||||
@@ -257,29 +264,29 @@ function append<E extends BufferableEvent>(
|
||||
|
||||
absorbingChatUpdate(upsert)
|
||||
|
||||
if(data.chatDeletes.has(chat.id)) {
|
||||
if (data.chatDeletes.has(chat.id)) {
|
||||
data.chatDeletes.delete(chat.id)
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
case 'chats.update':
|
||||
for(const update of eventData as ChatUpdate[]) {
|
||||
for (const update of eventData as ChatUpdate[]) {
|
||||
const chatId = update.id!
|
||||
const conditionMatches = update.conditional ? update.conditional(data) : true
|
||||
if(conditionMatches) {
|
||||
if (conditionMatches) {
|
||||
delete update.conditional
|
||||
|
||||
// if there is an existing upsert, merge the update into it
|
||||
const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId]
|
||||
if(upsert) {
|
||||
if (upsert) {
|
||||
concatChats(upsert, update)
|
||||
} else {
|
||||
// merge the update into the existing update
|
||||
const chatUpdate = data.chatUpdates[chatId] || { }
|
||||
const chatUpdate = data.chatUpdates[chatId] || {}
|
||||
data.chatUpdates[chatId] = concatChats(chatUpdate, update)
|
||||
}
|
||||
} else if(conditionMatches === undefined) {
|
||||
} else if (conditionMatches === undefined) {
|
||||
// condition yet to be fulfilled
|
||||
data.chatUpdates[chatId] = update
|
||||
}
|
||||
@@ -287,52 +294,51 @@ function append<E extends BufferableEvent>(
|
||||
|
||||
// if the chat has been updated
|
||||
// ignore any existing chat delete
|
||||
if(data.chatDeletes.has(chatId)) {
|
||||
if (data.chatDeletes.has(chatId)) {
|
||||
data.chatDeletes.delete(chatId)
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
case 'chats.delete':
|
||||
for(const chatId of eventData as string[]) {
|
||||
if(!data.chatDeletes.has(chatId)) {
|
||||
for (const chatId of eventData as string[]) {
|
||||
if (!data.chatDeletes.has(chatId)) {
|
||||
data.chatDeletes.add(chatId)
|
||||
}
|
||||
|
||||
// remove any prior updates & upserts
|
||||
if(data.chatUpdates[chatId]) {
|
||||
if (data.chatUpdates[chatId]) {
|
||||
delete data.chatUpdates[chatId]
|
||||
}
|
||||
|
||||
if(data.chatUpserts[chatId]) {
|
||||
if (data.chatUpserts[chatId]) {
|
||||
delete data.chatUpserts[chatId]
|
||||
|
||||
}
|
||||
|
||||
if(data.historySets.chats[chatId]) {
|
||||
if (data.historySets.chats[chatId]) {
|
||||
delete data.historySets.chats[chatId]
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
case 'contacts.upsert':
|
||||
for(const contact of eventData as Contact[]) {
|
||||
for (const contact of eventData as Contact[]) {
|
||||
let upsert = data.contactUpserts[contact.id]
|
||||
if(!upsert) {
|
||||
if (!upsert) {
|
||||
upsert = data.historySets.contacts[contact.id]
|
||||
if(upsert) {
|
||||
if (upsert) {
|
||||
logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set')
|
||||
}
|
||||
}
|
||||
|
||||
if(upsert) {
|
||||
if (upsert) {
|
||||
upsert = Object.assign(upsert, trimUndefined(contact))
|
||||
} else {
|
||||
upsert = contact
|
||||
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
|
||||
delete data.contactUpdates[contact.id]
|
||||
}
|
||||
@@ -341,15 +347,15 @@ function append<E extends BufferableEvent>(
|
||||
break
|
||||
case 'contacts.update':
|
||||
const contactUpdates = eventData as BaileysEventMap['contacts.update']
|
||||
for(const update of contactUpdates) {
|
||||
for (const update of contactUpdates) {
|
||||
const id = update.id!
|
||||
// merge into prior upsert
|
||||
const upsert = data.historySets.contacts[id] || data.contactUpserts[id]
|
||||
if(upsert) {
|
||||
if (upsert) {
|
||||
Object.assign(upsert, update)
|
||||
} else {
|
||||
// merge into prior update
|
||||
const contactUpdate = data.contactUpdates[id] || { }
|
||||
const contactUpdate = data.contactUpdates[id] || {}
|
||||
data.contactUpdates[id] = Object.assign(contactUpdate, update)
|
||||
}
|
||||
}
|
||||
@@ -357,34 +363,32 @@ function append<E extends BufferableEvent>(
|
||||
break
|
||||
case '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)
|
||||
let existing = data.messageUpserts[key]?.message
|
||||
if(!existing) {
|
||||
if (!existing) {
|
||||
existing = data.historySets.messages[key]
|
||||
if(existing) {
|
||||
if (existing) {
|
||||
logger.debug({ messageId: key }, 'absorbed message upsert in message set')
|
||||
}
|
||||
}
|
||||
|
||||
if(existing) {
|
||||
if (existing) {
|
||||
message.messageTimestamp = existing.messageTimestamp
|
||||
}
|
||||
|
||||
if(data.messageUpdates[key]) {
|
||||
if (data.messageUpdates[key]) {
|
||||
logger.debug('absorbed prior message update in message upsert')
|
||||
Object.assign(message, data.messageUpdates[key].update)
|
||||
delete data.messageUpdates[key]
|
||||
}
|
||||
|
||||
if(data.historySets.messages[key]) {
|
||||
if (data.historySets.messages[key]) {
|
||||
data.historySets.messages[key] = message
|
||||
} else {
|
||||
data.messageUpserts[key] = {
|
||||
message,
|
||||
type: type === 'notify' || data.messageUpserts[key]?.type === 'notify'
|
||||
? 'notify'
|
||||
: type
|
||||
type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -392,19 +396,19 @@ function append<E extends BufferableEvent>(
|
||||
break
|
||||
case '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 existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message
|
||||
if(existing) {
|
||||
if (existing) {
|
||||
Object.assign(existing, update)
|
||||
// if the message was received & read by us
|
||||
// the chat counter must have been incremented
|
||||
// so we need to decrement it
|
||||
if(update.status === WAMessageStatus.READ && !key.fromMe) {
|
||||
if (update.status === WAMessageStatus.READ && !key.fromMe) {
|
||||
decrementChatReadCounterIfMsgDidUnread(existing)
|
||||
}
|
||||
} else {
|
||||
const msgUpdate = data.messageUpdates[keyStr] || { key, update: { } }
|
||||
const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} }
|
||||
Object.assign(msgUpdate.update, update)
|
||||
data.messageUpdates[keyStr] = msgUpdate
|
||||
}
|
||||
@@ -413,20 +417,19 @@ function append<E extends BufferableEvent>(
|
||||
break
|
||||
case 'messages.delete':
|
||||
const deleteData = eventData as BaileysEventMap['messages.delete']
|
||||
if('keys' in deleteData) {
|
||||
if ('keys' in deleteData) {
|
||||
const { keys } = deleteData
|
||||
for(const key of keys) {
|
||||
for (const key of keys) {
|
||||
const keyStr = stringifyMessageKey(key)
|
||||
if(!data.messageDeletes[keyStr]) {
|
||||
if (!data.messageDeletes[keyStr]) {
|
||||
data.messageDeletes[keyStr] = key
|
||||
|
||||
}
|
||||
|
||||
if(data.messageUpserts[keyStr]) {
|
||||
if (data.messageUpserts[keyStr]) {
|
||||
delete data.messageUpserts[keyStr]
|
||||
}
|
||||
|
||||
if(data.messageUpdates[keyStr]) {
|
||||
if (data.messageUpdates[keyStr]) {
|
||||
delete data.messageUpdates[keyStr]
|
||||
}
|
||||
}
|
||||
@@ -437,14 +440,13 @@ function append<E extends BufferableEvent>(
|
||||
break
|
||||
case '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 existing = data.messageUpserts[keyStr]
|
||||
if(existing) {
|
||||
if (existing) {
|
||||
updateMessageWithReaction(existing.message, reaction)
|
||||
} else {
|
||||
data.messageReactions[keyStr] = data.messageReactions[keyStr]
|
||||
|| { key, reactions: [] }
|
||||
data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] }
|
||||
updateMessageWithReaction(data.messageReactions[keyStr], reaction)
|
||||
}
|
||||
}
|
||||
@@ -452,14 +454,13 @@ function append<E extends BufferableEvent>(
|
||||
break
|
||||
case '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 existing = data.messageUpserts[keyStr]
|
||||
if(existing) {
|
||||
if (existing) {
|
||||
updateMessageWithReceipt(existing.message, receipt)
|
||||
} else {
|
||||
data.messageReceipts[keyStr] = data.messageReceipts[keyStr]
|
||||
|| { key, userReceipt: [] }
|
||||
data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] }
|
||||
updateMessageWithReceipt(data.messageReceipts[keyStr], receipt)
|
||||
}
|
||||
}
|
||||
@@ -467,12 +468,11 @@ function append<E extends BufferableEvent>(
|
||||
break
|
||||
case 'groups.update':
|
||||
const groupUpdates = eventData as BaileysEventMap['groups.update']
|
||||
for(const update of groupUpdates) {
|
||||
for (const update of groupUpdates) {
|
||||
const id = update.id!
|
||||
const groupUpdate = data.groupUpdates[id] || { }
|
||||
if(!data.groupUpdates[id]) {
|
||||
const groupUpdate = data.groupUpdates[id] || {}
|
||||
if (!data.groupUpdates[id]) {
|
||||
data.groupUpdates[id] = Object.assign(groupUpdate, update)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,14 +484,14 @@ function append<E extends BufferableEvent>(
|
||||
function absorbingChatUpdate(existing: Chat) {
|
||||
const chatId = existing.id
|
||||
const update = data.chatUpdates[chatId]
|
||||
if(update) {
|
||||
if (update) {
|
||||
const conditionMatches = update.conditional ? update.conditional(data) : true
|
||||
if(conditionMatches) {
|
||||
if (conditionMatches) {
|
||||
delete update.conditional
|
||||
logger.debug({ chatId }, 'absorbed chat update in existing chat')
|
||||
Object.assign(existing, concatChats(update as Chat, existing))
|
||||
delete data.chatUpdates[chatId]
|
||||
} else if(conditionMatches === false) {
|
||||
} else if (conditionMatches === false) {
|
||||
logger.debug({ chatId }, 'chat update condition fail, removing')
|
||||
delete data.chatUpdates[chatId]
|
||||
}
|
||||
@@ -503,15 +503,15 @@ function append<E extends BufferableEvent>(
|
||||
// if the message has already been marked read by us
|
||||
const chatId = message.key.remoteJid!
|
||||
const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId]
|
||||
if(
|
||||
isRealMessage(message, '')
|
||||
&& shouldIncrementChatUnread(message)
|
||||
&& typeof chat?.unreadCount === 'number'
|
||||
&& chat.unreadCount > 0
|
||||
if (
|
||||
isRealMessage(message, '') &&
|
||||
shouldIncrementChatUnread(message) &&
|
||||
typeof chat?.unreadCount === 'number' &&
|
||||
chat.unreadCount > 0
|
||||
) {
|
||||
logger.debug({ chatId: chat.id }, 'decrementing chat counter')
|
||||
chat.unreadCount -= 1
|
||||
if(chat.unreadCount === 0) {
|
||||
if (chat.unreadCount === 0) {
|
||||
delete chat.unreadCount
|
||||
}
|
||||
}
|
||||
@@ -519,9 +519,9 @@ function append<E extends BufferableEvent>(
|
||||
}
|
||||
|
||||
function consolidateEvents(data: BufferedEventData) {
|
||||
const map: BaileysEventData = { }
|
||||
const map: BaileysEventData = {}
|
||||
|
||||
if(!data.historySets.empty) {
|
||||
if (!data.historySets.empty) {
|
||||
map['messaging-history.set'] = {
|
||||
chats: Object.values(data.historySets.chats),
|
||||
messages: Object.values(data.historySets.messages),
|
||||
@@ -534,22 +534,22 @@ function consolidateEvents(data: BufferedEventData) {
|
||||
}
|
||||
|
||||
const chatUpsertList = Object.values(data.chatUpserts)
|
||||
if(chatUpsertList.length) {
|
||||
if (chatUpsertList.length) {
|
||||
map['chats.upsert'] = chatUpsertList
|
||||
}
|
||||
|
||||
const chatUpdateList = Object.values(data.chatUpdates)
|
||||
if(chatUpdateList.length) {
|
||||
if (chatUpdateList.length) {
|
||||
map['chats.update'] = chatUpdateList
|
||||
}
|
||||
|
||||
const chatDeleteList = Array.from(data.chatDeletes)
|
||||
if(chatDeleteList.length) {
|
||||
if (chatDeleteList.length) {
|
||||
map['chats.delete'] = chatDeleteList
|
||||
}
|
||||
|
||||
const messageUpsertList = Object.values(data.messageUpserts)
|
||||
if(messageUpsertList.length) {
|
||||
if (messageUpsertList.length) {
|
||||
const type = messageUpsertList[0].type
|
||||
map['messages.upsert'] = {
|
||||
messages: messageUpsertList.map(m => m.message),
|
||||
@@ -558,41 +558,41 @@ function consolidateEvents(data: BufferedEventData) {
|
||||
}
|
||||
|
||||
const messageUpdateList = Object.values(data.messageUpdates)
|
||||
if(messageUpdateList.length) {
|
||||
if (messageUpdateList.length) {
|
||||
map['messages.update'] = messageUpdateList
|
||||
}
|
||||
|
||||
const messageDeleteList = Object.values(data.messageDeletes)
|
||||
if(messageDeleteList.length) {
|
||||
if (messageDeleteList.length) {
|
||||
map['messages.delete'] = { keys: messageDeleteList }
|
||||
}
|
||||
|
||||
const messageReactionList = Object.values(data.messageReactions).flatMap(
|
||||
({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction }))
|
||||
const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) =>
|
||||
reactions.flatMap(reaction => ({ key, reaction }))
|
||||
)
|
||||
if(messageReactionList.length) {
|
||||
if (messageReactionList.length) {
|
||||
map['messages.reaction'] = messageReactionList
|
||||
}
|
||||
|
||||
const messageReceiptList = Object.values(data.messageReceipts).flatMap(
|
||||
({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt }))
|
||||
const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) =>
|
||||
userReceipt.flatMap(receipt => ({ key, receipt }))
|
||||
)
|
||||
if(messageReceiptList.length) {
|
||||
if (messageReceiptList.length) {
|
||||
map['message-receipt.update'] = messageReceiptList
|
||||
}
|
||||
|
||||
const contactUpsertList = Object.values(data.contactUpserts)
|
||||
if(contactUpsertList.length) {
|
||||
if (contactUpsertList.length) {
|
||||
map['contacts.upsert'] = contactUpsertList
|
||||
}
|
||||
|
||||
const contactUpdateList = Object.values(data.contactUpdates)
|
||||
if(contactUpdateList.length) {
|
||||
if (contactUpdateList.length) {
|
||||
map['contacts.update'] = contactUpdateList
|
||||
}
|
||||
|
||||
const groupUpdateList = Object.values(data.groupUpdates)
|
||||
if(groupUpdateList.length) {
|
||||
if (groupUpdateList.length) {
|
||||
map['groups.update'] = groupUpdateList
|
||||
}
|
||||
|
||||
@@ -600,15 +600,17 @@ function consolidateEvents(data: BufferedEventData) {
|
||||
}
|
||||
|
||||
function concatChats<C extends Partial<Chat>>(a: C, b: Partial<Chat>) {
|
||||
if(b.unreadCount === null && // neutralize unread counter
|
||||
a.unreadCount! < 0) {
|
||||
if (
|
||||
b.unreadCount === null && // neutralize unread counter
|
||||
a.unreadCount! < 0
|
||||
) {
|
||||
a.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 }
|
||||
if(b.unreadCount! >= 0) {
|
||||
if (b.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 { proto } from '../../WAProto'
|
||||
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'
|
||||
|
||||
const PLATFORM_MAP = {
|
||||
'aix': 'AIX',
|
||||
'darwin': 'Mac OS',
|
||||
'win32': 'Windows',
|
||||
'android': 'Android',
|
||||
'freebsd': 'FreeBSD',
|
||||
'openbsd': 'OpenBSD',
|
||||
'sunos': 'Solaris'
|
||||
aix: 'AIX',
|
||||
darwin: 'Mac OS',
|
||||
win32: 'Windows',
|
||||
android: 'Android',
|
||||
freebsd: 'FreeBSD',
|
||||
openbsd: 'OpenBSD',
|
||||
sunos: 'Solaris'
|
||||
}
|
||||
|
||||
export const Browsers: BrowsersMap = {
|
||||
ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
|
||||
macOS: (browser) => ['Mac OS', browser, '14.4.1'],
|
||||
baileys: (browser) => ['Baileys', browser, '6.5.0'],
|
||||
windows: (browser) => ['Windows', browser, '10.0.22631'],
|
||||
ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
|
||||
macOS: browser => ['Mac OS', browser, '14.4.1'],
|
||||
baileys: browser => ['Baileys', browser, '6.5.0'],
|
||||
windows: browser => ['Windows', browser, '10.0.22631'],
|
||||
/** 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) => {
|
||||
@@ -34,7 +42,7 @@ export const getPlatformId = (browser: string) => {
|
||||
export const BufferJSON = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-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') }
|
||||
}
|
||||
|
||||
@@ -43,7 +51,7 @@ export const BufferJSON = {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-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
|
||||
return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
|
||||
}
|
||||
@@ -52,17 +60,13 @@ export const BufferJSON = {
|
||||
}
|
||||
}
|
||||
|
||||
export const getKeyAuthor = (
|
||||
key: proto.IMessageKey | undefined | null,
|
||||
meId = 'me'
|
||||
) => (
|
||||
export const getKeyAuthor = (key: proto.IMessageKey | undefined | null, meId = 'me') =>
|
||||
(key?.fromMe ? meId : key?.participant || key?.remoteJid) || ''
|
||||
)
|
||||
|
||||
export const writeRandomPadMax16 = (msg: Uint8Array) => {
|
||||
const pad = randomBytes(1)
|
||||
pad[0] &= 0xf
|
||||
if(!pad[0]) {
|
||||
if (!pad[0]) {
|
||||
pad[0] = 0xf
|
||||
}
|
||||
|
||||
@@ -71,23 +75,19 @@ export const writeRandomPadMax16 = (msg: Uint8Array) => {
|
||||
|
||||
export const unpadRandomMax16 = (e: Uint8Array | Buffer) => {
|
||||
const t = new Uint8Array(e)
|
||||
if(0 === t.length) {
|
||||
if (0 === t.length) {
|
||||
throw new Error('unpadPkcs7 given empty bytes')
|
||||
}
|
||||
|
||||
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}`)
|
||||
}
|
||||
|
||||
return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
|
||||
}
|
||||
|
||||
export const encodeWAMessage = (message: proto.IMessage) => (
|
||||
writeRandomPadMax16(
|
||||
proto.Message.encode(message).finish()
|
||||
)
|
||||
)
|
||||
export const encodeWAMessage = (message: proto.IMessage) => writeRandomPadMax16(proto.Message.encode(message).finish())
|
||||
|
||||
export const generateRegistrationId = (): number => {
|
||||
return Uint16Array.from(randomBytes(2))[0] & 16383
|
||||
@@ -96,7 +96,7 @@ export const generateRegistrationId = (): number => {
|
||||
export const encodeBigEndian = (e: number, t = 4) => {
|
||||
let r = e
|
||||
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
|
||||
r >>>= 8
|
||||
}
|
||||
@@ -104,7 +104,8 @@ export const encodeBigEndian = (e: number, t = 4) => {
|
||||
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 */
|
||||
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 = undefined
|
||||
},
|
||||
setTask: (newTask: () => void) => task = newTask,
|
||||
setInterval: (newInterval: number) => intervalMs = newInterval
|
||||
setTask: (newTask: () => void) => (task = newTask),
|
||||
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) => {
|
||||
const stack = new Error().stack
|
||||
@@ -140,7 +141,7 @@ export const delayCancellable = (ms: number) => {
|
||||
reject = _reject
|
||||
})
|
||||
const cancel = () => {
|
||||
clearTimeout (timeout)
|
||||
clearTimeout(timeout)
|
||||
reject(
|
||||
new Boom('Cancelled', {
|
||||
statusCode: 500,
|
||||
@@ -154,29 +155,33 @@ export const delayCancellable = (ms: number) => {
|
||||
return { delay, cancel }
|
||||
}
|
||||
|
||||
export async function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error) => void) => void) {
|
||||
if(!ms) {
|
||||
export async function promiseTimeout<T>(
|
||||
ms: number | undefined,
|
||||
promise: (resolve: (v: T) => void, reject: (error) => void) => void
|
||||
) {
|
||||
if (!ms) {
|
||||
return new Promise(promise)
|
||||
}
|
||||
|
||||
const stack = new Error().stack
|
||||
// Create a promise that rejects in <ms> milliseconds
|
||||
const { delay, cancel } = delayCancellable (ms)
|
||||
const { delay, cancel } = delayCancellable(ms)
|
||||
const p = new Promise((resolve, reject) => {
|
||||
delay
|
||||
.then(() => reject(
|
||||
.then(() =>
|
||||
reject(
|
||||
new Boom('Timed Out', {
|
||||
statusCode: DisconnectReason.timedOut,
|
||||
data: {
|
||||
stack
|
||||
}
|
||||
})
|
||||
))
|
||||
.catch (err => reject(err))
|
||||
)
|
||||
)
|
||||
.catch(err => reject(err))
|
||||
|
||||
promise (resolve, reject)
|
||||
})
|
||||
.finally (cancel)
|
||||
promise(resolve, reject)
|
||||
}).finally(cancel)
|
||||
return p as Promise<T>
|
||||
}
|
||||
|
||||
@@ -186,9 +191,9 @@ export const generateMessageIDV2 = (userId?: string): string => {
|
||||
const data = Buffer.alloc(8 + 20 + 16)
|
||||
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
|
||||
|
||||
if(userId) {
|
||||
if (userId) {
|
||||
const id = jidDecode(userId)
|
||||
if(id?.user) {
|
||||
if (id?.user) {
|
||||
data.write(id.user, 8)
|
||||
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 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 closeListener: (state: Partial<ConnectionState>) => void
|
||||
await (
|
||||
promiseTimeout<void>(
|
||||
timeoutMs,
|
||||
(resolve, reject) => {
|
||||
await promiseTimeout<void>(timeoutMs, (resolve, reject) => {
|
||||
closeListener = ({ connection, lastDisconnect }) => {
|
||||
if(connection === 'close') {
|
||||
if (connection === 'close') {
|
||||
reject(
|
||||
lastDisconnect?.error
|
||||
|| new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
||||
lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
ev.on('connection.update', closeListener)
|
||||
listener = async(update) => {
|
||||
if(await check(update)) {
|
||||
listener = async update => {
|
||||
if (await check(update)) {
|
||||
resolve()
|
||||
}
|
||||
}
|
||||
|
||||
ev.on(event, listener)
|
||||
}
|
||||
)
|
||||
.finally(() => {
|
||||
}).finally(() => {
|
||||
ev.off(event, listener)
|
||||
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.
|
||||
* 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'
|
||||
try {
|
||||
const result = await axios.get<{ version: WAVersion }>(
|
||||
URL,
|
||||
{
|
||||
const result = await axios.get<{ version: WAVersion }>(URL, {
|
||||
...options,
|
||||
responseType: 'json'
|
||||
}
|
||||
)
|
||||
})
|
||||
return {
|
||||
version: result.data.version,
|
||||
isLatest: true
|
||||
}
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
return {
|
||||
version: baileysVersion as WAVersion,
|
||||
isLatest: false,
|
||||
@@ -272,20 +267,17 @@ export const fetchLatestBaileysVersion = async(options: AxiosRequestConfig<{}> =
|
||||
* A utility that fetches the latest web version of whatsapp.
|
||||
* 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 {
|
||||
const { data } = await axios.get(
|
||||
'https://web.whatsapp.com/sw.js',
|
||||
{
|
||||
const { data } = await axios.get('https://web.whatsapp.com/sw.js', {
|
||||
...options,
|
||||
responseType: 'json'
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
const regex = /\\?"client_revision\\?":\s*(\d+)/
|
||||
const match = data.match(regex)
|
||||
|
||||
if(!match?.[1]) {
|
||||
if (!match?.[1]) {
|
||||
return {
|
||||
version: baileysVersion as WAVersion,
|
||||
isLatest: false,
|
||||
@@ -301,7 +293,7 @@ export const fetchLatestWaWebVersion = async(options: AxiosRequestConfig<{}>) =>
|
||||
version: [2, 3000, +clientRevision] as WAVersion,
|
||||
isLatest: true
|
||||
}
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
return {
|
||||
version: baileysVersion as WAVersion,
|
||||
isLatest: false,
|
||||
@@ -317,9 +309,9 @@ export const generateMdTagPrefix = () => {
|
||||
}
|
||||
|
||||
const STATUS_MAP: { [_: string]: proto.WebMessageInfo.Status } = {
|
||||
'sender': proto.WebMessageInfo.Status.SERVER_ACK,
|
||||
'played': proto.WebMessageInfo.Status.PLAYED,
|
||||
'read': proto.WebMessageInfo.Status.READ,
|
||||
sender: proto.WebMessageInfo.Status.SERVER_ACK,
|
||||
played: proto.WebMessageInfo.Status.PLAYED,
|
||||
read: 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) => {
|
||||
const status = STATUS_MAP[type!]
|
||||
if(typeof type === 'undefined') {
|
||||
if (typeof type === 'undefined') {
|
||||
return proto.WebMessageInfo.Status.DELIVERY_ACK
|
||||
}
|
||||
|
||||
@@ -348,7 +340,7 @@ export const getErrorCodeFromStreamError = (node: BinaryNode) => {
|
||||
let reason = reasonNode?.tag || 'unknown'
|
||||
const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession)
|
||||
|
||||
if(statusCode === DisconnectReason.restartRequired) {
|
||||
if (statusCode === DisconnectReason.restartRequired) {
|
||||
reason = 'restart required'
|
||||
}
|
||||
|
||||
@@ -366,7 +358,7 @@ export const getCallStatusFromNode = ({ tag, attrs }: BinaryNode) => {
|
||||
status = 'offer'
|
||||
break
|
||||
case 'terminate':
|
||||
if(attrs.reason === 'timeout') {
|
||||
if (attrs.reason === 'timeout') {
|
||||
status = 'timeout'
|
||||
} else {
|
||||
//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) => {
|
||||
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)
|
||||
if(!Number.isNaN(code) && code >= 400) {
|
||||
if (!Number.isNaN(code) && code >= 400) {
|
||||
statusCode = code
|
||||
}
|
||||
} else if(
|
||||
} else if (
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(error as any)?.code?.startsWith('E')
|
||||
|| error?.message?.includes('timed out')
|
||||
) { // handle ETIMEOUT, ENOTFOUND etc
|
||||
(error as any)?.code?.startsWith('E') ||
|
||||
error?.message?.includes('timed out')
|
||||
) {
|
||||
// handle ETIMEOUT, ENOTFOUND etc
|
||||
statusCode = 408
|
||||
}
|
||||
|
||||
@@ -417,9 +410,9 @@ export const isWABusinessPlatform = (platform: string) => {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function trimUndefined(obj: {[_: string]: any}) {
|
||||
for(const key in obj) {
|
||||
if(typeof obj[key] === 'undefined') {
|
||||
export function trimUndefined(obj: { [_: string]: any }) {
|
||||
for (const key in obj) {
|
||||
if (typeof obj[key] === 'undefined') {
|
||||
delete obj[key]
|
||||
}
|
||||
}
|
||||
@@ -434,17 +427,17 @@ export function bytesToCrockford(buffer: Buffer): string {
|
||||
let bitCount = 0
|
||||
const crockford: string[] = []
|
||||
|
||||
for(const element of buffer) {
|
||||
for (const element of buffer) {
|
||||
value = (value << 8) | (element & 0xff)
|
||||
bitCount += 8
|
||||
|
||||
while(bitCount >= 5) {
|
||||
while (bitCount >= 5) {
|
||||
crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
|
||||
bitCount -= 5
|
||||
}
|
||||
}
|
||||
|
||||
if(bitCount > 0) {
|
||||
if (bitCount > 0) {
|
||||
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
|
||||
}
|
||||
|
||||
|
||||
@@ -10,10 +10,7 @@ import { downloadContentFromMessage } from './messages-media'
|
||||
|
||||
const inflatePromise = promisify(inflate)
|
||||
|
||||
export const downloadHistory = async(
|
||||
msg: proto.Message.IHistorySyncNotification,
|
||||
options: AxiosRequestConfig<{}>
|
||||
) => {
|
||||
export const downloadHistory = async (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => {
|
||||
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
||||
const bufferArray: Buffer[] = []
|
||||
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.FULL:
|
||||
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 })
|
||||
|
||||
const msgs = chat.messages || []
|
||||
@@ -48,33 +45,32 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
|
||||
delete chat.muteEndTime
|
||||
delete chat.pinned
|
||||
|
||||
for(const item of msgs) {
|
||||
for (const item of msgs) {
|
||||
const message = item.message!
|
||||
messages.push(message)
|
||||
|
||||
if(!chat.messages?.length) {
|
||||
if (!chat.messages?.length) {
|
||||
// keep only the most recent message in the chat array
|
||||
chat.messages = [{ message }]
|
||||
}
|
||||
|
||||
if(!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
||||
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
||||
chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
|
||||
}
|
||||
|
||||
if(
|
||||
(message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
|
||||
|| message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB
|
||||
)
|
||||
&& message.messageStubParameters?.[0]
|
||||
if (
|
||||
(message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
|
||||
message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
|
||||
message.messageStubParameters?.[0]
|
||||
) {
|
||||
contacts.push({
|
||||
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
|
||||
}
|
||||
|
||||
@@ -83,7 +79,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
|
||||
|
||||
break
|
||||
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! })
|
||||
}
|
||||
|
||||
@@ -99,7 +95,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
|
||||
}
|
||||
}
|
||||
|
||||
export const downloadAndProcessHistorySyncNotification = async(
|
||||
export const downloadAndProcessHistorySyncNotification = async (
|
||||
msg: proto.Message.IHistorySyncNotification,
|
||||
options: AxiosRequestConfig<{}>
|
||||
) => {
|
||||
|
||||
@@ -7,10 +7,7 @@ import { extractImageThumb, getHttpStream } from './messages-media'
|
||||
const THUMBNAIL_WIDTH_PX = 192
|
||||
|
||||
/** Fetches an image and generates a thumbnail for it */
|
||||
const getCompressedJpegThumbnail = async(
|
||||
url: string,
|
||||
{ thumbnailWidth, fetchOpts }: URLGenerationOptions
|
||||
) => {
|
||||
const getCompressedJpegThumbnail = async (url: string, { thumbnailWidth, fetchOpts }: URLGenerationOptions) => {
|
||||
const stream = await getHttpStream(url, fetchOpts)
|
||||
const result = await extractImageThumb(stream, thumbnailWidth)
|
||||
return result
|
||||
@@ -34,12 +31,12 @@ export type URLGenerationOptions = {
|
||||
* @param text first matched URL in text
|
||||
* @returns the URL info required to generate link preview
|
||||
*/
|
||||
export const getUrlInfo = async(
|
||||
export const getUrlInfo = async (
|
||||
text: string,
|
||||
opts: URLGenerationOptions = {
|
||||
thumbnailWidth: THUMBNAIL_WIDTH_PX,
|
||||
fetchOpts: { timeout: 3000 }
|
||||
},
|
||||
}
|
||||
): Promise<WAUrlInfo | undefined> => {
|
||||
try {
|
||||
// retries
|
||||
@@ -48,7 +45,7 @@ export const getUrlInfo = async(
|
||||
|
||||
const { getLinkPreview } = await import('link-preview-js')
|
||||
let previewLink = text
|
||||
if(!text.startsWith('https://') && !text.startsWith('http://')) {
|
||||
if (!text.startsWith('https://') && !text.startsWith('http://')) {
|
||||
previewLink = 'https://' + previewLink
|
||||
}
|
||||
|
||||
@@ -58,14 +55,14 @@ export const getUrlInfo = async(
|
||||
handleRedirects: (baseURL: string, forwardedURL: string) => {
|
||||
const urlObj = new URL(baseURL)
|
||||
const forwardedURLObj = new URL(forwardedURL)
|
||||
if(retries >= maxRetry) {
|
||||
if (retries >= maxRetry) {
|
||||
return false
|
||||
}
|
||||
|
||||
if(
|
||||
forwardedURLObj.hostname === urlObj.hostname
|
||||
|| forwardedURLObj.hostname === 'www.' + urlObj.hostname
|
||||
|| 'www.' + forwardedURLObj.hostname === urlObj.hostname
|
||||
if (
|
||||
forwardedURLObj.hostname === urlObj.hostname ||
|
||||
forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
|
||||
'www.' + forwardedURLObj.hostname === urlObj.hostname
|
||||
) {
|
||||
retries + 1
|
||||
return true
|
||||
@@ -75,7 +72,7 @@ export const getUrlInfo = async(
|
||||
},
|
||||
headers: opts.fetchOpts as {}
|
||||
})
|
||||
if(info && 'title' in info && info.title) {
|
||||
if (info && 'title' in info && info.title) {
|
||||
const [image] = info.images
|
||||
|
||||
const urlInfo: WAUrlInfo = {
|
||||
@@ -86,7 +83,7 @@ export const getUrlInfo = async(
|
||||
originalThumbnailUrl: image
|
||||
}
|
||||
|
||||
if(opts.uploadImage) {
|
||||
if (opts.uploadImage) {
|
||||
const { imageMessage } = await prepareWAMessageMedia(
|
||||
{ image: { url: image } },
|
||||
{
|
||||
@@ -95,27 +92,20 @@ export const getUrlInfo = async(
|
||||
options: opts.fetchOpts
|
||||
}
|
||||
)
|
||||
urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail
|
||||
? Buffer.from(imageMessage.jpegThumbnail)
|
||||
: undefined
|
||||
urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined
|
||||
urlInfo.highQualityThumbnail = imageMessage || undefined
|
||||
} else {
|
||||
try {
|
||||
urlInfo.jpegThumbnail = image
|
||||
? (await getCompressedJpegThumbnail(image, opts)).buffer
|
||||
: undefined
|
||||
} catch(error) {
|
||||
opts.logger?.debug(
|
||||
{ err: error.stack, url: previewLink },
|
||||
'error in generating thumbnail'
|
||||
)
|
||||
urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined
|
||||
} catch (error) {
|
||||
opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail')
|
||||
}
|
||||
}
|
||||
|
||||
return urlInfo
|
||||
}
|
||||
} catch(error) {
|
||||
if(!error.message.includes('receive a valid')) {
|
||||
} catch (error) {
|
||||
if (!error.message.includes('receive a valid')) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import { hkdf } from './crypto'
|
||||
const o = 128
|
||||
|
||||
class d {
|
||||
|
||||
salt: string
|
||||
|
||||
constructor(e: string) {
|
||||
@@ -17,7 +16,7 @@ class d {
|
||||
}
|
||||
add(e, t) {
|
||||
var r = this
|
||||
for(const item of t) {
|
||||
for (const item of t) {
|
||||
e = r._addSingle(e, item)
|
||||
}
|
||||
|
||||
@@ -25,7 +24,7 @@ class d {
|
||||
}
|
||||
subtract(e, t) {
|
||||
var r = this
|
||||
for(const item of t) {
|
||||
for (const item of t) {
|
||||
e = r._subtractSingle(e, item)
|
||||
}
|
||||
|
||||
@@ -38,20 +37,20 @@ class d {
|
||||
async _addSingle(e, t) {
|
||||
var r = this
|
||||
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) {
|
||||
var r = this
|
||||
|
||||
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) {
|
||||
const n = new DataView(e)
|
||||
, i = new DataView(t)
|
||||
, a = new ArrayBuffer(n.byteLength)
|
||||
, s = new DataView(a)
|
||||
for(let e = 0; e < n.byteLength; e += 2) {
|
||||
const n = new DataView(e),
|
||||
i = new DataView(t),
|
||||
a = new ArrayBuffer(n.byteLength),
|
||||
s = new DataView(a)
|
||||
for (let e = 0; e < n.byteLength; e += 2) {
|
||||
s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,12 +6,12 @@ export const makeMutex = () => {
|
||||
|
||||
return {
|
||||
mutex<T>(code: () => Promise<T> | T): Promise<T> {
|
||||
task = (async() => {
|
||||
task = (async () => {
|
||||
// wait for the previous task to complete
|
||||
// if there is an error, we swallow so as to not block the queue
|
||||
try {
|
||||
await task
|
||||
} catch{ }
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
// execute the current task
|
||||
@@ -24,7 +24,7 @@ export const makeMutex = () => {
|
||||
// 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
|
||||
return task
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ export const makeKeyedMutex = () => {
|
||||
|
||||
return {
|
||||
mutex<T>(key: string, task: () => Promise<T> | T): Promise<T> {
|
||||
if(!map[key]) {
|
||||
if (!map[key]) {
|
||||
map[key] = makeMutex()
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,19 @@ import { Readable, Transform } from 'stream'
|
||||
import { URL } from 'url'
|
||||
import { proto } from '../../WAProto'
|
||||
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults'
|
||||
import { BaileysEventMap, DownloadableMessage, MediaConnInfo, MediaDecryptionKeyInfo, MediaType, MessageType, SocketConfig, WAGenericMediaMessage, WAMediaUpload, WAMediaUploadFunction, WAMessageContent } from '../Types'
|
||||
import {
|
||||
BaileysEventMap,
|
||||
DownloadableMessage,
|
||||
MediaConnInfo,
|
||||
MediaDecryptionKeyInfo,
|
||||
MediaType,
|
||||
MessageType,
|
||||
SocketConfig,
|
||||
WAGenericMediaMessage,
|
||||
WAMediaUpload,
|
||||
WAMediaUploadFunction,
|
||||
WAMessageContent
|
||||
} from '../Types'
|
||||
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
|
||||
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
|
||||
import { generateMessageIDV2 } from './generics'
|
||||
@@ -19,30 +31,24 @@ import { ILogger } from './logger'
|
||||
|
||||
const getTmpFilesDirectory = () => tmpdir()
|
||||
|
||||
const getImageProcessingLibrary = async() => {
|
||||
const getImageProcessingLibrary = async () => {
|
||||
const [_jimp, sharp] = await Promise.all([
|
||||
(async() => {
|
||||
const jimp = await (
|
||||
import('jimp')
|
||||
.catch(() => { })
|
||||
)
|
||||
(async () => {
|
||||
const jimp = await import('jimp').catch(() => {})
|
||||
return jimp
|
||||
})(),
|
||||
(async() => {
|
||||
const sharp = await (
|
||||
import('sharp')
|
||||
.catch(() => { })
|
||||
)
|
||||
(async () => {
|
||||
const sharp = await import('sharp').catch(() => {})
|
||||
return sharp
|
||||
})()
|
||||
])
|
||||
|
||||
if(sharp) {
|
||||
if (sharp) {
|
||||
return { sharp }
|
||||
}
|
||||
|
||||
const jimp = _jimp?.default || _jimp
|
||||
if(jimp) {
|
||||
if (jimp) {
|
||||
return { jimp }
|
||||
}
|
||||
|
||||
@@ -55,12 +61,15 @@ export const hkdfInfoKey = (type: MediaType) => {
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
if(!buffer) {
|
||||
export async function getMediaKeys(
|
||||
buffer: Uint8Array | string | null | undefined,
|
||||
mediaType: MediaType
|
||||
): Promise<MediaDecryptionKeyInfo> {
|
||||
if (!buffer) {
|
||||
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')
|
||||
}
|
||||
|
||||
@@ -69,49 +78,47 @@ export async function getMediaKeys(buffer: Uint8Array | string | null | undefine
|
||||
return {
|
||||
iv: expandedMediaKey.slice(0, 16),
|
||||
cipherKey: expandedMediaKey.slice(16, 48),
|
||||
macKey: expandedMediaKey.slice(48, 80),
|
||||
macKey: expandedMediaKey.slice(48, 80)
|
||||
}
|
||||
}
|
||||
|
||||
/** Extracts video thumb using FFMPEG */
|
||||
const extractVideoThumb = async(
|
||||
const extractVideoThumb = async (
|
||||
path: string,
|
||||
destPath: string,
|
||||
time: string,
|
||||
size: { width: number, height: number },
|
||||
) => new Promise<void>((resolve, reject) => {
|
||||
size: { width: number; height: number }
|
||||
) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`
|
||||
exec(cmd, (err) => {
|
||||
if(err) {
|
||||
exec(cmd, err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | string, width = 32) => {
|
||||
if(bufferOrFilePath instanceof Readable) {
|
||||
export const extractImageThumb = async (bufferOrFilePath: Readable | Buffer | string, width = 32) => {
|
||||
if (bufferOrFilePath instanceof Readable) {
|
||||
bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
||||
}
|
||||
|
||||
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 dimensions = await img.metadata()
|
||||
|
||||
const buffer = await img
|
||||
.resize(width)
|
||||
.jpeg({ quality: 50 })
|
||||
.toBuffer()
|
||||
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer()
|
||||
return {
|
||||
buffer,
|
||||
original: {
|
||||
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 jimp = await read(bufferOrFilePath as string)
|
||||
@@ -119,10 +126,7 @@ export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | str
|
||||
width: jimp.getWidth(),
|
||||
height: jimp.getHeight()
|
||||
}
|
||||
const buffer = await jimp
|
||||
.quality(50)
|
||||
.resize(width, AUTO, RESIZE_BILINEAR)
|
||||
.getBufferAsync(MIME_JPEG)
|
||||
const buffer = await jimp.quality(50).resize(width, AUTO, RESIZE_BILINEAR).getBufferAsync(MIME_JPEG)
|
||||
return {
|
||||
buffer,
|
||||
original: dimensions
|
||||
@@ -132,20 +136,14 @@ export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | str
|
||||
}
|
||||
}
|
||||
|
||||
export const encodeBase64EncodedStringForUpload = (b64: string) => (
|
||||
encodeURIComponent(
|
||||
b64
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/\=+$/, '')
|
||||
)
|
||||
)
|
||||
export const encodeBase64EncodedStringForUpload = (b64: string) =>
|
||||
encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''))
|
||||
|
||||
export const generateProfilePicture = async(mediaUpload: WAMediaUpload) => {
|
||||
export const generateProfilePicture = async (mediaUpload: WAMediaUpload) => {
|
||||
let bufferOrFilePath: Buffer | string
|
||||
if(Buffer.isBuffer(mediaUpload)) {
|
||||
if (Buffer.isBuffer(mediaUpload)) {
|
||||
bufferOrFilePath = mediaUpload
|
||||
} else if('url' in mediaUpload) {
|
||||
} else if ('url' in mediaUpload) {
|
||||
bufferOrFilePath = mediaUpload.url.toString()
|
||||
} else {
|
||||
bufferOrFilePath = await toBuffer(mediaUpload.stream)
|
||||
@@ -153,44 +151,42 @@ export const generateProfilePicture = async(mediaUpload: WAMediaUpload) => {
|
||||
|
||||
const lib = await getImageProcessingLibrary()
|
||||
let img: Promise<Buffer>
|
||||
if('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
||||
img = lib.sharp.default(bufferOrFilePath)
|
||||
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
||||
img = lib.sharp
|
||||
.default(bufferOrFilePath)
|
||||
.resize(640, 640)
|
||||
.jpeg({
|
||||
quality: 50,
|
||||
quality: 50
|
||||
})
|
||||
.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 jimp = await read(bufferOrFilePath as string)
|
||||
const min = Math.min(jimp.getWidth(), jimp.getHeight())
|
||||
const cropped = jimp.crop(0, 0, min, min)
|
||||
|
||||
img = cropped
|
||||
.quality(50)
|
||||
.resize(640, 640, RESIZE_BILINEAR)
|
||||
.getBufferAsync(MIME_JPEG)
|
||||
img = cropped.quality(50).resize(640, 640, RESIZE_BILINEAR).getBufferAsync(MIME_JPEG)
|
||||
} else {
|
||||
throw new Boom('No image processing library available')
|
||||
}
|
||||
|
||||
return {
|
||||
img: await img,
|
||||
img: await img
|
||||
}
|
||||
}
|
||||
|
||||
/** gets the SHA256 of the given media message */
|
||||
export const mediaMessageSHA256B64 = (message: WAMessageContent) => {
|
||||
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) {
|
||||
const musicMetadata = await import('music-metadata')
|
||||
let metadata: IAudioMetadata
|
||||
if(Buffer.isBuffer(buffer)) {
|
||||
if (Buffer.isBuffer(buffer)) {
|
||||
metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true })
|
||||
} else if(typeof buffer === 'string') {
|
||||
} else if (typeof buffer === 'string') {
|
||||
const rStream = createReadStream(buffer)
|
||||
try {
|
||||
metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true })
|
||||
@@ -209,11 +205,11 @@ export async function getAudioDuration(buffer: Buffer | string | Readable) {
|
||||
*/
|
||||
export async function getAudioWaveform(buffer: Buffer | string | Readable, logger?: ILogger) {
|
||||
try {
|
||||
const { default: decoder } = await eval('import(\'audio-decode\')')
|
||||
const { default: decoder } = await eval("import('audio-decode')")
|
||||
let audioData: Buffer
|
||||
if(Buffer.isBuffer(buffer)) {
|
||||
if (Buffer.isBuffer(buffer)) {
|
||||
audioData = buffer
|
||||
} else if(typeof buffer === 'string') {
|
||||
} else if (typeof buffer === 'string') {
|
||||
const rStream = createReadStream(buffer)
|
||||
audioData = await toBuffer(rStream)
|
||||
} else {
|
||||
@@ -226,10 +222,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 blockSize = Math.floor(rawData.length / samples) // the number of samples in each subdivision
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
@@ -238,20 +234,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.
|
||||
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
|
||||
const waveform = new Uint8Array(
|
||||
normalizedData.map((n) => Math.floor(100 * n))
|
||||
)
|
||||
const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)))
|
||||
|
||||
return waveform
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
logger?.debug('Failed to generate waveform: ' + e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export const toReadable = (buffer: Buffer) => {
|
||||
const readable = new Readable({ read: () => {} })
|
||||
readable.push(buffer)
|
||||
@@ -259,7 +252,7 @@ export const toReadable = (buffer: Buffer) => {
|
||||
return readable
|
||||
}
|
||||
|
||||
export const toBuffer = async(stream: Readable) => {
|
||||
export const toBuffer = async (stream: Readable) => {
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(chunk)
|
||||
@@ -269,16 +262,16 @@ export const toBuffer = async(stream: Readable) => {
|
||||
return Buffer.concat(chunks)
|
||||
}
|
||||
|
||||
export const getStream = async(item: WAMediaUpload, opts?: AxiosRequestConfig) => {
|
||||
if(Buffer.isBuffer(item)) {
|
||||
export const getStream = async (item: WAMediaUpload, opts?: AxiosRequestConfig) => {
|
||||
if (Buffer.isBuffer(item)) {
|
||||
return { stream: toReadable(item), type: 'buffer' } as const
|
||||
}
|
||||
|
||||
if('stream' in item) {
|
||||
if ('stream' in item) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -294,17 +287,17 @@ export async function generateThumbnail(
|
||||
}
|
||||
) {
|
||||
let thumbnail: string | undefined
|
||||
let originalImageDimensions: { width: number, height: number } | undefined
|
||||
if(mediaType === 'image') {
|
||||
let originalImageDimensions: { width: number; height: number } | undefined
|
||||
if (mediaType === 'image') {
|
||||
const { buffer, original } = await extractImageThumb(file)
|
||||
thumbnail = buffer.toString('base64')
|
||||
if(original.width && original.height) {
|
||||
if (original.width && original.height) {
|
||||
originalImageDimensions = {
|
||||
width: original.width,
|
||||
height: original.height,
|
||||
height: original.height
|
||||
}
|
||||
}
|
||||
} else if(mediaType === 'video') {
|
||||
} else if (mediaType === 'video') {
|
||||
const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg')
|
||||
try {
|
||||
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 })
|
||||
@@ -312,7 +305,7 @@ export async function generateThumbnail(
|
||||
thumbnail = buff.toString('base64')
|
||||
|
||||
await fs.unlink(imgFilename)
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
options.logger?.debug('could not generate video thumb: ' + err)
|
||||
}
|
||||
}
|
||||
@@ -323,7 +316,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' })
|
||||
return fetched.data as Readable
|
||||
}
|
||||
@@ -334,7 +327,7 @@ type EncryptedStreamOptions = {
|
||||
opts?: AxiosRequestConfig
|
||||
}
|
||||
|
||||
export const encryptedStream = async(
|
||||
export const encryptedStream = async (
|
||||
media: WAMediaUpload,
|
||||
mediaType: MediaType,
|
||||
{ logger, saveOriginalFileIfRequired, opts }: EncryptedStreamOptions = {}
|
||||
@@ -346,20 +339,14 @@ export const encryptedStream = async(
|
||||
const mediaKey = Crypto.randomBytes(32)
|
||||
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
|
||||
|
||||
const encFilePath = join(
|
||||
getTmpFilesDirectory(),
|
||||
mediaType + generateMessageIDV2() + '-enc'
|
||||
)
|
||||
const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc')
|
||||
const encFileWriteStream = createWriteStream(encFilePath)
|
||||
|
||||
let originalFileStream: WriteStream | undefined
|
||||
let originalFilePath: string | undefined
|
||||
|
||||
if(saveOriginalFileIfRequired) {
|
||||
originalFilePath = join(
|
||||
getTmpFilesDirectory(),
|
||||
mediaType + generateMessageIDV2() + '-original'
|
||||
)
|
||||
if (saveOriginalFileIfRequired) {
|
||||
originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original')
|
||||
originalFileStream = createWriteStream(originalFilePath)
|
||||
}
|
||||
|
||||
@@ -379,21 +366,14 @@ export const encryptedStream = async(
|
||||
for await (const data of stream) {
|
||||
fileLength += data.length
|
||||
|
||||
if(
|
||||
type === 'remote'
|
||||
&& opts?.maxContentLength
|
||||
&& fileLength + data.length > opts.maxContentLength
|
||||
) {
|
||||
throw new Boom(
|
||||
`content length exceeded when encrypting "${type}"`,
|
||||
{
|
||||
if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
|
||||
throw new Boom(`content length exceeded when encrypting "${type}"`, {
|
||||
data: { media, type }
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if(originalFileStream) {
|
||||
if(!originalFileStream.write(data)) {
|
||||
if (originalFileStream) {
|
||||
if (!originalFileStream.write(data)) {
|
||||
await once(originalFileStream, 'drain')
|
||||
}
|
||||
}
|
||||
@@ -427,7 +407,7 @@ export const encryptedStream = async(
|
||||
fileSha256,
|
||||
fileLength
|
||||
}
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
// destroy all streams with error
|
||||
encFileWriteStream.destroy()
|
||||
originalFileStream?.destroy?.()
|
||||
@@ -437,13 +417,12 @@ export const encryptedStream = async(
|
||||
sha256Enc.destroy()
|
||||
stream.destroy()
|
||||
|
||||
|
||||
try {
|
||||
await fs.unlink(encFilePath)
|
||||
if(originalFilePath) {
|
||||
if (originalFilePath) {
|
||||
await fs.unlink(originalFilePath)
|
||||
}
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
logger?.error({ err }, 'failed deleting tmp files')
|
||||
}
|
||||
|
||||
@@ -466,10 +445,10 @@ export type MediaDownloadOptions = {
|
||||
|
||||
export const getUrlFromDirectPath = (directPath: string) => `https://${DEF_HOST}${directPath}`
|
||||
|
||||
export const downloadContentFromMessage = async(
|
||||
export const downloadContentFromMessage = async (
|
||||
{ mediaKey, directPath, url }: DownloadableMessage,
|
||||
type: MediaType,
|
||||
opts: MediaDownloadOptions = { }
|
||||
opts: MediaDownloadOptions = {}
|
||||
) => {
|
||||
const downloadUrl = url || getUrlFromDirectPath(directPath!)
|
||||
const keys = await getMediaKeys(mediaKey, type)
|
||||
@@ -481,18 +460,18 @@ export const downloadContentFromMessage = async(
|
||||
* 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
|
||||
* */
|
||||
export const downloadEncryptedContent = async(
|
||||
export const downloadEncryptedContent = async (
|
||||
downloadUrl: string,
|
||||
{ cipherKey, iv }: MediaDecryptionKeyInfo,
|
||||
{ startByte, endByte, options }: MediaDownloadOptions = { }
|
||||
{ startByte, endByte, options }: MediaDownloadOptions = {}
|
||||
) => {
|
||||
let bytesFetched = 0
|
||||
let startChunk = 0
|
||||
let firstBlockIsIV = false
|
||||
// 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)
|
||||
if(chunk) {
|
||||
if (chunk) {
|
||||
startChunk = chunk - AES_CHUNK_SIZE
|
||||
bytesFetched = chunk
|
||||
|
||||
@@ -503,33 +482,30 @@ export const downloadEncryptedContent = async(
|
||||
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
||||
|
||||
const headers: AxiosRequestConfig['headers'] = {
|
||||
...options?.headers || { },
|
||||
Origin: DEFAULT_ORIGIN,
|
||||
...(options?.headers || {}),
|
||||
Origin: DEFAULT_ORIGIN
|
||||
}
|
||||
if(startChunk || endChunk) {
|
||||
if (startChunk || endChunk) {
|
||||
headers.Range = `bytes=${startChunk}-`
|
||||
if(endChunk) {
|
||||
if (endChunk) {
|
||||
headers.Range += endChunk
|
||||
}
|
||||
}
|
||||
|
||||
// download the message
|
||||
const fetched = await getHttpStream(
|
||||
downloadUrl,
|
||||
{
|
||||
...options || { },
|
||||
const fetched = await getHttpStream(downloadUrl, {
|
||||
...(options || {}),
|
||||
headers,
|
||||
maxBodyLength: Infinity,
|
||||
maxContentLength: Infinity,
|
||||
}
|
||||
)
|
||||
maxContentLength: Infinity
|
||||
})
|
||||
|
||||
let remainingBytes = Buffer.from([])
|
||||
|
||||
let aes: Crypto.Decipher
|
||||
|
||||
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 end = bytesFetched + bytes.length < endByte! ? undefined : Math.max(endByte! - bytesFetched, 0)
|
||||
|
||||
@@ -549,9 +525,9 @@ export const downloadEncryptedContent = async(
|
||||
remainingBytes = data.slice(decryptLength)
|
||||
data = data.slice(0, decryptLength)
|
||||
|
||||
if(!aes) {
|
||||
if (!aes) {
|
||||
let ivValue = iv
|
||||
if(firstBlockIsIV) {
|
||||
if (firstBlockIsIV) {
|
||||
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
||||
data = data.slice(AES_CHUNK_SIZE)
|
||||
}
|
||||
@@ -559,16 +535,15 @@ export const downloadEncryptedContent = async(
|
||||
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
||||
// if an end byte that is not EOF is specified
|
||||
// stop auto padding (PKCS7) -- otherwise throws an error for decryption
|
||||
if(endByte) {
|
||||
if (endByte) {
|
||||
aes.setAutoPadding(false)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
pushBytes(aes.update(data), b => this.push(b))
|
||||
callback()
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
callback(error)
|
||||
}
|
||||
},
|
||||
@@ -576,10 +551,10 @@ export const downloadEncryptedContent = async(
|
||||
try {
|
||||
pushBytes(aes.final(), b => this.push(b))
|
||||
callback()
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
callback(error)
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
return fetched.pipe(output, { end: true })
|
||||
}
|
||||
@@ -588,11 +563,7 @@ export function extensionForMediaMessage(message: WAMessageContent) {
|
||||
const getExtension = (mimetype: string) => mimetype.split(';')[0].split('/')[1]
|
||||
const type = Object.keys(message)[0] as MessageType
|
||||
let extension: string
|
||||
if(
|
||||
type === 'locationMessage' ||
|
||||
type === 'liveLocationMessage' ||
|
||||
type === 'productMessage'
|
||||
) {
|
||||
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
|
||||
extension = '.jpeg'
|
||||
} else {
|
||||
const messageContent = message[type] as WAGenericMediaMessage
|
||||
@@ -604,18 +575,18 @@ export function extensionForMediaMessage(message: WAMessageContent) {
|
||||
|
||||
export const getWAUploadToServer = (
|
||||
{ customUploadHosts, fetchAgent, logger, options }: SocketConfig,
|
||||
refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>,
|
||||
refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>
|
||||
): WAMediaUploadFunction => {
|
||||
return async(filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
||||
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
||||
// send a query JSON to obtain the url & auth token to upload our media
|
||||
let uploadInfo = await refreshMediaConn(false)
|
||||
|
||||
let urls: { mediaUrl: string, directPath: string } | undefined
|
||||
const hosts = [ ...customUploadHosts, ...uploadInfo.hosts ]
|
||||
let urls: { mediaUrl: string; directPath: string } | undefined
|
||||
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
||||
|
||||
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
||||
|
||||
for(const { hostname } of hosts) {
|
||||
for (const { hostname } of hosts) {
|
||||
logger.debug(`uploading to "${hostname}"`)
|
||||
|
||||
const auth = encodeURIComponent(uploadInfo.auth) // the auth token
|
||||
@@ -623,28 +594,23 @@ export const getWAUploadToServer = (
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let result: any
|
||||
try {
|
||||
|
||||
const body = await axios.post(
|
||||
url,
|
||||
createReadStream(filePath),
|
||||
{
|
||||
const body = await axios.post(url, createReadStream(filePath), {
|
||||
...options,
|
||||
maxRedirects: 0,
|
||||
headers: {
|
||||
...options.headers || { },
|
||||
...(options.headers || {}),
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Origin': DEFAULT_ORIGIN
|
||||
Origin: DEFAULT_ORIGIN
|
||||
},
|
||||
httpsAgent: fetchAgent,
|
||||
timeout: timeoutMs,
|
||||
responseType: 'json',
|
||||
maxBodyLength: Infinity,
|
||||
maxContentLength: Infinity,
|
||||
}
|
||||
)
|
||||
maxContentLength: Infinity
|
||||
})
|
||||
result = body.data
|
||||
|
||||
if(result?.url || result?.directPath) {
|
||||
if (result?.url || result?.directPath) {
|
||||
urls = {
|
||||
mediaUrl: result.url,
|
||||
directPath: result.direct_path
|
||||
@@ -654,21 +620,21 @@ export const getWAUploadToServer = (
|
||||
uploadInfo = await refreshMediaConn(true)
|
||||
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
||||
}
|
||||
} catch(error) {
|
||||
if(axios.isAxiosError(error)) {
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error)) {
|
||||
result = error.response?.data
|
||||
}
|
||||
|
||||
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) {
|
||||
throw new Boom(
|
||||
'Media upload failed on all hosts',
|
||||
{ statusCode: 500 }
|
||||
)
|
||||
if (!urls) {
|
||||
throw new Boom('Media upload failed on all hosts', { statusCode: 500 })
|
||||
}
|
||||
|
||||
return urls
|
||||
@@ -682,11 +648,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
|
||||
*/
|
||||
export const encryptMediaRetryRequest = async(
|
||||
key: proto.IMessageKey,
|
||||
mediaKey: Buffer | Uint8Array,
|
||||
meId: string
|
||||
) => {
|
||||
export const encryptMediaRetryRequest = async (key: proto.IMessageKey, mediaKey: Buffer | Uint8Array, meId: string) => {
|
||||
const recp: proto.IServerErrorReceipt = { stanzaId: key.id }
|
||||
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
|
||||
|
||||
@@ -707,17 +669,17 @@ export const encryptMediaRetryRequest = async(
|
||||
// keeping it here to maintain parity with WA Web
|
||||
{
|
||||
tag: 'encrypt',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{ tag: 'enc_p', attrs: { }, content: ciphertext },
|
||||
{ tag: 'enc_iv', attrs: { }, content: iv }
|
||||
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
||||
{ tag: 'enc_iv', attrs: {}, content: iv }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'rmr',
|
||||
attrs: {
|
||||
jid: key.remoteJid!,
|
||||
'from_me': (!!key.fromMe).toString(),
|
||||
from_me: (!!key.fromMe).toString(),
|
||||
// @ts-ignore
|
||||
participant: key.participant || undefined
|
||||
}
|
||||
@@ -741,17 +703,17 @@ export const decodeMediaRetryNode = (node: BinaryNode) => {
|
||||
}
|
||||
|
||||
const errorNode = getBinaryNodeChild(node, 'error')
|
||||
if(errorNode) {
|
||||
if (errorNode) {
|
||||
const errorCode = +errorNode.attrs.code
|
||||
event.error = new Boom(
|
||||
`Failed to re-upload media (${errorCode})`,
|
||||
{ data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(errorCode) }
|
||||
)
|
||||
event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
|
||||
data: errorNode.attrs,
|
||||
statusCode: getStatusCodeForMediaRetry(errorCode)
|
||||
})
|
||||
} else {
|
||||
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
|
||||
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
|
||||
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
|
||||
if(ciphertext && iv) {
|
||||
if (ciphertext && iv) {
|
||||
event.media = { ciphertext, iv }
|
||||
} else {
|
||||
event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
||||
@@ -761,8 +723,8 @@ export const decodeMediaRetryNode = (node: BinaryNode) => {
|
||||
return event
|
||||
}
|
||||
|
||||
export const decryptMediaRetryData = async(
|
||||
{ ciphertext, iv }: { ciphertext: Uint8Array, iv: Uint8Array },
|
||||
export const decryptMediaRetryData = async (
|
||||
{ ciphertext, iv }: { ciphertext: Uint8Array; iv: Uint8Array },
|
||||
mediaKey: Uint8Array,
|
||||
msgId: string
|
||||
) => {
|
||||
@@ -777,5 +739,5 @@ const MEDIA_RETRY_STATUS_MAP = {
|
||||
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
||||
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
||||
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
||||
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
|
||||
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
||||
} as const
|
||||
@@ -21,13 +21,20 @@ import {
|
||||
WAMessageContent,
|
||||
WAMessageStatus,
|
||||
WAProto,
|
||||
WATextMessage,
|
||||
WATextMessage
|
||||
} from '../Types'
|
||||
import { isJidGroup, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
|
||||
import { sha256 } from './crypto'
|
||||
import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics'
|
||||
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 = {
|
||||
media: WAMediaUpload
|
||||
@@ -51,15 +58,15 @@ const MIMETYPE_MAP: { [T in MediaType]?: string } = {
|
||||
document: 'application/pdf',
|
||||
audio: 'audio/ogg; codecs=opus',
|
||||
sticker: 'image/webp',
|
||||
'product-catalog-image': 'image/jpeg',
|
||||
'product-catalog-image': 'image/jpeg'
|
||||
}
|
||||
|
||||
const MessageTypeProto = {
|
||||
'image': WAProto.Message.ImageMessage,
|
||||
'video': WAProto.Message.VideoMessage,
|
||||
'audio': WAProto.Message.AudioMessage,
|
||||
'sticker': WAProto.Message.StickerMessage,
|
||||
'document': WAProto.Message.DocumentMessage,
|
||||
image: WAProto.Message.ImageMessage,
|
||||
video: WAProto.Message.VideoMessage,
|
||||
audio: WAProto.Message.AudioMessage,
|
||||
sticker: WAProto.Message.StickerMessage,
|
||||
document: WAProto.Message.DocumentMessage
|
||||
} as const
|
||||
|
||||
/**
|
||||
@@ -69,25 +76,30 @@ const MessageTypeProto = {
|
||||
*/
|
||||
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)
|
||||
if(!!getUrlInfo && url) {
|
||||
if (!!getUrlInfo && url) {
|
||||
try {
|
||||
const urlInfo = await getUrlInfo(url)
|
||||
return urlInfo
|
||||
} catch(error) { // ignore if fails
|
||||
} catch (error) {
|
||||
// ignore if fails
|
||||
logger?.warn({ trace: error.stack }, 'url generation failed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const assertColor = async(color) => {
|
||||
const assertColor = async color => {
|
||||
let assertedColor
|
||||
if(typeof color === 'number') {
|
||||
if (typeof color === 'number') {
|
||||
assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1
|
||||
} else {
|
||||
let hex = color.trim().replace('#', '')
|
||||
if(hex.length <= 6) {
|
||||
if (hex.length <= 6) {
|
||||
hex = 'FF' + hex.padStart(6, '0')
|
||||
}
|
||||
|
||||
@@ -96,20 +108,17 @@ const assertColor = async(color) => {
|
||||
}
|
||||
}
|
||||
|
||||
export const prepareWAMessageMedia = async(
|
||||
message: AnyMediaMessageContent,
|
||||
options: MediaGenerationOptions
|
||||
) => {
|
||||
export const prepareWAMessageMedia = async (message: AnyMediaMessageContent, options: MediaGenerationOptions) => {
|
||||
const logger = options.logger
|
||||
|
||||
let mediaType: typeof MEDIA_KEYS[number] | undefined
|
||||
for(const key of MEDIA_KEYS) {
|
||||
if(key in message) {
|
||||
let mediaType: (typeof MEDIA_KEYS)[number] | undefined
|
||||
for (const key of MEDIA_KEYS) {
|
||||
if (key in message) {
|
||||
mediaType = key
|
||||
}
|
||||
}
|
||||
|
||||
if(!mediaType) {
|
||||
if (!mediaType) {
|
||||
throw new Boom('Invalid media type', { statusCode: 400 })
|
||||
}
|
||||
|
||||
@@ -119,26 +128,26 @@ export const prepareWAMessageMedia = async(
|
||||
}
|
||||
delete uploadData[mediaType]
|
||||
// check if cacheable + generate cache key
|
||||
const cacheableKey = typeof uploadData.media === 'object' &&
|
||||
('url' in uploadData.media) &&
|
||||
const cacheableKey =
|
||||
typeof uploadData.media === 'object' &&
|
||||
'url' in uploadData.media &&
|
||||
!!uploadData.media.url &&
|
||||
!!options.mediaCache && (
|
||||
!!options.mediaCache &&
|
||||
// generate the key
|
||||
mediaType + ':' + uploadData.media.url.toString()
|
||||
)
|
||||
|
||||
if(mediaType === 'document' && !uploadData.fileName) {
|
||||
if (mediaType === 'document' && !uploadData.fileName) {
|
||||
uploadData.fileName = 'file'
|
||||
}
|
||||
|
||||
if(!uploadData.mimetype) {
|
||||
if (!uploadData.mimetype) {
|
||||
uploadData.mimetype = MIMETYPE_MAP[mediaType]
|
||||
}
|
||||
|
||||
// check for cache hit
|
||||
if(cacheableKey) {
|
||||
if (cacheableKey) {
|
||||
const mediaBuff = options.mediaCache!.get<Buffer>(cacheableKey)
|
||||
if(mediaBuff) {
|
||||
if (mediaBuff) {
|
||||
logger?.debug({ cacheableKey }, 'got media cache hit')
|
||||
|
||||
const obj = WAProto.Message.decode(mediaBuff)
|
||||
@@ -151,19 +160,12 @@ export const prepareWAMessageMedia = async(
|
||||
}
|
||||
|
||||
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
|
||||
const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
|
||||
(typeof uploadData['jpegThumbnail'] === 'undefined')
|
||||
const requiresThumbnailComputation =
|
||||
(mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined'
|
||||
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true
|
||||
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true
|
||||
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation
|
||||
const {
|
||||
mediaKey,
|
||||
encFilePath,
|
||||
originalFilePath,
|
||||
fileEncSha256,
|
||||
fileSha256,
|
||||
fileLength
|
||||
} = await encryptedStream(
|
||||
const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(
|
||||
uploadData.media,
|
||||
options.mediaTypeOverride || mediaType,
|
||||
{
|
||||
@@ -175,23 +177,25 @@ export const prepareWAMessageMedia = async(
|
||||
// url safe Base64 encode the SHA256 hash of the body
|
||||
const fileEncSha256B64 = fileEncSha256.toString('base64')
|
||||
const [{ mediaUrl, directPath }] = await Promise.all([
|
||||
(async() => {
|
||||
const result = await options.upload(
|
||||
encFilePath,
|
||||
{ fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs }
|
||||
)
|
||||
(async () => {
|
||||
const result = await options.upload(encFilePath, {
|
||||
fileEncSha256B64,
|
||||
mediaType,
|
||||
timeoutMs: options.mediaUploadTimeoutMs
|
||||
})
|
||||
logger?.debug({ mediaType, cacheableKey }, 'uploaded media')
|
||||
return result
|
||||
})(),
|
||||
(async() => {
|
||||
(async () => {
|
||||
try {
|
||||
if(requiresThumbnailComputation) {
|
||||
const {
|
||||
thumbnail,
|
||||
originalImageDimensions
|
||||
} = await generateThumbnail(originalFilePath!, mediaType as 'image' | 'video', options)
|
||||
if (requiresThumbnailComputation) {
|
||||
const { thumbnail, originalImageDimensions } = await generateThumbnail(
|
||||
originalFilePath!,
|
||||
mediaType as 'image' | 'video',
|
||||
options
|
||||
)
|
||||
uploadData.jpegThumbnail = thumbnail
|
||||
if(!uploadData.width && originalImageDimensions) {
|
||||
if (!uploadData.width && originalImageDimensions) {
|
||||
uploadData.width = originalImageDimensions.width
|
||||
uploadData.height = originalImageDimensions.height
|
||||
logger?.debug('set dimensions')
|
||||
@@ -200,43 +204,39 @@ export const prepareWAMessageMedia = async(
|
||||
logger?.debug('generated thumbnail')
|
||||
}
|
||||
|
||||
if(requiresDurationComputation) {
|
||||
if (requiresDurationComputation) {
|
||||
uploadData.seconds = await getAudioDuration(originalFilePath!)
|
||||
logger?.debug('computed audio duration')
|
||||
}
|
||||
|
||||
if(requiresWaveformProcessing) {
|
||||
if (requiresWaveformProcessing) {
|
||||
uploadData.waveform = await getAudioWaveform(originalFilePath!, logger)
|
||||
logger?.debug('processed waveform')
|
||||
}
|
||||
|
||||
if(requiresAudioBackground) {
|
||||
if (requiresAudioBackground) {
|
||||
uploadData.backgroundArgb = await assertColor(options.backgroundColor)
|
||||
logger?.debug('computed backgroundColor audio status')
|
||||
}
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
logger?.warn({ trace: error.stack }, 'failed to obtain extra info')
|
||||
}
|
||||
})(),
|
||||
])
|
||||
.finally(
|
||||
async() => {
|
||||
})()
|
||||
]).finally(async () => {
|
||||
try {
|
||||
await fs.unlink(encFilePath)
|
||||
if(originalFilePath) {
|
||||
if (originalFilePath) {
|
||||
await fs.unlink(originalFilePath)
|
||||
}
|
||||
|
||||
logger?.debug('removed tmp files')
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
logger?.warn('failed to remove tmp file')
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
const obj = WAProto.Message.fromObject({
|
||||
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject(
|
||||
{
|
||||
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
||||
url: mediaUrl,
|
||||
directPath,
|
||||
mediaKey,
|
||||
@@ -246,16 +246,15 @@ export const prepareWAMessageMedia = async(
|
||||
mediaKeyTimestamp: unixTimestampSeconds(),
|
||||
...uploadData,
|
||||
media: undefined
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
if(uploadData.ptv) {
|
||||
if (uploadData.ptv) {
|
||||
obj.ptvMessage = obj.videoMessage
|
||||
delete obj.videoMessage
|
||||
}
|
||||
|
||||
if(cacheableKey) {
|
||||
if (cacheableKey) {
|
||||
logger?.debug({ cacheableKey }, 'set cache')
|
||||
options.mediaCache!.set(cacheableKey, WAProto.Message.encode(obj).finish())
|
||||
}
|
||||
@@ -283,12 +282,9 @@ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration?: n
|
||||
* @param message the message to forward
|
||||
* @param options.forceForward will show the message as forwarded even if it is from you
|
||||
*/
|
||||
export const generateForwardMessageContent = (
|
||||
message: WAMessage,
|
||||
forceForward?: boolean
|
||||
) => {
|
||||
export const generateForwardMessageContent = (message: WAMessage, forceForward?: boolean) => {
|
||||
let content = message.message
|
||||
if(!content) {
|
||||
if (!content) {
|
||||
throw new Boom('no content in message', { statusCode: 400 })
|
||||
}
|
||||
|
||||
@@ -300,14 +296,14 @@ export const generateForwardMessageContent = (
|
||||
|
||||
let score = content[key].contextInfo?.forwardingScore || 0
|
||||
score += message.key.fromMe && !forceForward ? 0 : 1
|
||||
if(key === 'conversation') {
|
||||
if (key === 'conversation') {
|
||||
content.extendedTextMessage = { text: content[key] }
|
||||
delete content.conversation
|
||||
|
||||
key = 'extendedTextMessage'
|
||||
}
|
||||
|
||||
if(score > 0) {
|
||||
if (score > 0) {
|
||||
content[key].contextInfo = { forwardingScore: score, isForwarded: true }
|
||||
} else {
|
||||
content[key].contextInfo = {}
|
||||
@@ -316,20 +312,20 @@ export const generateForwardMessageContent = (
|
||||
return content
|
||||
}
|
||||
|
||||
export const generateWAMessageContent = async(
|
||||
export const generateWAMessageContent = async (
|
||||
message: AnyMessageContent,
|
||||
options: MessageContentGenerationOptions
|
||||
) => {
|
||||
let m: WAMessageContent = {}
|
||||
if('text' in message) {
|
||||
if ('text' in message) {
|
||||
const extContent = { text: message.text } as WATextMessage
|
||||
|
||||
let urlInfo = message.linkPreview
|
||||
if(typeof urlInfo === 'undefined') {
|
||||
if (typeof urlInfo === 'undefined') {
|
||||
urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger)
|
||||
}
|
||||
|
||||
if(urlInfo) {
|
||||
if (urlInfo) {
|
||||
extContent.matchedText = urlInfo['matched-text']
|
||||
extContent.jpegThumbnail = urlInfo.jpegThumbnail
|
||||
extContent.description = urlInfo.description
|
||||
@@ -337,7 +333,7 @@ export const generateWAMessageContent = async(
|
||||
extContent.previewType = 0
|
||||
|
||||
const img = urlInfo.highQualityThumbnail
|
||||
if(img) {
|
||||
if (img) {
|
||||
extContent.thumbnailDirectPath = img.directPath
|
||||
extContent.mediaKey = img.mediaKey
|
||||
extContent.mediaKeyTimestamp = img.mediaKeyTimestamp
|
||||
@@ -348,50 +344,50 @@ export const generateWAMessageContent = async(
|
||||
}
|
||||
}
|
||||
|
||||
if(options.backgroundColor) {
|
||||
if (options.backgroundColor) {
|
||||
extContent.backgroundArgb = await assertColor(options.backgroundColor)
|
||||
}
|
||||
|
||||
if(options.font) {
|
||||
if (options.font) {
|
||||
extContent.font = options.font
|
||||
}
|
||||
|
||||
m.extendedTextMessage = extContent
|
||||
} else if('contacts' in message) {
|
||||
} else if ('contacts' in message) {
|
||||
const contactLen = message.contacts.contacts.length
|
||||
if(!contactLen) {
|
||||
if (!contactLen) {
|
||||
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])
|
||||
} else {
|
||||
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)
|
||||
} else if('react' in message) {
|
||||
if(!message.react.senderTimestampMs) {
|
||||
} else if ('react' in message) {
|
||||
if (!message.react.senderTimestampMs) {
|
||||
message.react.senderTimestampMs = Date.now()
|
||||
}
|
||||
|
||||
m.reactionMessage = WAProto.Message.ReactionMessage.fromObject(message.react)
|
||||
} else if('delete' in message) {
|
||||
} else if ('delete' in message) {
|
||||
m.protocolMessage = {
|
||||
key: message.delete,
|
||||
type: WAProto.Message.ProtocolMessage.Type.REVOKE
|
||||
}
|
||||
} else if('forward' in message) {
|
||||
m = generateForwardMessageContent(
|
||||
message.forward,
|
||||
message.force
|
||||
)
|
||||
} else if('disappearingMessagesInChat' in message) {
|
||||
const exp = typeof message.disappearingMessagesInChat === 'boolean' ?
|
||||
(message.disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) :
|
||||
message.disappearingMessagesInChat
|
||||
} else if ('forward' in message) {
|
||||
m = generateForwardMessageContent(message.forward, message.force)
|
||||
} else if ('disappearingMessagesInChat' in message) {
|
||||
const exp =
|
||||
typeof message.disappearingMessagesInChat === 'boolean'
|
||||
? message.disappearingMessagesInChat
|
||||
? WA_DEFAULT_EPHEMERAL
|
||||
: 0
|
||||
: message.disappearingMessagesInChat
|
||||
m = prepareDisappearingMessageSettingContent(exp)
|
||||
} else if('groupInvite' in message) {
|
||||
} else if ('groupInvite' in message) {
|
||||
m.groupInviteMessage = {}
|
||||
m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode
|
||||
m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration
|
||||
@@ -401,16 +397,16 @@ export const generateWAMessageContent = async(
|
||||
m.groupInviteMessage.groupName = message.groupInvite.subject
|
||||
//TODO: use built-in interface and get disappearing mode info etc.
|
||||
//TODO: cache / use store!?
|
||||
if(options.getProfilePicUrl) {
|
||||
if (options.getProfilePicUrl) {
|
||||
const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview')
|
||||
if(pfpUrl) {
|
||||
if (pfpUrl) {
|
||||
const resp = await axios.get(pfpUrl, { responseType: 'arraybuffer' })
|
||||
if(resp.status === 200) {
|
||||
if (resp.status === 200) {
|
||||
m.groupInviteMessage.jpegThumbnail = resp.data
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if('pin' in message) {
|
||||
} else if ('pin' in message) {
|
||||
m.pinInChatMessage = {}
|
||||
m.messageContextInfo = {}
|
||||
|
||||
@@ -419,77 +415,67 @@ export const generateWAMessageContent = async(
|
||||
m.pinInChatMessage.senderTimestampMs = Date.now()
|
||||
|
||||
m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0
|
||||
} else if('buttonReply' in message) {
|
||||
} else if ('buttonReply' in message) {
|
||||
switch (message.type) {
|
||||
case 'template':
|
||||
m.templateButtonReplyMessage = {
|
||||
selectedDisplayText: message.buttonReply.displayText,
|
||||
selectedId: message.buttonReply.id,
|
||||
selectedIndex: message.buttonReply.index,
|
||||
selectedIndex: message.buttonReply.index
|
||||
}
|
||||
break
|
||||
case 'plain':
|
||||
m.buttonsResponseMessage = {
|
||||
selectedButtonId: message.buttonReply.id,
|
||||
selectedDisplayText: message.buttonReply.displayText,
|
||||
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
|
||||
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
|
||||
}
|
||||
break
|
||||
}
|
||||
} else if('ptv' in message && message.ptv) {
|
||||
const { videoMessage } = await prepareWAMessageMedia(
|
||||
{ video: message.video },
|
||||
options
|
||||
)
|
||||
} else if ('ptv' in message && message.ptv) {
|
||||
const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options)
|
||||
m.ptvMessage = videoMessage
|
||||
} else if('product' in message) {
|
||||
const { imageMessage } = await prepareWAMessageMedia(
|
||||
{ image: message.product.productImage },
|
||||
options
|
||||
)
|
||||
} else if ('product' in message) {
|
||||
const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options)
|
||||
m.productMessage = WAProto.Message.ProductMessage.fromObject({
|
||||
...message,
|
||||
product: {
|
||||
...message.product,
|
||||
productImage: imageMessage,
|
||||
productImage: imageMessage
|
||||
}
|
||||
})
|
||||
} else if('listReply' in message) {
|
||||
} else if ('listReply' in message) {
|
||||
m.listResponseMessage = { ...message.listReply }
|
||||
} else if('poll' in message) {
|
||||
} else if ('poll' in message) {
|
||||
message.poll.selectableCount ||= 0
|
||||
message.poll.toAnnouncementGroup ||= false
|
||||
|
||||
if(!Array.isArray(message.poll.values)) {
|
||||
if (!Array.isArray(message.poll.values)) {
|
||||
throw new Boom('Invalid poll values', { statusCode: 400 })
|
||||
}
|
||||
|
||||
if(
|
||||
message.poll.selectableCount < 0
|
||||
|| message.poll.selectableCount > message.poll.values.length
|
||||
) {
|
||||
throw new Boom(
|
||||
`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`,
|
||||
{ statusCode: 400 }
|
||||
)
|
||||
if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
|
||||
throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
|
||||
statusCode: 400
|
||||
})
|
||||
}
|
||||
|
||||
m.messageContextInfo = {
|
||||
// encKey
|
||||
messageSecret: message.poll.messageSecret || randomBytes(32),
|
||||
messageSecret: message.poll.messageSecret || randomBytes(32)
|
||||
}
|
||||
|
||||
const pollCreationMessage = {
|
||||
name: message.poll.name,
|
||||
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)
|
||||
m.pollCreationMessageV2 = pollCreationMessage
|
||||
} else {
|
||||
if(message.poll.selectableCount > 0) {
|
||||
if (message.poll.selectableCount > 0) {
|
||||
//poll v3 is for single select polls
|
||||
m.pollCreationMessageV3 = pollCreationMessage
|
||||
} else {
|
||||
@@ -497,30 +483,27 @@ export const generateWAMessageContent = async(
|
||||
m.pollCreationMessage = pollCreationMessage
|
||||
}
|
||||
}
|
||||
} else if('sharePhoneNumber' in message) {
|
||||
} else if ('sharePhoneNumber' in message) {
|
||||
m.protocolMessage = {
|
||||
type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
|
||||
}
|
||||
} else if('requestPhoneNumber' in message) {
|
||||
} else if ('requestPhoneNumber' in message) {
|
||||
m.requestPhoneNumberMessage = {}
|
||||
} else {
|
||||
m = await prepareWAMessageMedia(
|
||||
message,
|
||||
options
|
||||
)
|
||||
m = await prepareWAMessageMedia(message, options)
|
||||
}
|
||||
|
||||
if('viewOnce' in message && !!message.viewOnce) {
|
||||
if ('viewOnce' in message && !!message.viewOnce) {
|
||||
m = { viewOnceMessage: { message: m } }
|
||||
}
|
||||
|
||||
if('mentions' in message && message.mentions?.length) {
|
||||
if ('mentions' in message && message.mentions?.length) {
|
||||
const [messageType] = Object.keys(m)
|
||||
m[messageType].contextInfo = m[messageType] || { }
|
||||
m[messageType].contextInfo = m[messageType] || {}
|
||||
m[messageType].contextInfo.mentionedJid = message.mentions
|
||||
}
|
||||
|
||||
if('edit' in message) {
|
||||
if ('edit' in message) {
|
||||
m = {
|
||||
protocolMessage: {
|
||||
key: message.edit,
|
||||
@@ -531,7 +514,7 @@ export const generateWAMessageContent = async(
|
||||
}
|
||||
}
|
||||
|
||||
if('contextInfo' in message && !!message.contextInfo) {
|
||||
if ('contextInfo' in message && !!message.contextInfo) {
|
||||
const [messageType] = Object.keys(m)
|
||||
m[messageType] = m[messageType] || {}
|
||||
m[messageType].contextInfo = message.contextInfo
|
||||
@@ -547,7 +530,7 @@ export const generateWAMessageFromContent = (
|
||||
) => {
|
||||
// set timestamp to now
|
||||
// if not specified
|
||||
if(!options.timestamp) {
|
||||
if (!options.timestamp) {
|
||||
options.timestamp = new Date()
|
||||
}
|
||||
|
||||
@@ -556,8 +539,10 @@ export const generateWAMessageFromContent = (
|
||||
const timestamp = unixTimestampSeconds(options.timestamp)
|
||||
const { quoted, userJid } = options
|
||||
|
||||
if(quoted) {
|
||||
const participant = quoted.key.fromMe ? userJid : (quoted.participant || quoted.key.participant || quoted.key.remoteJid)
|
||||
if (quoted) {
|
||||
const participant = quoted.key.fromMe
|
||||
? userJid
|
||||
: quoted.participant || quoted.key.participant || quoted.key.remoteJid
|
||||
|
||||
let quotedMsg = normalizeMessageContent(quoted.message)!
|
||||
const msgType = getContentType(quotedMsg)!
|
||||
@@ -565,25 +550,25 @@ export const generateWAMessageFromContent = (
|
||||
quotedMsg = proto.Message.fromObject({ [msgType]: 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
|
||||
}
|
||||
|
||||
const contextInfo: proto.IContextInfo = innerMessage[key].contextInfo || { }
|
||||
const contextInfo: proto.IContextInfo = innerMessage[key].contextInfo || {}
|
||||
contextInfo.participant = jidNormalizedUser(participant!)
|
||||
contextInfo.stanzaId = quoted.key.id
|
||||
contextInfo.quotedMessage = quotedMsg
|
||||
|
||||
// if a participant is quoted, then it must be a group
|
||||
// hence, remoteJid of group must also be entered
|
||||
if(jid !== quoted.key.remoteJid) {
|
||||
if (jid !== quoted.key.remoteJid) {
|
||||
contextInfo.remoteJid = quoted.key.remoteJid
|
||||
}
|
||||
|
||||
innerMessage[key].contextInfo = contextInfo
|
||||
}
|
||||
|
||||
if(
|
||||
if (
|
||||
// if we want to send a disappearing message
|
||||
!!options?.ephemeralExpiration &&
|
||||
// and it's not a protocol message -- delete, toggle disappear message
|
||||
@@ -593,7 +578,7 @@ export const generateWAMessageFromContent = (
|
||||
) {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -604,7 +589,7 @@ export const generateWAMessageFromContent = (
|
||||
key: {
|
||||
remoteJid: jid,
|
||||
fromMe: true,
|
||||
id: options?.messageId || generateMessageIDV2(),
|
||||
id: options?.messageId || generateMessageIDV2()
|
||||
},
|
||||
message: message,
|
||||
messageTimestamp: timestamp,
|
||||
@@ -615,26 +600,15 @@ export const generateWAMessageFromContent = (
|
||||
return WAProto.WebMessageInfo.fromObject(messageJSON)
|
||||
}
|
||||
|
||||
export const generateWAMessage = async(
|
||||
jid: string,
|
||||
content: AnyMessageContent,
|
||||
options: MessageGenerationOptions,
|
||||
) => {
|
||||
export const generateWAMessage = async (jid: string, content: AnyMessageContent, options: MessageGenerationOptions) => {
|
||||
// ensure msg ID is with every log
|
||||
options.logger = options?.logger?.child({ msgId: options.messageId })
|
||||
return generateWAMessageFromContent(
|
||||
jid,
|
||||
await generateWAMessageContent(
|
||||
content,
|
||||
options
|
||||
),
|
||||
options
|
||||
)
|
||||
return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options)
|
||||
}
|
||||
|
||||
/** Get the key to access the true type of content */
|
||||
export const getContentType = (content: WAProto.IMessage | undefined) => {
|
||||
if(content) {
|
||||
if (content) {
|
||||
const keys = Object.keys(content)
|
||||
const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage')
|
||||
return key as keyof typeof content
|
||||
@@ -648,14 +622,14 @@ export const getContentType = (content: WAProto.IMessage | undefined) => {
|
||||
* @returns
|
||||
*/
|
||||
export const normalizeMessageContent = (content: WAMessageContent | null | undefined): WAMessageContent | undefined => {
|
||||
if(!content) {
|
||||
if (!content) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
// 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)
|
||||
if(!inner) {
|
||||
if (!inner) {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -666,12 +640,12 @@ export const normalizeMessageContent = (content: WAMessageContent | null | undef
|
||||
|
||||
function getFutureProofMessage(message: typeof content) {
|
||||
return (
|
||||
message?.ephemeralMessage
|
||||
|| message?.viewOnceMessage
|
||||
|| message?.documentWithCaptionMessage
|
||||
|| message?.viewOnceMessageV2
|
||||
|| message?.viewOnceMessageV2Extension
|
||||
|| message?.editedMessage
|
||||
message?.ephemeralMessage ||
|
||||
message?.viewOnceMessage ||
|
||||
message?.documentWithCaptionMessage ||
|
||||
message?.viewOnceMessageV2 ||
|
||||
message?.viewOnceMessageV2Extension ||
|
||||
message?.editedMessage
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -681,40 +655,40 @@ export const normalizeMessageContent = (content: WAMessageContent | null | undef
|
||||
* Eg. extracts the inner message from a disappearing message/view once message
|
||||
*/
|
||||
export const extractMessageContent = (content: WAMessageContent | undefined | null): WAMessageContent | undefined => {
|
||||
const extractFromTemplateMessage = (msg: proto.Message.TemplateMessage.IHydratedFourRowTemplate | proto.Message.IButtonsMessage) => {
|
||||
if(msg.imageMessage) {
|
||||
const extractFromTemplateMessage = (
|
||||
msg: proto.Message.TemplateMessage.IHydratedFourRowTemplate | proto.Message.IButtonsMessage
|
||||
) => {
|
||||
if (msg.imageMessage) {
|
||||
return { imageMessage: msg.imageMessage }
|
||||
} else if(msg.documentMessage) {
|
||||
} else if (msg.documentMessage) {
|
||||
return { documentMessage: msg.documentMessage }
|
||||
} else if(msg.videoMessage) {
|
||||
} else if (msg.videoMessage) {
|
||||
return { videoMessage: msg.videoMessage }
|
||||
} else if(msg.locationMessage) {
|
||||
} else if (msg.locationMessage) {
|
||||
return { locationMessage: msg.locationMessage }
|
||||
} else {
|
||||
return {
|
||||
conversation:
|
||||
'contentText' in msg
|
||||
? msg.contentText
|
||||
: ('hydratedContentText' in msg ? msg.hydratedContentText : '')
|
||||
'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
content = normalizeMessageContent(content)
|
||||
|
||||
if(content?.buttonsMessage) {
|
||||
if (content?.buttonsMessage) {
|
||||
return extractFromTemplateMessage(content.buttonsMessage)
|
||||
}
|
||||
|
||||
if(content?.templateMessage?.hydratedFourRowTemplate) {
|
||||
if (content?.templateMessage?.hydratedFourRowTemplate) {
|
||||
return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate)
|
||||
}
|
||||
|
||||
if(content?.templateMessage?.hydratedTemplate) {
|
||||
if (content?.templateMessage?.hydratedTemplate) {
|
||||
return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate)
|
||||
}
|
||||
|
||||
if(content?.templateMessage?.fourRowTemplate) {
|
||||
if (content?.templateMessage?.fourRowTemplate) {
|
||||
return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate)
|
||||
}
|
||||
|
||||
@@ -724,17 +698,22 @@ export const extractMessageContent = (content: WAMessageContent | undefined | nu
|
||||
/**
|
||||
* Returns the device predicted by message ID
|
||||
*/
|
||||
export const getDevice = (id: string) => /^3A.{18}$/.test(id) ? 'ios' :
|
||||
/^3E.{20}$/.test(id) ? 'web' :
|
||||
/^(.{21}|.{32})$/.test(id) ? 'android' :
|
||||
/^(3F|.{18}$)/.test(id) ? 'desktop' :
|
||||
'unknown'
|
||||
export const getDevice = (id: string) =>
|
||||
/^3A.{18}$/.test(id)
|
||||
? 'ios'
|
||||
: /^3E.{20}$/.test(id)
|
||||
? 'web'
|
||||
: /^(.{21}|.{32})$/.test(id)
|
||||
? 'android'
|
||||
: /^(3F|.{18}$)/.test(id)
|
||||
? 'desktop'
|
||||
: 'unknown'
|
||||
|
||||
/** Upserts a receipt in the message */
|
||||
export const updateMessageWithReceipt = (msg: Pick<WAMessage, 'userReceipt'>, receipt: MessageUserReceipt) => {
|
||||
msg.userReceipt = msg.userReceipt || []
|
||||
const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid)
|
||||
if(recp) {
|
||||
if (recp) {
|
||||
Object.assign(recp, receipt)
|
||||
} else {
|
||||
msg.userReceipt.push(receipt)
|
||||
@@ -745,9 +724,8 @@ export const updateMessageWithReceipt = (msg: Pick<WAMessage, 'userReceipt'>, re
|
||||
export const updateMessageWithReaction = (msg: Pick<WAMessage, 'reactions'>, reaction: proto.IReaction) => {
|
||||
const authorID = getKeyAuthor(reaction.key)
|
||||
|
||||
const reactions = (msg.reactions || [])
|
||||
.filter(r => getKeyAuthor(r.key) !== authorID)
|
||||
if(reaction.text) {
|
||||
const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID)
|
||||
if (reaction.text) {
|
||||
reactions.push(reaction)
|
||||
}
|
||||
|
||||
@@ -755,15 +733,11 @@ export const updateMessageWithReaction = (msg: Pick<WAMessage, 'reactions'>, rea
|
||||
}
|
||||
|
||||
/** Update the message with a new poll update */
|
||||
export const updateMessageWithPollUpdate = (
|
||||
msg: Pick<WAMessage, 'pollUpdates'>,
|
||||
update: proto.IPollUpdate
|
||||
) => {
|
||||
export const updateMessageWithPollUpdate = (msg: Pick<WAMessage, 'pollUpdates'>, update: proto.IPollUpdate) => {
|
||||
const authorID = getKeyAuthor(update.pollUpdateMessageKey)
|
||||
|
||||
const reactions = (msg.pollUpdates || [])
|
||||
.filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
|
||||
if(update.vote?.selectedOptions?.length) {
|
||||
const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
|
||||
if (update.vote?.selectedOptions?.length) {
|
||||
reactions.push(update)
|
||||
}
|
||||
|
||||
@@ -785,26 +759,33 @@ export function getAggregateVotesInPollMessage(
|
||||
{ message, pollUpdates }: Pick<WAMessage, 'pollUpdates' | 'message'>,
|
||||
meId?: string
|
||||
) {
|
||||
const opts = message?.pollCreationMessage?.options || message?.pollCreationMessageV2?.options || message?.pollCreationMessageV3?.options || []
|
||||
const voteHashMap = opts.reduce((acc, opt) => {
|
||||
const opts =
|
||||
message?.pollCreationMessage?.options ||
|
||||
message?.pollCreationMessageV2?.options ||
|
||||
message?.pollCreationMessageV3?.options ||
|
||||
[]
|
||||
const voteHashMap = opts.reduce(
|
||||
(acc, opt) => {
|
||||
const hash = sha256(Buffer.from(opt.optionName || '')).toString()
|
||||
acc[hash] = {
|
||||
name: opt.optionName || '',
|
||||
voters: []
|
||||
}
|
||||
return acc
|
||||
}, {} as { [_: string]: VoteAggregation })
|
||||
},
|
||||
{} as { [_: string]: VoteAggregation }
|
||||
)
|
||||
|
||||
for(const update of pollUpdates || []) {
|
||||
for (const update of pollUpdates || []) {
|
||||
const { vote } = update
|
||||
if(!vote) {
|
||||
if (!vote) {
|
||||
continue
|
||||
}
|
||||
|
||||
for(const option of vote.selectedOptions || []) {
|
||||
for (const option of vote.selectedOptions || []) {
|
||||
const hash = option.toString()
|
||||
let data = voteHashMap[hash]
|
||||
if(!data) {
|
||||
if (!data) {
|
||||
voteHashMap[hash] = {
|
||||
name: 'Unknown',
|
||||
voters: []
|
||||
@@ -812,9 +793,7 @@ export function getAggregateVotesInPollMessage(
|
||||
data = voteHashMap[hash]
|
||||
}
|
||||
|
||||
voteHashMap[hash].voters.push(
|
||||
getKeyAuthor(update.pollUpdateMessageKey, meId)
|
||||
)
|
||||
voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -823,11 +802,11 @@ export function getAggregateVotesInPollMessage(
|
||||
|
||||
/** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
|
||||
export const aggregateMessageKeysNotFromMe = (keys: proto.IMessageKey[]) => {
|
||||
const keyMap: { [id: string]: { jid: string, participant: string | undefined, messageIds: string[] } } = { }
|
||||
for(const { remoteJid, id, participant, fromMe } of keys) {
|
||||
if(!fromMe) {
|
||||
const keyMap: { [id: string]: { jid: string; participant: string | undefined; messageIds: string[] } } = {}
|
||||
for (const { remoteJid, id, participant, fromMe } of keys) {
|
||||
if (!fromMe) {
|
||||
const uqKey = `${remoteJid}:${participant || ''}`
|
||||
if(!keyMap[uqKey]) {
|
||||
if (!keyMap[uqKey]) {
|
||||
keyMap[uqKey] = {
|
||||
jid: remoteJid!,
|
||||
participant: participant!,
|
||||
@@ -852,16 +831,18 @@ const REUPLOAD_REQUIRED_STATUS = [410, 404]
|
||||
/**
|
||||
* 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,
|
||||
type: Type,
|
||||
options: MediaDownloadOptions,
|
||||
ctx?: DownloadMediaMessageContext
|
||||
) => {
|
||||
const result = await downloadMsg()
|
||||
.catch(async(error) => {
|
||||
if(ctx && axios.isAxiosError(error) && // check if the message requires a reupload
|
||||
REUPLOAD_REQUIRED_STATUS.includes(error.response?.status!)) {
|
||||
const result = await downloadMsg().catch(async error => {
|
||||
if (
|
||||
ctx &&
|
||||
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...')
|
||||
// request reupload
|
||||
message = await ctx.reuploadRequest(message)
|
||||
@@ -876,7 +857,7 @@ export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
||||
|
||||
async function downloadMsg() {
|
||||
const mContent = extractMessageContent(message.message)
|
||||
if(!mContent) {
|
||||
if (!mContent) {
|
||||
throw new Boom('No message present', { statusCode: 400, data: message })
|
||||
}
|
||||
|
||||
@@ -884,12 +865,12 @@ export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
||||
let mediaType = contentType?.replace('Message', '') as MediaType
|
||||
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`)
|
||||
}
|
||||
|
||||
let download: DownloadableMessage
|
||||
if('thumbnailDirectPath' in media && !('url' in media)) {
|
||||
if ('thumbnailDirectPath' in media && !('url' in media)) {
|
||||
download = {
|
||||
directPath: media.thumbnailDirectPath,
|
||||
mediaKey: media.mediaKey
|
||||
@@ -900,7 +881,7 @@ export const downloadMediaMessage = async<Type extends 'buffer' | 'stream'>(
|
||||
}
|
||||
|
||||
const stream = await downloadContentFromMessage(download, mediaType, options)
|
||||
if(type === 'buffer') {
|
||||
if (type === 'buffer') {
|
||||
const bufferArray: Buffer[] = []
|
||||
for await (const chunk of stream) {
|
||||
bufferArray.push(chunk)
|
||||
@@ -916,16 +897,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 */
|
||||
export const assertMediaContent = (content: proto.IMessage | null | undefined) => {
|
||||
content = extractMessageContent(content)
|
||||
const mediaContent = content?.documentMessage
|
||||
|| content?.imageMessage
|
||||
|| content?.videoMessage
|
||||
|| content?.audioMessage
|
||||
|| content?.stickerMessage
|
||||
if(!mediaContent) {
|
||||
throw new Boom(
|
||||
'given message is not a media message',
|
||||
{ statusCode: 400, data: content }
|
||||
)
|
||||
const mediaContent =
|
||||
content?.documentMessage ||
|
||||
content?.imageMessage ||
|
||||
content?.videoMessage ||
|
||||
content?.audioMessage ||
|
||||
content?.stickerMessage
|
||||
if (!mediaContent) {
|
||||
throw new Boom('given message is not a media message', { statusCode: 400, data: content })
|
||||
}
|
||||
|
||||
return mediaContent
|
||||
|
||||
@@ -27,7 +27,7 @@ export const makeNoiseHandler = ({
|
||||
logger = logger.child({ class: 'ns' })
|
||||
|
||||
const authenticate = (data: Uint8Array) => {
|
||||
if(!isFinished) {
|
||||
if (!isFinished) {
|
||||
hash = sha256(Buffer.concat([hash, data]))
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ export const makeNoiseHandler = ({
|
||||
const iv = generateIV(isFinished ? readCounter : writeCounter)
|
||||
const result = aesDecryptGCM(ciphertext, decKey, iv, hash)
|
||||
|
||||
if(isFinished) {
|
||||
if (isFinished) {
|
||||
readCounter += 1
|
||||
} else {
|
||||
writeCounter += 1
|
||||
@@ -57,12 +57,12 @@ export const makeNoiseHandler = ({
|
||||
return result
|
||||
}
|
||||
|
||||
const localHKDF = async(data: Uint8Array) => {
|
||||
const localHKDF = async (data: Uint8Array) => {
|
||||
const key = await hkdf(Buffer.from(data), 64, { salt, info: '' })
|
||||
return [key.slice(0, 32), key.slice(32)]
|
||||
}
|
||||
|
||||
const mixIntoKey = async(data: Uint8Array) => {
|
||||
const mixIntoKey = async (data: Uint8Array) => {
|
||||
const [write, read] = await localHKDF(data)
|
||||
salt = write
|
||||
encKey = read
|
||||
@@ -71,7 +71,7 @@ export const makeNoiseHandler = ({
|
||||
writeCounter = 0
|
||||
}
|
||||
|
||||
const finishInit = async() => {
|
||||
const finishInit = async () => {
|
||||
const [write, read] = await localHKDF(new Uint8Array(0))
|
||||
encKey = write
|
||||
decKey = read
|
||||
@@ -102,7 +102,7 @@ export const makeNoiseHandler = ({
|
||||
authenticate,
|
||||
mixIntoKey,
|
||||
finishInit,
|
||||
processHandshake: async({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => {
|
||||
processHandshake: async ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => {
|
||||
authenticate(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!)
|
||||
|
||||
if(issuerSerial !== WA_CERT_DETAILS.SERIAL) {
|
||||
if (issuerSerial !== WA_CERT_DETAILS.SERIAL) {
|
||||
throw new Boom('certification match failed', { statusCode: 400 })
|
||||
}
|
||||
|
||||
@@ -125,13 +125,13 @@ export const makeNoiseHandler = ({
|
||||
return keyEnc
|
||||
},
|
||||
encodeFrame: (data: Buffer | Uint8Array) => {
|
||||
if(isFinished) {
|
||||
if (isFinished) {
|
||||
data = encrypt(data)
|
||||
}
|
||||
|
||||
let header: Buffer
|
||||
|
||||
if(routingInfo) {
|
||||
if (routingInfo) {
|
||||
header = Buffer.alloc(7)
|
||||
header.write('ED', 0, 'utf8')
|
||||
header.writeUint8(0, 2)
|
||||
@@ -146,7 +146,7 @@ export const makeNoiseHandler = ({
|
||||
const introSize = sentIntro ? 0 : header.length
|
||||
const frame = Buffer.alloc(introSize + 3 + data.byteLength)
|
||||
|
||||
if(!sentIntro) {
|
||||
if (!sentIntro) {
|
||||
frame.set(header)
|
||||
sentIntro = true
|
||||
}
|
||||
@@ -157,26 +157,26 @@ export const makeNoiseHandler = ({
|
||||
|
||||
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
|
||||
// on top of the WS frames
|
||||
// so we get this data and separate out the frames
|
||||
const getBytesSize = () => {
|
||||
if(inBytes.length >= 3) {
|
||||
if (inBytes.length >= 3) {
|
||||
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`)
|
||||
|
||||
let size = getBytesSize()
|
||||
while(size && inBytes.length >= size + 3) {
|
||||
while (size && inBytes.length >= size + 3) {
|
||||
let frame: Uint8Array | BinaryNode = inBytes.slice(3, size + 3)
|
||||
inBytes = inBytes.slice(size + 3)
|
||||
|
||||
if(isFinished) {
|
||||
if (isFinished) {
|
||||
const result = decrypt(frame)
|
||||
frame = await decodeBinaryNode(result)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import { AxiosRequestConfig } from 'axios'
|
||||
import { proto } from '../../WAProto'
|
||||
import { AuthenticationCreds, BaileysEventEmitter, CacheStore, Chat, GroupMetadata, ParticipantAction, RequestJoinAction, RequestJoinMethod, SignalKeyStoreWithTransaction, WAMessageStubType } from '../Types'
|
||||
import {
|
||||
AuthenticationCreds,
|
||||
BaileysEventEmitter,
|
||||
CacheStore,
|
||||
Chat,
|
||||
GroupMetadata,
|
||||
ParticipantAction,
|
||||
RequestJoinAction,
|
||||
RequestJoinMethod,
|
||||
SignalKeyStoreWithTransaction,
|
||||
WAMessageStubType
|
||||
} from '../Types'
|
||||
import { getContentType, normalizeMessageContent } from '../Utils/messages'
|
||||
import { areJidsSameUser, isJidBroadcast, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
|
||||
import { aesDecryptGCM, hmacSign } from './crypto'
|
||||
@@ -25,9 +36,7 @@ const REAL_MSG_STUB_TYPES = new Set([
|
||||
WAMessageStubType.CALL_MISSED_VOICE
|
||||
])
|
||||
|
||||
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
|
||||
WAMessageStubType.GROUP_PARTICIPANT_ADD
|
||||
])
|
||||
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
|
||||
|
||||
/** Cleans a received message to further processing */
|
||||
export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
|
||||
@@ -36,25 +45,25 @@ export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
|
||||
message.key.participant = message.key.participant ? jidNormalizedUser(message.key.participant) : undefined
|
||||
const content = normalizeMessageContent(message.message)
|
||||
// if the message has a reaction, ensure fromMe & remoteJid are from our perspective
|
||||
if(content?.reactionMessage) {
|
||||
if (content?.reactionMessage) {
|
||||
normaliseKey(content.reactionMessage.key!)
|
||||
}
|
||||
|
||||
if(content?.pollUpdateMessage) {
|
||||
if (content?.pollUpdateMessage) {
|
||||
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey!)
|
||||
}
|
||||
|
||||
function normaliseKey(msgKey: proto.IMessageKey) {
|
||||
// if the reaction is from another user
|
||||
// we've to correctly map the key to this user's perspective
|
||||
if(!message.key.fromMe) {
|
||||
if (!message.key.fromMe) {
|
||||
// if the sender believed the message being reacted to is not from them
|
||||
// we've to correct the key to be from them, or some other participant
|
||||
msgKey.fromMe = !msgKey.fromMe
|
||||
? areJidsSameUser(msgKey.participant || msgKey.remoteJid!, meId)
|
||||
// if the message being reacted to, was from them
|
||||
: // if the message being reacted to, was from them
|
||||
// fromMe automatically becomes false
|
||||
: false
|
||||
false
|
||||
// set the remoteJid to being the same as the chat the message came from
|
||||
msgKey.remoteJid = message.key.remoteJid
|
||||
// set participant of the message
|
||||
@@ -67,33 +76,26 @@ export const isRealMessage = (message: proto.IWebMessageInfo, meId: string) => {
|
||||
const normalizedContent = normalizeMessageContent(message.message)
|
||||
const hasSomeContent = !!getContentType(normalizedContent)
|
||||
return (
|
||||
!!normalizedContent
|
||||
|| REAL_MSG_STUB_TYPES.has(message.messageStubType!)
|
||||
|| (
|
||||
REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType!)
|
||||
&& message.messageStubParameters?.some(p => areJidsSameUser(meId, p))
|
||||
(!!normalizedContent ||
|
||||
REAL_MSG_STUB_TYPES.has(message.messageStubType!) ||
|
||||
(REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType!) &&
|
||||
message.messageStubParameters?.some(p => areJidsSameUser(meId, p)))) &&
|
||||
hasSomeContent &&
|
||||
!normalizedContent?.protocolMessage &&
|
||||
!normalizedContent?.reactionMessage &&
|
||||
!normalizedContent?.pollUpdateMessage
|
||||
)
|
||||
)
|
||||
&& hasSomeContent
|
||||
&& !normalizedContent?.protocolMessage
|
||||
&& !normalizedContent?.reactionMessage
|
||||
&& !normalizedContent?.pollUpdateMessage
|
||||
}
|
||||
|
||||
export const shouldIncrementChatUnread = (message: proto.IWebMessageInfo) => (
|
||||
export const shouldIncrementChatUnread = (message: proto.IWebMessageInfo) =>
|
||||
!message.key.fromMe && !message.messageStubType
|
||||
)
|
||||
|
||||
/**
|
||||
* Get the ID of the chat from the given key.
|
||||
* Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
|
||||
*/
|
||||
export const getChatId = ({ remoteJid, participant, fromMe }: proto.IMessageKey) => {
|
||||
if(
|
||||
isJidBroadcast(remoteJid!)
|
||||
&& !isJidStatusBroadcast(remoteJid!)
|
||||
&& !fromMe
|
||||
) {
|
||||
if (isJidBroadcast(remoteJid!) && !isJidStatusBroadcast(remoteJid!) && !fromMe) {
|
||||
return participant!
|
||||
}
|
||||
|
||||
@@ -119,22 +121,15 @@ type PollContext = {
|
||||
*/
|
||||
export function decryptPollVote(
|
||||
{ encPayload, encIv }: proto.Message.IPollEncValue,
|
||||
{
|
||||
pollCreatorJid,
|
||||
pollMsgId,
|
||||
pollEncKey,
|
||||
voterJid,
|
||||
}: PollContext
|
||||
{ pollCreatorJid, pollMsgId, pollEncKey, voterJid }: PollContext
|
||||
) {
|
||||
const sign = Buffer.concat(
|
||||
[
|
||||
const sign = Buffer.concat([
|
||||
toBinary(pollMsgId),
|
||||
toBinary(pollCreatorJid),
|
||||
toBinary(voterJid),
|
||||
toBinary('Poll Vote'),
|
||||
new Uint8Array([1])
|
||||
]
|
||||
)
|
||||
])
|
||||
|
||||
const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
|
||||
const decKey = hmacSign(sign, key0, 'sha256')
|
||||
@@ -148,17 +143,9 @@ export function decryptPollVote(
|
||||
}
|
||||
}
|
||||
|
||||
const processMessage = async(
|
||||
const processMessage = async (
|
||||
message: proto.IWebMessageInfo,
|
||||
{
|
||||
shouldProcessHistoryMsg,
|
||||
placeholderResendCache,
|
||||
ev,
|
||||
creds,
|
||||
keyStore,
|
||||
logger,
|
||||
options
|
||||
}: ProcessMessageContext
|
||||
{ shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options }: ProcessMessageContext
|
||||
) => {
|
||||
const meId = creds.me!.id
|
||||
const { accountSettings } = creds
|
||||
@@ -166,11 +153,11 @@ const processMessage = async(
|
||||
const chat: Partial<Chat> = { id: jidNormalizedUser(getChatId(message.key)) }
|
||||
const isRealMsg = isRealMessage(message, meId)
|
||||
|
||||
if(isRealMsg) {
|
||||
if (isRealMsg) {
|
||||
chat.messages = [{ message }]
|
||||
chat.conversationTimestamp = toNumber(message.messageTimestamp)
|
||||
// only increment unread count if not CIPHERTEXT and from another person
|
||||
if(shouldIncrementChatUnread(message)) {
|
||||
if (shouldIncrementChatUnread(message)) {
|
||||
chat.unreadCount = (chat.unreadCount || 0) + 1
|
||||
}
|
||||
}
|
||||
@@ -179,31 +166,31 @@ const processMessage = async(
|
||||
|
||||
// unarchive chat if it's a real message, or someone reacted to our message
|
||||
// and we've the unarchive chats setting on
|
||||
if(
|
||||
(isRealMsg || content?.reactionMessage?.key?.fromMe)
|
||||
&& accountSettings?.unarchiveChats
|
||||
) {
|
||||
if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
|
||||
chat.archived = false
|
||||
chat.readOnly = false
|
||||
}
|
||||
|
||||
const protocolMsg = content?.protocolMessage
|
||||
if(protocolMsg) {
|
||||
if (protocolMsg) {
|
||||
switch (protocolMsg.type) {
|
||||
case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
|
||||
const histNotification = protocolMsg.historySyncNotification!
|
||||
const process = shouldProcessHistoryMsg
|
||||
const isLatest = !creds.processedHistoryMessages?.length
|
||||
|
||||
logger?.info({
|
||||
logger?.info(
|
||||
{
|
||||
histNotification,
|
||||
process,
|
||||
id: message.key.id,
|
||||
isLatest,
|
||||
}, 'got history notification')
|
||||
isLatest
|
||||
},
|
||||
'got history notification'
|
||||
)
|
||||
|
||||
if(process) {
|
||||
if(histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
|
||||
if (process) {
|
||||
if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
|
||||
ev.emit('creds.update', {
|
||||
processedHistoryMessages: [
|
||||
...(creds.processedHistoryMessages || []),
|
||||
@@ -212,17 +199,11 @@ const processMessage = async(
|
||||
})
|
||||
}
|
||||
|
||||
const data = await downloadAndProcessHistorySyncNotification(
|
||||
histNotification,
|
||||
options
|
||||
)
|
||||
const data = await downloadAndProcessHistorySyncNotification(histNotification, options)
|
||||
|
||||
ev.emit('messaging-history.set', {
|
||||
...data,
|
||||
isLatest:
|
||||
histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND
|
||||
? isLatest
|
||||
: undefined,
|
||||
isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
|
||||
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
|
||||
})
|
||||
}
|
||||
@@ -230,12 +211,11 @@ const processMessage = async(
|
||||
break
|
||||
case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
|
||||
const keys = protocolMsg.appStateSyncKeyShare!.keys
|
||||
if(keys?.length) {
|
||||
if (keys?.length) {
|
||||
let newAppStateSyncKeyId = ''
|
||||
await keyStore.transaction(
|
||||
async() => {
|
||||
await keyStore.transaction(async () => {
|
||||
const newKeys: string[] = []
|
||||
for(const { keyData, keyId } of keys) {
|
||||
for (const { keyData, keyId } of keys) {
|
||||
const strKeyId = Buffer.from(keyId!.keyId!).toString('base64')
|
||||
newKeys.push(strKeyId)
|
||||
|
||||
@@ -244,12 +224,8 @@ const processMessage = async(
|
||||
newAppStateSyncKeyId = strKeyId
|
||||
}
|
||||
|
||||
logger?.info(
|
||||
{ newAppStateSyncKeyId, newKeys },
|
||||
'injecting new app state sync keys'
|
||||
)
|
||||
}
|
||||
)
|
||||
logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
|
||||
})
|
||||
|
||||
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
|
||||
} else {
|
||||
@@ -276,14 +252,14 @@ const processMessage = async(
|
||||
break
|
||||
case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
|
||||
const response = protocolMsg.peerDataOperationRequestResponseMessage!
|
||||
if(response) {
|
||||
if (response) {
|
||||
placeholderResendCache?.del(response.stanzaId!)
|
||||
// TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
|
||||
const { peerDataOperationResult } = response
|
||||
for(const result of peerDataOperationResult!) {
|
||||
for (const result of peerDataOperationResult!) {
|
||||
const { placeholderMessageResendResponse: retryResponse } = result
|
||||
//eslint-disable-next-line max-depth
|
||||
if(retryResponse) {
|
||||
if (retryResponse) {
|
||||
const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes!)
|
||||
// wait till another upsert event is available, don't want it to be part of the PDO response message
|
||||
setTimeout(() => {
|
||||
@@ -298,9 +274,7 @@ const processMessage = async(
|
||||
}
|
||||
|
||||
case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
|
||||
ev.emit(
|
||||
'messages.update',
|
||||
[
|
||||
ev.emit('messages.update', [
|
||||
{
|
||||
// flip the sender / fromMe properties because they're in the perspective of the sender
|
||||
key: { ...message.key, id: protocolMsg.key?.id },
|
||||
@@ -315,26 +289,26 @@ const processMessage = async(
|
||||
: message.messageTimestamp
|
||||
}
|
||||
}
|
||||
]
|
||||
)
|
||||
])
|
||||
break
|
||||
}
|
||||
} else if(content?.reactionMessage) {
|
||||
} else if (content?.reactionMessage) {
|
||||
const reaction: proto.IReaction = {
|
||||
...content.reactionMessage,
|
||||
key: message.key,
|
||||
key: message.key
|
||||
}
|
||||
ev.emit('messages.reaction', [{
|
||||
ev.emit('messages.reaction', [
|
||||
{
|
||||
reaction,
|
||||
key: content.reactionMessage?.key!,
|
||||
}])
|
||||
} else if(message.messageStubType) {
|
||||
key: content.reactionMessage?.key!
|
||||
}
|
||||
])
|
||||
} else if (message.messageStubType) {
|
||||
const jid = message.key?.remoteJid!
|
||||
//let actor = whatsappID (message.participant)
|
||||
let participants: string[]
|
||||
const emitParticipantsUpdate = (action: ParticipantAction) => (
|
||||
const emitParticipantsUpdate = (action: ParticipantAction) =>
|
||||
ev.emit('group-participants.update', { id: jid, author: message.participant!, participants, action })
|
||||
)
|
||||
const emitGroupUpdate = (update: Partial<GroupMetadata>) => {
|
||||
ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ?? undefined }])
|
||||
}
|
||||
@@ -355,7 +329,7 @@ const processMessage = async(
|
||||
participants = message.messageStubParameters || []
|
||||
emitParticipantsUpdate('remove')
|
||||
// mark the chat read only if you left the group
|
||||
if(participantsIncludesMe()) {
|
||||
if (participantsIncludesMe()) {
|
||||
chat.readOnly = true
|
||||
}
|
||||
|
||||
@@ -364,7 +338,7 @@ const processMessage = async(
|
||||
case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
|
||||
case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
|
||||
participants = message.messageStubParameters || []
|
||||
if(participantsIncludesMe()) {
|
||||
if (participantsIncludesMe()) {
|
||||
chat.readOnly = false
|
||||
}
|
||||
|
||||
@@ -415,7 +389,6 @@ const processMessage = async(
|
||||
emitGroupRequestJoin(participant, action, method)
|
||||
break
|
||||
}
|
||||
|
||||
} /* else if(content?.pollUpdateMessage) {
|
||||
const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
|
||||
// we need to fetch the poll creation message to get the poll enc key
|
||||
@@ -466,7 +439,7 @@ const processMessage = async(
|
||||
}
|
||||
} */
|
||||
|
||||
if(Object.keys(chat).length > 1) {
|
||||
if (Object.keys(chat).length > 1) {
|
||||
ev.emit('chats.update', [chat])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,39 @@
|
||||
import { chunk } from 'lodash'
|
||||
import { KEY_BUNDLE_TYPE } from '../Defaults'
|
||||
import { SignalRepository } from '../Types'
|
||||
import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth'
|
||||
import { assertNodeErrorFree, BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, jidDecode, JidWithDevice, S_WHATSAPP_NET } from '../WABinary'
|
||||
import {
|
||||
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 { Curve, generateSignalPubKey } from './crypto'
|
||||
import { encodeBigEndian } from './generics'
|
||||
|
||||
export const createSignalIdentity = (
|
||||
wid: string,
|
||||
accountSignatureKey: Uint8Array
|
||||
): SignalIdentity => {
|
||||
export const createSignalIdentity = (wid: string, accountSignatureKey: Uint8Array): SignalIdentity => {
|
||||
return {
|
||||
identifier: { name: wid, deviceId: 0 },
|
||||
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[] = []
|
||||
for(let id = min; id < limit;id++) {
|
||||
for (let id = min; id < limit; id++) {
|
||||
idList.push(id.toString())
|
||||
}
|
||||
|
||||
@@ -30,9 +44,9 @@ export const generateOrGetPreKeys = (creds: AuthenticationCreds, range: number)
|
||||
const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId
|
||||
const remaining = range - avaliable
|
||||
const lastPreKeyId = creds.nextPreKeyId + remaining - 1
|
||||
const newPreKeys: { [id: number]: KeyPair } = { }
|
||||
if(remaining > 0) {
|
||||
for(let i = creds.nextPreKeyId;i <= lastPreKeyId;i++) {
|
||||
const newPreKeys: { [id: number]: KeyPair } = {}
|
||||
if (remaining > 0) {
|
||||
for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
|
||||
newPreKeys[i] = Curve.generateKeyPair()
|
||||
}
|
||||
}
|
||||
@@ -40,46 +54,40 @@ export const generateOrGetPreKeys = (creds: AuthenticationCreds, range: number)
|
||||
return {
|
||||
newPreKeys,
|
||||
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',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{ tag: 'id', attrs: { }, content: encodeBigEndian(key.keyId, 3) },
|
||||
{ tag: 'value', attrs: { }, content: key.keyPair.public },
|
||||
{ tag: 'signature', attrs: { }, content: key.signature }
|
||||
{ tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
|
||||
{ tag: 'value', attrs: {}, content: key.keyPair.public },
|
||||
{ tag: 'signature', attrs: {}, content: key.signature }
|
||||
]
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
export const xmppPreKey = (pair: KeyPair, id: number): BinaryNode => (
|
||||
{
|
||||
export const xmppPreKey = (pair: KeyPair, id: number): BinaryNode => ({
|
||||
tag: 'key',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{ tag: 'id', attrs: { }, content: encodeBigEndian(id, 3) },
|
||||
{ tag: 'value', attrs: { }, content: pair.public }
|
||||
{ tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
|
||||
{ tag: 'value', attrs: {}, content: pair.public }
|
||||
]
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
export const parseAndInjectE2ESessions = async(
|
||||
node: BinaryNode,
|
||||
repository: SignalRepository
|
||||
) => {
|
||||
const extractKey = (key: BinaryNode) => (
|
||||
key ? ({
|
||||
export const parseAndInjectE2ESessions = async (node: BinaryNode, repository: SignalRepository) => {
|
||||
const extractKey = (key: BinaryNode) =>
|
||||
key
|
||||
? {
|
||||
keyId: getBinaryNodeChildUInt(key, 'id', 3)!,
|
||||
publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')!),
|
||||
signature: getBinaryNodeChildBuffer(key, 'signature')!,
|
||||
}) : undefined
|
||||
)
|
||||
signature: getBinaryNodeChildBuffer(key, 'signature')!
|
||||
}
|
||||
: undefined
|
||||
const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user')
|
||||
for(const node of nodes) {
|
||||
for (const node of nodes) {
|
||||
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
|
||||
const chunkSize = 100
|
||||
const chunks = chunk(nodes, chunkSize)
|
||||
for(const nodesChunk of chunks) {
|
||||
for (const nodesChunk of chunks) {
|
||||
await Promise.all(
|
||||
nodesChunk.map(
|
||||
async node => {
|
||||
nodesChunk.map(async node => {
|
||||
const signedKey = getBinaryNodeChild(node, 'skey')!
|
||||
const key = getBinaryNodeChild(node, 'key')!
|
||||
const identity = getBinaryNodeChildBuffer(node, 'identity')!
|
||||
@@ -109,8 +116,7 @@ export const parseAndInjectE2ESessions = async(
|
||||
preKey: extractKey(key)!
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -120,14 +126,13 @@ export const extractDeviceJids = (result: USyncQueryResultList[], myJid: string,
|
||||
|
||||
const extracted: JidWithDevice[] = []
|
||||
|
||||
|
||||
for(const userResult of result) {
|
||||
const { devices, id } = userResult as { devices: ParsedDeviceInfo, id: string }
|
||||
for (const userResult of result) {
|
||||
const { devices, id } = userResult as { devices: ParsedDeviceInfo; id: string }
|
||||
const { user } = jidDecode(id)!
|
||||
const deviceList = devices?.deviceList as DeviceListData[]
|
||||
if(Array.isArray(deviceList)) {
|
||||
for(const { id: device, keyIndex } of deviceList) {
|
||||
if(
|
||||
if (Array.isArray(deviceList)) {
|
||||
for (const { id: device, keyIndex } of deviceList) {
|
||||
if (
|
||||
(!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
|
||||
(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
|
||||
* @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 update: Partial<AuthenticationCreds> = {
|
||||
@@ -160,7 +165,7 @@ export const getNextPreKeys = async({ creds, keys }: AuthenticationState, count:
|
||||
return { update, preKeys }
|
||||
}
|
||||
|
||||
export const getNextPreKeysNode = async(state: AuthenticationState, count: number) => {
|
||||
export const getNextPreKeysNode = async (state: AuthenticationState, count: number) => {
|
||||
const { creds } = state
|
||||
const { update, preKeys } = await getNextPreKeys(state, count)
|
||||
|
||||
@@ -169,13 +174,13 @@ export const getNextPreKeysNode = async(state: AuthenticationState, count: numbe
|
||||
attrs: {
|
||||
xmlns: 'encrypt',
|
||||
type: 'set',
|
||||
to: S_WHATSAPP_NET,
|
||||
to: S_WHATSAPP_NET
|
||||
},
|
||||
content: [
|
||||
{ tag: 'registration', attrs: { }, content: encodeBigEndian(creds.registrationId) },
|
||||
{ tag: 'type', attrs: { }, content: KEY_BUNDLE_TYPE },
|
||||
{ tag: 'identity', attrs: { }, content: creds.signedIdentityKey.public },
|
||||
{ tag: 'list', attrs: { }, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
|
||||
{ tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
|
||||
{ tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
|
||||
{ tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
|
||||
{ tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
|
||||
xmppSignedPreKey(creds.signedPreKey)
|
||||
]
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ const fileLocks = new Map<string, Mutex>()
|
||||
// Get or create a mutex for a specific file path
|
||||
const getFileLock = (path: string): Mutex => {
|
||||
let mutex = fileLocks.get(path)
|
||||
if(!mutex) {
|
||||
if (!mutex) {
|
||||
mutex = new 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.
|
||||
* 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
|
||||
const writeData = async(data: any, file: string) => {
|
||||
const writeData = async (data: any, file: string) => {
|
||||
const filePath = join(folder, fixFileName(file)!)
|
||||
const mutex = getFileLock(filePath)
|
||||
|
||||
return mutex.acquire().then(async(release) => {
|
||||
return mutex.acquire().then(async release => {
|
||||
try {
|
||||
await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer))
|
||||
} 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 {
|
||||
const filePath = join(folder, fixFileName(file)!)
|
||||
const mutex = getFileLock(filePath)
|
||||
|
||||
return await mutex.acquire().then(async(release) => {
|
||||
return await mutex.acquire().then(async release => {
|
||||
try {
|
||||
const data = await readFile(filePath, { encoding: 'utf-8' })
|
||||
return JSON.parse(data, BufferJSON.reviver)
|
||||
@@ -58,32 +60,33 @@ export const useMultiFileAuthState = async(folder: string): Promise<{ state: Aut
|
||||
release()
|
||||
}
|
||||
})
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const removeData = async(file: string) => {
|
||||
const removeData = async (file: string) => {
|
||||
try {
|
||||
const filePath = join(folder, fixFileName(file)!)
|
||||
const mutex = getFileLock(filePath)
|
||||
|
||||
return mutex.acquire().then(async(release) => {
|
||||
return mutex.acquire().then(async release => {
|
||||
try {
|
||||
await unlink(filePath)
|
||||
} catch{
|
||||
} catch {
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
})
|
||||
} catch{
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const folderInfo = await stat(folder).catch(() => { })
|
||||
if(folderInfo) {
|
||||
if(!folderInfo.isDirectory()) {
|
||||
throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
|
||||
const folderInfo = await stat(folder).catch(() => {})
|
||||
if (folderInfo) {
|
||||
if (!folderInfo.isDirectory()) {
|
||||
throw new Error(
|
||||
`found something that is not a directory at ${folder}, either delete it or specify a different location`
|
||||
)
|
||||
}
|
||||
} else {
|
||||
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 creds: AuthenticationCreds = await readData('creds.json') || initAuthCreds()
|
||||
const creds: AuthenticationCreds = (await readData('creds.json')) || initAuthCreds()
|
||||
|
||||
return {
|
||||
state: {
|
||||
creds,
|
||||
keys: {
|
||||
get: async(type, ids) => {
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
|
||||
get: async (type, ids) => {
|
||||
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
|
||||
await Promise.all(
|
||||
ids.map(
|
||||
async id => {
|
||||
ids.map(async id => {
|
||||
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)
|
||||
}
|
||||
|
||||
data[id] = value
|
||||
}
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
return data
|
||||
},
|
||||
set: async(data) => {
|
||||
set: async data => {
|
||||
const tasks: Promise<void>[] = []
|
||||
for(const category in data) {
|
||||
for(const id in data[category]) {
|
||||
for (const category in data) {
|
||||
for (const id in data[category]) {
|
||||
const value = data[category][id]
|
||||
const file = `${category}-${id}.json`
|
||||
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')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
|
||||
appVersion: {
|
||||
primary: config.version[0],
|
||||
secondary: config.version[1],
|
||||
tertiary: config.version[2],
|
||||
tertiary: config.version[2]
|
||||
},
|
||||
platform: proto.ClientPayload.UserAgent.Platform.WEB,
|
||||
releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
|
||||
@@ -23,30 +23,29 @@ const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
|
||||
localeLanguageIso6391: 'en',
|
||||
mnc: '000',
|
||||
mcc: '000',
|
||||
localeCountryIso31661Alpha2: config.countryCode,
|
||||
localeCountryIso31661Alpha2: config.countryCode
|
||||
}
|
||||
}
|
||||
|
||||
const PLATFORM_MAP = {
|
||||
'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 => {
|
||||
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]]
|
||||
}
|
||||
|
||||
return { webSubPlatform }
|
||||
}
|
||||
|
||||
|
||||
const getClientPayload = (config: SocketConfig) => {
|
||||
const payload: proto.IClientPayload = {
|
||||
connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
|
||||
connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
|
||||
userAgent: getUserAgent(config),
|
||||
userAgent: getUserAgent(config)
|
||||
}
|
||||
|
||||
payload.webInfo = getWebInfo(config)
|
||||
@@ -54,7 +53,6 @@ const getClientPayload = (config: SocketConfig) => {
|
||||
return payload
|
||||
}
|
||||
|
||||
|
||||
export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
|
||||
const { user, device } = jidDecode(userJid)!
|
||||
const payload: proto.IClientPayload = {
|
||||
@@ -62,7 +60,7 @@ export const generateLoginNode = (userJid: string, config: SocketConfig): proto.
|
||||
passive: false,
|
||||
pull: true,
|
||||
username: +user,
|
||||
device: device,
|
||||
device: device
|
||||
}
|
||||
return proto.ClientPayload.fromObject(payload)
|
||||
}
|
||||
@@ -85,7 +83,7 @@ export const generateRegistrationNode = (
|
||||
const companion: proto.IDeviceProps = {
|
||||
os: config.browser[0],
|
||||
platformType: getPlatformType(config.browser[1]),
|
||||
requireFullSync: config.syncFullHistory,
|
||||
requireFullSync: config.syncFullHistory
|
||||
}
|
||||
|
||||
const companionProto = proto.DeviceProps.encode(companion).finish()
|
||||
@@ -102,8 +100,8 @@ export const generateRegistrationNode = (
|
||||
eIdent: signedIdentityKey.public,
|
||||
eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
|
||||
eSkeyVal: signedPreKey.keyPair.public,
|
||||
eSkeySig: signedPreKey.signature,
|
||||
},
|
||||
eSkeySig: signedPreKey.signature
|
||||
}
|
||||
}
|
||||
|
||||
return proto.ClientPayload.fromObject(registerPayload)
|
||||
@@ -111,7 +109,11 @@ export const generateRegistrationNode = (
|
||||
|
||||
export const configureSuccessfulPairing = (
|
||||
stanza: BinaryNode,
|
||||
{ advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
||||
{
|
||||
advSecretKey,
|
||||
signedIdentityKey,
|
||||
signalIdentities
|
||||
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
||||
) => {
|
||||
const msgId = stanza.attrs.id
|
||||
|
||||
@@ -122,7 +124,7 @@ export const configureSuccessfulPairing = (
|
||||
const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device')
|
||||
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 })
|
||||
}
|
||||
|
||||
@@ -132,20 +134,20 @@ export const configureSuccessfulPairing = (
|
||||
const { details, hmac } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
|
||||
// check HMAC matches
|
||||
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')
|
||||
}
|
||||
|
||||
const account = proto.ADVSignedDeviceIdentity.decode(details!)
|
||||
const { accountSignatureKey, accountSignature, details: deviceDetails } = account
|
||||
// verify the device signature matches
|
||||
const accountMsg = Buffer.concat([ Buffer.from([6, 0]), deviceDetails!, signedIdentityKey.public ])
|
||||
if(!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
|
||||
const accountMsg = Buffer.concat([Buffer.from([6, 0]), deviceDetails!, signedIdentityKey.public])
|
||||
if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
|
||||
throw new Boom('Failed to verify account signature')
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
const identity = createSignalIdentity(jid, accountSignatureKey!)
|
||||
@@ -158,12 +160,12 @@ export const configureSuccessfulPairing = (
|
||||
attrs: {
|
||||
to: S_WHATSAPP_NET,
|
||||
type: 'result',
|
||||
id: msgId,
|
||||
id: msgId
|
||||
},
|
||||
content: [
|
||||
{
|
||||
tag: 'pair-device-sign',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [
|
||||
{
|
||||
tag: 'device-identity',
|
||||
@@ -178,10 +180,7 @@ export const configureSuccessfulPairing = (
|
||||
const authUpdate: Partial<AuthenticationCreds> = {
|
||||
account,
|
||||
me: { id: jid, name: bizName },
|
||||
signalIdentities: [
|
||||
...(signalIdentities || []),
|
||||
identity
|
||||
],
|
||||
signalIdentities: [...(signalIdentities || []), identity],
|
||||
platform: platformNode?.attrs.name
|
||||
}
|
||||
|
||||
@@ -191,18 +190,13 @@ export const configureSuccessfulPairing = (
|
||||
}
|
||||
}
|
||||
|
||||
export const encodeSignedDeviceIdentity = (
|
||||
account: proto.IADVSignedDeviceIdentity,
|
||||
includeSignatureKey: boolean
|
||||
) => {
|
||||
export const encodeSignedDeviceIdentity = (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => {
|
||||
account = { ...account }
|
||||
// set to null if we are not to include the signature key
|
||||
// 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
|
||||
}
|
||||
|
||||
return proto.ADVSignedDeviceIdentity
|
||||
.encode(account)
|
||||
.finish()
|
||||
return proto.ADVSignedDeviceIdentity.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)
|
||||
|
||||
export const decompressingIfRequired = async(buffer: Buffer) => {
|
||||
if(2 & buffer.readUInt8()) {
|
||||
export const decompressingIfRequired = async (buffer: Buffer) => {
|
||||
if (2 & buffer.readUInt8()) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -24,7 +25,7 @@ export const decodeDecompressedBinaryNode = (
|
||||
const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts
|
||||
|
||||
const checkEOS = (length: number) => {
|
||||
if(indexRef.index + length > buffer.length) {
|
||||
if (indexRef.index + length > buffer.length) {
|
||||
throw new Error('end of stream')
|
||||
}
|
||||
}
|
||||
@@ -54,7 +55,7 @@ export const decodeDecompressedBinaryNode = (
|
||||
const readInt = (n: number, littleEndian = false) => {
|
||||
checkEOS(n)
|
||||
let val = 0
|
||||
for(let i = 0; i < n; i++) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const shift = littleEndian ? i : n - 1 - i
|
||||
val |= next() << (shift * 8)
|
||||
}
|
||||
@@ -68,7 +69,7 @@ export const decodeDecompressedBinaryNode = (
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -76,7 +77,7 @@ export const decodeDecompressedBinaryNode = (
|
||||
}
|
||||
|
||||
const unpackNibble = (value: number) => {
|
||||
if(value >= 0 && value <= 9) {
|
||||
if (value >= 0 && value <= 9) {
|
||||
return '0'.charCodeAt(0) + value
|
||||
}
|
||||
|
||||
@@ -93,9 +94,9 @@ export const decodeDecompressedBinaryNode = (
|
||||
}
|
||||
|
||||
const unpackByte = (tag: number, value: number) => {
|
||||
if(tag === TAGS.NIBBLE_8) {
|
||||
if (tag === TAGS.NIBBLE_8) {
|
||||
return unpackNibble(value)
|
||||
} else if(tag === TAGS.HEX_8) {
|
||||
} else if (tag === TAGS.HEX_8) {
|
||||
return unpackHex(value)
|
||||
} else {
|
||||
throw new Error('unknown tag: ' + tag)
|
||||
@@ -106,13 +107,13 @@ export const decodeDecompressedBinaryNode = (
|
||||
const startByte = readByte()
|
||||
let value = ''
|
||||
|
||||
for(let i = 0; i < (startByte & 127); i++) {
|
||||
for (let i = 0; i < (startByte & 127); i++) {
|
||||
const curByte = readByte()
|
||||
value += String.fromCharCode(unpackByte(tag, (curByte & 0xf0) >> 4))
|
||||
value += String.fromCharCode(unpackByte(tag, curByte & 0x0f))
|
||||
}
|
||||
|
||||
if(startByte >> 7 !== 0) {
|
||||
if (startByte >> 7 !== 0) {
|
||||
value = value.slice(0, -1)
|
||||
}
|
||||
|
||||
@@ -139,7 +140,7 @@ export const decodeDecompressedBinaryNode = (
|
||||
const readJidPair = () => {
|
||||
const i = readString(readByte())
|
||||
const j = readString(readByte())
|
||||
if(j) {
|
||||
if (j) {
|
||||
return (i || '') + '@' + j
|
||||
}
|
||||
|
||||
@@ -153,15 +154,11 @@ export const decodeDecompressedBinaryNode = (
|
||||
const device = readByte()
|
||||
const user = readString(readByte())
|
||||
|
||||
return jidEncode(
|
||||
user,
|
||||
domainType === 0 || domainType === 128 ? 's.whatsapp.net' : 'lid',
|
||||
device
|
||||
)
|
||||
return jidEncode(user, domainType === 0 || domainType === 128 ? 's.whatsapp.net' : 'lid', device)
|
||||
}
|
||||
|
||||
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] || ''
|
||||
}
|
||||
|
||||
@@ -194,7 +191,7 @@ export const decodeDecompressedBinaryNode = (
|
||||
const readList = (tag: number) => {
|
||||
const items: BinaryNode[] = []
|
||||
const size = readListSize(tag)
|
||||
for(let i = 0;i < size;i++) {
|
||||
for (let i = 0; i < size; i++) {
|
||||
items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef))
|
||||
}
|
||||
|
||||
@@ -203,12 +200,12 @@ export const decodeDecompressedBinaryNode = (
|
||||
|
||||
const getTokenDouble = (index1: number, index2: number) => {
|
||||
const dict = DOUBLE_BYTE_TOKENS[index1]
|
||||
if(!dict) {
|
||||
if (!dict) {
|
||||
throw new Error(`Invalid double token dict (${index1})`)
|
||||
}
|
||||
|
||||
const value = dict[index2]
|
||||
if(typeof value === 'undefined') {
|
||||
if (typeof value === 'undefined') {
|
||||
throw new Error(`Invalid double token (${index2})`)
|
||||
}
|
||||
|
||||
@@ -217,28 +214,28 @@ export const decodeDecompressedBinaryNode = (
|
||||
|
||||
const listSize = readListSize(readByte())
|
||||
const header = readString(readByte())
|
||||
if(!listSize || !header.length) {
|
||||
if (!listSize || !header.length) {
|
||||
throw new Error('invalid node')
|
||||
}
|
||||
|
||||
const attrs: BinaryNode['attrs'] = { }
|
||||
const attrs: BinaryNode['attrs'] = {}
|
||||
let data: BinaryNode['content']
|
||||
if(listSize === 0 || !header) {
|
||||
if (listSize === 0 || !header) {
|
||||
throw new Error('invalid node')
|
||||
}
|
||||
|
||||
// read the attributes in
|
||||
const attributesLength = (listSize - 1) >> 1
|
||||
for(let i = 0; i < attributesLength; i++) {
|
||||
for (let i = 0; i < attributesLength; i++) {
|
||||
const key = readString(readByte())
|
||||
const value = readString(readByte())
|
||||
|
||||
attrs[key] = value
|
||||
}
|
||||
|
||||
if(listSize % 2 === 0) {
|
||||
if (listSize % 2 === 0) {
|
||||
const tag = readByte()
|
||||
if(isListTag(tag)) {
|
||||
if (isListTag(tag)) {
|
||||
data = readList(tag)
|
||||
} else {
|
||||
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)
|
||||
return decodeDecompressedBinaryNode(decompBuff, constants)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import * as constants from './constants'
|
||||
import { FullJid, jidDecode } from './jid-utils'
|
||||
import type { BinaryNode, BinaryNodeCodingOptions } from './types'
|
||||
@@ -22,14 +21,14 @@ const encodeBinaryNodeInner = (
|
||||
const pushByte = (value: number) => buffer.push(value & 0xff)
|
||||
|
||||
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
|
||||
buffer.push((value >> (curShift * 8)) & 0xff)
|
||||
}
|
||||
}
|
||||
|
||||
const pushBytes = (bytes: Uint8Array | Buffer | number[]) => {
|
||||
for(const b of bytes) {
|
||||
for (const b of bytes) {
|
||||
buffer.push(b)
|
||||
}
|
||||
}
|
||||
@@ -38,18 +37,16 @@ const encodeBinaryNodeInner = (
|
||||
pushBytes([(value >> 8) & 0xff, value & 0xff])
|
||||
}
|
||||
|
||||
const pushInt20 = (value: number) => (
|
||||
pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff])
|
||||
)
|
||||
const pushInt20 = (value: number) => pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff])
|
||||
const writeByteLength = (length: number) => {
|
||||
if(length >= 4294967296) {
|
||||
if (length >= 4294967296) {
|
||||
throw new Error('string too large to encode: ' + length)
|
||||
}
|
||||
|
||||
if(length >= 1 << 20) {
|
||||
if (length >= 1 << 20) {
|
||||
pushByte(TAGS.BINARY_32)
|
||||
pushInt(length, 4) // 32 bit integer
|
||||
} else if(length >= 256) {
|
||||
} else if (length >= 256) {
|
||||
pushByte(TAGS.BINARY_20)
|
||||
pushInt20(length)
|
||||
} else {
|
||||
@@ -59,20 +56,20 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
|
||||
const writeStringRaw = (str: string) => {
|
||||
const bytes = Buffer.from (str, 'utf-8')
|
||||
const bytes = Buffer.from(str, 'utf-8')
|
||||
writeByteLength(bytes.length)
|
||||
pushBytes(bytes)
|
||||
}
|
||||
|
||||
const writeJid = ({ domainType, device, user, server }: FullJid) => {
|
||||
if(typeof device !== 'undefined') {
|
||||
if (typeof device !== 'undefined') {
|
||||
pushByte(TAGS.AD_JID)
|
||||
pushByte(domainType || 0)
|
||||
pushByte(device || 0)
|
||||
writeString(user)
|
||||
} else {
|
||||
pushByte(TAGS.JID_PAIR)
|
||||
if(user.length) {
|
||||
if (user.length) {
|
||||
writeString(user)
|
||||
} else {
|
||||
pushByte(TAGS.LIST_EMPTY)
|
||||
@@ -91,7 +88,7 @@ const encodeBinaryNodeInner = (
|
||||
case '\0':
|
||||
return 15
|
||||
default:
|
||||
if(char >= '0' && char <= '9') {
|
||||
if (char >= '0' && char <= '9') {
|
||||
return char.charCodeAt(0) - '0'.charCodeAt(0)
|
||||
}
|
||||
|
||||
@@ -100,19 +97,19 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
|
||||
const packHex = (char: string) => {
|
||||
if(char >= '0' && char <= '9') {
|
||||
if (char >= '0' && char <= '9') {
|
||||
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)
|
||||
}
|
||||
|
||||
if(char >= 'a' && char <= 'f') {
|
||||
if (char >= 'a' && char <= 'f') {
|
||||
return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0)
|
||||
}
|
||||
|
||||
if(char === '\0') {
|
||||
if (char === '\0') {
|
||||
return 15
|
||||
}
|
||||
|
||||
@@ -120,14 +117,14 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
|
||||
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')
|
||||
}
|
||||
|
||||
pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
|
||||
|
||||
let roundedLength = Math.ceil(str.length / 2.0)
|
||||
if(str.length % 2 !== 0) {
|
||||
if (str.length % 2 !== 0) {
|
||||
roundedLength |= 128
|
||||
}
|
||||
|
||||
@@ -140,23 +137,23 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
|
||||
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]))
|
||||
}
|
||||
|
||||
if(str.length % 2 !== 0) {
|
||||
if (str.length % 2 !== 0) {
|
||||
pushByte(packBytePair(str[str.length - 1], '\x00'))
|
||||
}
|
||||
}
|
||||
|
||||
const isNibble = (str?: string) => {
|
||||
if(!str || str.length > TAGS.PACKED_MAX) {
|
||||
if (!str || str.length > TAGS.PACKED_MAX) {
|
||||
return false
|
||||
}
|
||||
|
||||
for(const char of str) {
|
||||
for (const char of str) {
|
||||
const isInNibbleRange = char >= '0' && char <= '9'
|
||||
if(!isInNibbleRange && char !== '-' && char !== '.') {
|
||||
if (!isInNibbleRange && char !== '-' && char !== '.') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -165,13 +162,13 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
|
||||
const isHex = (str?: string) => {
|
||||
if(!str || str.length > TAGS.PACKED_MAX) {
|
||||
if (!str || str.length > TAGS.PACKED_MAX) {
|
||||
return false
|
||||
}
|
||||
|
||||
for(const char of str) {
|
||||
for (const char of str) {
|
||||
const isInNibbleRange = char >= '0' && char <= '9'
|
||||
if(!isInNibbleRange && !(char >= 'A' && char <= 'F')) {
|
||||
if (!isInNibbleRange && !(char >= 'A' && char <= 'F')) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -180,25 +177,25 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
|
||||
const writeString = (str?: string) => {
|
||||
if(str === undefined || str === null) {
|
||||
if (str === undefined || str === null) {
|
||||
pushByte(TAGS.LIST_EMPTY)
|
||||
return
|
||||
}
|
||||
|
||||
const tokenIndex = TOKEN_MAP[str]
|
||||
if(tokenIndex) {
|
||||
if(typeof tokenIndex.dict === 'number') {
|
||||
if (tokenIndex) {
|
||||
if (typeof tokenIndex.dict === 'number') {
|
||||
pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
|
||||
}
|
||||
|
||||
pushByte(tokenIndex.index)
|
||||
} else if(isNibble(str)) {
|
||||
} else if (isNibble(str)) {
|
||||
writePackedBytes(str, 'nibble')
|
||||
} else if(isHex(str)) {
|
||||
} else if (isHex(str)) {
|
||||
writePackedBytes(str, 'hex')
|
||||
} else if(str) {
|
||||
} else if (str) {
|
||||
const decodedJid = jidDecode(str)
|
||||
if(decodedJid) {
|
||||
if (decodedJid) {
|
||||
writeJid(decodedJid)
|
||||
} else {
|
||||
writeStringRaw(str)
|
||||
@@ -207,9 +204,9 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
|
||||
const writeListStart = (listSize: number) => {
|
||||
if(listSize === 0) {
|
||||
if (listSize === 0) {
|
||||
pushByte(TAGS.LIST_EMPTY)
|
||||
} else if(listSize < 256) {
|
||||
} else if (listSize < 256) {
|
||||
pushBytes([TAGS.LIST_8, listSize])
|
||||
} else {
|
||||
pushByte(TAGS.LIST_16)
|
||||
@@ -217,37 +214,36 @@ const encodeBinaryNodeInner = (
|
||||
}
|
||||
}
|
||||
|
||||
if(!tag) {
|
||||
if (!tag) {
|
||||
throw new Error('Invalid node: tag cannot be undefined')
|
||||
}
|
||||
|
||||
const validAttributes = Object.keys(attrs || {}).filter(k => (
|
||||
typeof attrs[k] !== 'undefined' && attrs[k] !== null
|
||||
))
|
||||
const validAttributes = Object.keys(attrs || {}).filter(k => typeof attrs[k] !== 'undefined' && attrs[k] !== null)
|
||||
|
||||
writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0))
|
||||
writeString(tag)
|
||||
|
||||
for(const key of validAttributes) {
|
||||
if(typeof attrs[key] === 'string') {
|
||||
for (const key of validAttributes) {
|
||||
if (typeof attrs[key] === 'string') {
|
||||
writeString(key)
|
||||
writeString(attrs[key])
|
||||
}
|
||||
}
|
||||
|
||||
if(typeof content === 'string') {
|
||||
if (typeof content === 'string') {
|
||||
writeString(content)
|
||||
} else if(Buffer.isBuffer(content) || content instanceof Uint8Array) {
|
||||
} else if (Buffer.isBuffer(content) || content instanceof Uint8Array) {
|
||||
writeByteLength(content.length)
|
||||
pushBytes(content)
|
||||
} else if(Array.isArray(content)) {
|
||||
const validContent = content.filter(item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string')
|
||||
} else if (Array.isArray(content)) {
|
||||
const validContent = content.filter(
|
||||
item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string')
|
||||
)
|
||||
writeListStart(validContent.length)
|
||||
for(const item of validContent) {
|
||||
for (const item of validContent) {
|
||||
encodeBinaryNodeInner(item, opts, buffer)
|
||||
}
|
||||
} else if(typeof content === 'undefined') {
|
||||
} else if (typeof content === 'undefined') {
|
||||
// do nothing
|
||||
} else {
|
||||
throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
|
||||
|
||||
@@ -5,7 +5,7 @@ import { BinaryNode } from './types'
|
||||
// some extra useful utilities
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export const getBinaryNodeChildren = (node: BinaryNode | undefined, childTag: st
|
||||
}
|
||||
|
||||
export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
|
||||
if(Array.isArray(content)) {
|
||||
if (Array.isArray(content)) {
|
||||
return content
|
||||
}
|
||||
|
||||
@@ -21,37 +21,37 @@ export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
export const getBinaryNodeChildBuffer = (node: BinaryNode | undefined, childTag: string) => {
|
||||
const child = getBinaryNodeChild(node, childTag)?.content
|
||||
if(Buffer.isBuffer(child) || child instanceof Uint8Array) {
|
||||
if (Buffer.isBuffer(child) || child instanceof Uint8Array) {
|
||||
return child
|
||||
}
|
||||
}
|
||||
|
||||
export const getBinaryNodeChildString = (node: BinaryNode | undefined, childTag: string) => {
|
||||
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')
|
||||
} else if(typeof child === 'string') {
|
||||
} else if (typeof child === 'string') {
|
||||
return child
|
||||
}
|
||||
}
|
||||
|
||||
export const getBinaryNodeChildUInt = (node: BinaryNode, childTag: string, length: number) => {
|
||||
const buff = getBinaryNodeChildBuffer(node, childTag)
|
||||
if(buff) {
|
||||
if (buff) {
|
||||
return bufferToUInt(buff, length)
|
||||
}
|
||||
}
|
||||
|
||||
export const assertNodeErrorFree = (node: BinaryNode) => {
|
||||
const errNode = getBinaryNodeChild(node, 'error')
|
||||
if(errNode) {
|
||||
if (errNode) {
|
||||
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.name || attrs.config_code] = attrs.value || attrs.config_value
|
||||
return dict
|
||||
}, { } as { [_: string]: string }
|
||||
},
|
||||
{} as { [_: string]: string }
|
||||
)
|
||||
return dict
|
||||
}
|
||||
|
||||
export const getBinaryNodeMessages = ({ content }: BinaryNode) => {
|
||||
const msgs: proto.WebMessageInfo[] = []
|
||||
if(Array.isArray(content)) {
|
||||
for(const item of content) {
|
||||
if(item.tag === 'message') {
|
||||
if (Array.isArray(content)) {
|
||||
for (const item of content) {
|
||||
if (item.tag === 'message') {
|
||||
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) {
|
||||
let a = 0
|
||||
for(let i = 0; i < t; i++) {
|
||||
for (let i = 0; i < t; i++) {
|
||||
a = 256 * a + e[i]
|
||||
}
|
||||
|
||||
@@ -92,20 +93,20 @@ function bufferToUInt(e: Uint8Array | Buffer, t: number) {
|
||||
const tabs = (n: number) => '\t'.repeat(n)
|
||||
|
||||
export function binaryNodeToString(node: BinaryNode | BinaryNode['content'], i = 0) {
|
||||
if(!node) {
|
||||
if (!node) {
|
||||
return node
|
||||
}
|
||||
|
||||
if(typeof node === 'string') {
|
||||
if (typeof node === 'string') {
|
||||
return tabs(i) + node
|
||||
}
|
||||
|
||||
if(node instanceof Uint8Array) {
|
||||
if (node instanceof Uint8Array) {
|
||||
return tabs(i) + Buffer.from(node).toString('hex')
|
||||
}
|
||||
|
||||
if(Array.isArray(node)) {
|
||||
return node.map((x) => tabs(i + 1) + binaryNodeToString(x, i + 1)).join('\n')
|
||||
if (Array.isArray(node)) {
|
||||
return node.map(x => tabs(i + 1) + binaryNodeToString(x, i + 1)).join('\n')
|
||||
}
|
||||
|
||||
const children = binaryNodeToString(node.content, i + 1)
|
||||
|
||||
@@ -17,14 +17,13 @@ export type FullJid = JidWithDevice & {
|
||||
domainType?: number
|
||||
}
|
||||
|
||||
|
||||
export const jidEncode = (user: string | number | null, server: JidServer, device?: number, agent?: number) => {
|
||||
return `${user || ''}${!!agent ? `_${agent}` : ''}${!!device ? `:${device}` : ''}@${server}`
|
||||
}
|
||||
|
||||
export const jidDecode = (jid: string | undefined): FullJid | undefined => {
|
||||
const sepIdx = typeof jid === 'string' ? jid.indexOf('@') : -1
|
||||
if(sepIdx < 0) {
|
||||
if (sepIdx < 0) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -43,34 +42,33 @@ export const jidDecode = (jid: string | undefined): FullJid | undefined => {
|
||||
}
|
||||
|
||||
/** 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
|
||||
)
|
||||
/** 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 */
|
||||
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 */
|
||||
export const isLidUser = (jid: string | undefined) => (jid?.endsWith('@lid'))
|
||||
export const isLidUser = (jid: string | undefined) => jid?.endsWith('@lid')
|
||||
/** 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 */
|
||||
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 */
|
||||
export const isJidStatusBroadcast = (jid: string) => jid === 'status@broadcast'
|
||||
/** 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}$/
|
||||
|
||||
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) => {
|
||||
const result = jidDecode(jid)
|
||||
if(!result) {
|
||||
if (!result) {
|
||||
return ''
|
||||
}
|
||||
|
||||
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 { 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)
|
||||
|
||||
@@ -10,12 +19,10 @@ export const encodeWAM = (binaryInfo: BinaryInfo) => {
|
||||
encodeEvents(binaryInfo)
|
||||
|
||||
console.log(binaryInfo.buffer)
|
||||
const totalSize = binaryInfo.buffer
|
||||
.map((a) => a.length)
|
||||
.reduce((a, b) => a + b)
|
||||
const totalSize = binaryInfo.buffer.map(a => a.length).reduce((a, b) => a + b)
|
||||
const buffer = Buffer.alloc(totalSize)
|
||||
let offset = 0
|
||||
for(const buffer_ of binaryInfo.buffer) {
|
||||
for (const buffer_ of binaryInfo.buffer) {
|
||||
buffer_.copy(buffer, offset)
|
||||
offset += buffer_.length
|
||||
}
|
||||
@@ -34,11 +41,11 @@ function encodeWAMHeader(binaryInfo: BinaryInfo) {
|
||||
binaryInfo.buffer.push(headerBuffer)
|
||||
}
|
||||
|
||||
function encodeGlobalAttributes(binaryInfo: BinaryInfo, globals: {[key: string]: Value}) {
|
||||
for(const [key, _value] of Object.entries(globals)) {
|
||||
function encodeGlobalAttributes(binaryInfo: BinaryInfo, globals: { [key: string]: Value }) {
|
||||
for (const [key, _value] of Object.entries(globals)) {
|
||||
const id = WEB_GLOBALS.find(a => a?.name === key)!.id
|
||||
let value = _value
|
||||
if(typeof value === 'boolean') {
|
||||
if (typeof value === 'boolean') {
|
||||
value = value ? 1 : 0
|
||||
}
|
||||
|
||||
@@ -47,30 +54,27 @@ function encodeGlobalAttributes(binaryInfo: BinaryInfo, globals: {[key: string]:
|
||||
}
|
||||
|
||||
function encodeEvents(binaryInfo: BinaryInfo) {
|
||||
for(const [
|
||||
name,
|
||||
{ props, globals },
|
||||
] of binaryInfo.events.map((a) => Object.entries(a)[0])) {
|
||||
for (const [name, { props, globals }] of binaryInfo.events.map(a => Object.entries(a)[0])) {
|
||||
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)
|
||||
|
||||
let extended = false
|
||||
|
||||
for(const [, value] of props_) {
|
||||
for (const [, value] of props_) {
|
||||
extended ||= value !== null
|
||||
}
|
||||
|
||||
const eventFlag = extended ? FLAG_EVENT : FLAG_EVENT | FLAG_EXTENDED
|
||||
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 id = (event.props)[key][0]
|
||||
extended = i < (props_.length - 1)
|
||||
const id = event.props[key][0]
|
||||
extended = i < props_.length - 1
|
||||
let value = _value
|
||||
if(typeof value === 'boolean') {
|
||||
if (typeof value === 'boolean') {
|
||||
value = value ? 1 : 0
|
||||
}
|
||||
|
||||
@@ -80,34 +84,33 @@ function encodeEvents(binaryInfo: BinaryInfo) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function serializeData(key: number, value: Value, flag: number): Buffer {
|
||||
const bufferLength = getHeaderBitLength(key)
|
||||
let buffer: Buffer
|
||||
let offset = 0
|
||||
if(value === null) {
|
||||
if(flag === FLAG_GLOBAL) {
|
||||
if (value === null) {
|
||||
if (flag === FLAG_GLOBAL) {
|
||||
buffer = Buffer.alloc(bufferLength)
|
||||
offset = serializeHeader(buffer, offset, key, flag)
|
||||
return buffer
|
||||
}
|
||||
} else if(typeof value === 'number' && Number.isInteger(value)) {
|
||||
} else if (typeof value === 'number' && Number.isInteger(value)) {
|
||||
// is number
|
||||
if(value === 0 || value === 1) {
|
||||
if (value === 0 || value === 1) {
|
||||
buffer = Buffer.alloc(bufferLength)
|
||||
offset = serializeHeader(buffer, offset, key, flag | ((value + 1) << 4))
|
||||
return buffer
|
||||
} else if(-128 <= value && value < 128) {
|
||||
} else if (-128 <= value && value < 128) {
|
||||
buffer = Buffer.alloc(bufferLength + 1)
|
||||
offset = serializeHeader(buffer, offset, key, flag | (3 << 4))
|
||||
buffer.writeInt8(value, offset)
|
||||
return buffer
|
||||
} else if(-32768 <= value && value < 32768) {
|
||||
} else if (-32768 <= value && value < 32768) {
|
||||
buffer = Buffer.alloc(bufferLength + 2)
|
||||
offset = serializeHeader(buffer, offset, key, flag | (4 << 4))
|
||||
buffer.writeInt16LE(value, offset)
|
||||
return buffer
|
||||
} else if(-2147483648 <= value && value < 2147483648) {
|
||||
} else if (-2147483648 <= value && value < 2147483648) {
|
||||
buffer = Buffer.alloc(bufferLength + 4)
|
||||
offset = serializeHeader(buffer, offset, key, flag | (5 << 4))
|
||||
buffer.writeInt32LE(value, offset)
|
||||
@@ -118,20 +121,20 @@ function serializeData(key: number, value: Value, flag: number): Buffer {
|
||||
buffer.writeDoubleLE(value, offset)
|
||||
return buffer
|
||||
}
|
||||
} else if(typeof value === 'number') {
|
||||
} else if (typeof value === 'number') {
|
||||
// is float
|
||||
buffer = Buffer.alloc(bufferLength + 8)
|
||||
offset = serializeHeader(buffer, offset, key, flag | (7 << 4))
|
||||
buffer.writeDoubleLE(value, offset)
|
||||
return buffer
|
||||
} else if(typeof value === 'string') {
|
||||
} else if (typeof value === 'string') {
|
||||
// is string
|
||||
const utf8Bytes = Buffer.byteLength(value, 'utf8')
|
||||
if(utf8Bytes < 256) {
|
||||
if (utf8Bytes < 256) {
|
||||
buffer = Buffer.alloc(bufferLength + 1 + utf8Bytes)
|
||||
offset = serializeHeader(buffer, offset, key, flag | (8 << 4))
|
||||
buffer.writeUint8(utf8Bytes, offset++)
|
||||
} else if(utf8Bytes < 65536) {
|
||||
} else if (utf8Bytes < 65536) {
|
||||
buffer = Buffer.alloc(bufferLength + 2 + utf8Bytes)
|
||||
offset = serializeHeader(buffer, offset, key, flag | (9 << 4))
|
||||
buffer.writeUInt16LE(utf8Bytes, offset)
|
||||
@@ -150,13 +153,8 @@ function serializeData(key: number, value: Value, flag: number): Buffer {
|
||||
throw 'missing'
|
||||
}
|
||||
|
||||
function serializeHeader(
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
key: number,
|
||||
flag: number
|
||||
) {
|
||||
if(key < 256) {
|
||||
function serializeHeader(buffer: Buffer, offset: number, key: number, flag: number) {
|
||||
if (key < 256) {
|
||||
buffer.writeUInt8(flag, offset)
|
||||
offset += 1
|
||||
buffer.writeUInt8(key, offset)
|
||||
|
||||
@@ -8,7 +8,7 @@ export class USyncContactProtocol implements USyncQueryProtocol {
|
||||
getQueryElement(): BinaryNode {
|
||||
return {
|
||||
tag: 'contact',
|
||||
attrs: {},
|
||||
attrs: {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,12 +17,12 @@ export class USyncContactProtocol implements USyncQueryProtocol {
|
||||
return {
|
||||
tag: 'contact',
|
||||
attrs: {},
|
||||
content: user.phone,
|
||||
content: user.phone
|
||||
}
|
||||
}
|
||||
|
||||
parser(node: BinaryNode): boolean {
|
||||
if(node.tag === 'contact') {
|
||||
if (node.tag === 'contact') {
|
||||
assertNodeErrorFree(node)
|
||||
return node?.attrs?.type === 'in'
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ export class USyncDeviceProtocol implements USyncQueryProtocol {
|
||||
return {
|
||||
tag: 'devices',
|
||||
attrs: {
|
||||
version: '2',
|
||||
},
|
||||
version: '2'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,16 +42,16 @@ export class USyncDeviceProtocol implements USyncQueryProtocol {
|
||||
const deviceList: DeviceListData[] = []
|
||||
let keyIndex: KeyIndexData | undefined = undefined
|
||||
|
||||
if(node.tag === 'devices') {
|
||||
if (node.tag === 'devices') {
|
||||
assertNodeErrorFree(node)
|
||||
const deviceListNode = getBinaryNodeChild(node, 'device-list')
|
||||
const keyIndexNode = getBinaryNodeChild(node, 'key-index-list')
|
||||
|
||||
if(Array.isArray(deviceListNode?.content)) {
|
||||
for(const { tag, attrs } of deviceListNode.content) {
|
||||
if (Array.isArray(deviceListNode?.content)) {
|
||||
for (const { tag, attrs } of deviceListNode.content) {
|
||||
const id = +attrs.id
|
||||
const keyIndex = +attrs['key-index']
|
||||
if(tag === 'device') {
|
||||
if (tag === 'device') {
|
||||
deviceList.push({
|
||||
id,
|
||||
keyIndex,
|
||||
@@ -61,7 +61,7 @@ export class USyncDeviceProtocol implements USyncQueryProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
if(keyIndexNode?.tag === 'key-index-list') {
|
||||
if (keyIndexNode?.tag === 'key-index-list') {
|
||||
keyIndex = {
|
||||
timestamp: +keyIndexNode.attrs['ts'],
|
||||
signedKeyIndex: keyIndexNode?.content as Uint8Array,
|
||||
|
||||
@@ -12,7 +12,7 @@ export class USyncDisappearingModeProtocol implements USyncQueryProtocol {
|
||||
getQueryElement(): BinaryNode {
|
||||
return {
|
||||
tag: 'disappearing_mode',
|
||||
attrs: {},
|
||||
attrs: {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,14 +21,14 @@ export class USyncDisappearingModeProtocol implements USyncQueryProtocol {
|
||||
}
|
||||
|
||||
parser(node: BinaryNode): DisappearingModeData | undefined {
|
||||
if(node.tag === 'status') {
|
||||
if (node.tag === 'status') {
|
||||
assertNodeErrorFree(node)
|
||||
const duration: number = +node?.attrs.duration
|
||||
const setAt = new Date(+(node?.attrs.t || 0) * 1000)
|
||||
|
||||
return {
|
||||
duration,
|
||||
setAt,
|
||||
setAt
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ export class USyncStatusProtocol implements USyncQueryProtocol {
|
||||
getQueryElement(): BinaryNode {
|
||||
return {
|
||||
tag: 'status',
|
||||
attrs: {},
|
||||
attrs: {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,23 +21,23 @@ export class USyncStatusProtocol implements USyncQueryProtocol {
|
||||
}
|
||||
|
||||
parser(node: BinaryNode): StatusData | undefined {
|
||||
if(node.tag === 'status') {
|
||||
if (node.tag === 'status') {
|
||||
assertNodeErrorFree(node)
|
||||
let status: string | null = node?.content?.toString() ?? null
|
||||
const setAt = new Date(+(node?.attrs.t || 0) * 1000)
|
||||
if(!status) {
|
||||
if(+node.attrs?.code === 401) {
|
||||
if (!status) {
|
||||
if (+node.attrs?.code === 401) {
|
||||
status = ''
|
||||
} else {
|
||||
status = null
|
||||
}
|
||||
} else if(typeof status === 'string' && status.length === 0) {
|
||||
} else if (typeof status === 'string' && status.length === 0) {
|
||||
status = null
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
setAt,
|
||||
setAt
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
|
||||
getQueryElement(): BinaryNode {
|
||||
return {
|
||||
tag: 'bot',
|
||||
attrs: { },
|
||||
attrs: {},
|
||||
content: [{ tag: 'profile', attrs: { v: '1' } }]
|
||||
}
|
||||
}
|
||||
@@ -34,8 +34,8 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
|
||||
getUserElement(user: USyncUser): BinaryNode {
|
||||
return {
|
||||
tag: 'bot',
|
||||
attrs: { },
|
||||
content: [{ tag: 'profile', attrs: { 'persona_id': user.personaId } }]
|
||||
attrs: {},
|
||||
content: [{ tag: 'profile', attrs: { persona_id: user.personaId } }]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,18 +49,17 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
|
||||
const commands: BotProfileCommand[] = []
|
||||
const prompts: string[] = []
|
||||
|
||||
for(const command of getBinaryNodeChildren(commandsNode, 'command')) {
|
||||
for (const command of getBinaryNodeChildren(commandsNode, 'command')) {
|
||||
commands.push({
|
||||
name: getBinaryNodeChildString(command, 'name')!,
|
||||
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')!}`)
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
isDefault: !!getBinaryNodeChild(profile, 'default'),
|
||||
jid: node.attrs.jid,
|
||||
|
||||
@@ -7,7 +7,7 @@ export class USyncLIDProtocol implements USyncQueryProtocol {
|
||||
getQueryElement(): BinaryNode {
|
||||
return {
|
||||
tag: 'lid',
|
||||
attrs: {},
|
||||
attrs: {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ export class USyncLIDProtocol implements USyncQueryProtocol {
|
||||
}
|
||||
|
||||
parser(node: BinaryNode): string | null {
|
||||
if(node.tag === 'lid') {
|
||||
if (node.tag === 'lid') {
|
||||
return node.attrs.val
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,15 @@ import { USyncQueryProtocol } from '../Types/USync'
|
||||
import { BinaryNode, getBinaryNodeChild } from '../WABinary'
|
||||
import { USyncBotProfileProtocol } from './Protocols/UsyncBotProfileProtocol'
|
||||
import { USyncLIDProtocol } from './Protocols/UsyncLIDProtocol'
|
||||
import { USyncContactProtocol, USyncDeviceProtocol, USyncDisappearingModeProtocol, USyncStatusProtocol } from './Protocols'
|
||||
import {
|
||||
USyncContactProtocol,
|
||||
USyncDeviceProtocol,
|
||||
USyncDisappearingModeProtocol,
|
||||
USyncStatusProtocol
|
||||
} from './Protocols'
|
||||
import { USyncUser } from './USyncUser'
|
||||
|
||||
export type USyncQueryResultList = { [protocol: string]: unknown, id: string }
|
||||
export type USyncQueryResultList = { [protocol: string]: unknown; id: string }
|
||||
|
||||
export type USyncQueryResult = {
|
||||
list: USyncQueryResultList[]
|
||||
@@ -41,18 +46,20 @@ export class USyncQuery {
|
||||
}
|
||||
|
||||
parseUSyncQueryResult(result: BinaryNode): USyncQueryResult | undefined {
|
||||
if(result.attrs.type !== 'result') {
|
||||
if (result.attrs.type !== 'result') {
|
||||
return
|
||||
}
|
||||
|
||||
const protocolMap = Object.fromEntries(this.protocols.map((protocol) => {
|
||||
const protocolMap = Object.fromEntries(
|
||||
this.protocols.map(protocol => {
|
||||
return [protocol.name, protocol.parser]
|
||||
}))
|
||||
})
|
||||
)
|
||||
|
||||
const queryResult: USyncQueryResult = {
|
||||
// TODO: implement errors etc.
|
||||
list: [],
|
||||
sideList: [],
|
||||
sideList: []
|
||||
}
|
||||
|
||||
const usyncNode = getBinaryNodeChild(result, 'usync')
|
||||
@@ -62,18 +69,24 @@ export class USyncQuery {
|
||||
//const resultNode = getBinaryNodeChild(usyncNode, 'result')
|
||||
|
||||
const listNode = getBinaryNodeChild(usyncNode, 'list')
|
||||
if(Array.isArray(listNode?.content) && typeof listNode !== 'undefined') {
|
||||
queryResult.list = listNode.content.map((node) => {
|
||||
if (Array.isArray(listNode?.content) && typeof listNode !== 'undefined') {
|
||||
queryResult.list = listNode.content.map(node => {
|
||||
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 parser = protocolMap[protocol]
|
||||
if(parser) {
|
||||
if (parser) {
|
||||
return [protocol, parser(content)]
|
||||
} else {
|
||||
return [protocol, null]
|
||||
}
|
||||
}).filter(([, b]) => b !== null) as [string, unknown][]) : {}
|
||||
})
|
||||
.filter(([, b]) => b !== null) as [string, unknown][]
|
||||
)
|
||||
: {}
|
||||
return { ...data, id }
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user