chore: fix format

This commit is contained in:
canove
2025-05-28 22:44:21 -03:00
parent eb6c6c8ba9
commit ae0de94307
8 changed files with 994 additions and 897 deletions

View File

@@ -66,6 +66,7 @@
"json": "^11.0.0", "json": "^11.0.0",
"link-preview-js": "^3.0.0", "link-preview-js": "^3.0.0",
"open": "^8.4.2", "open": "^8.4.2",
"prettier": "^3.5.3",
"protobufjs-cli": "^1.1.3", "protobufjs-cli": "^1.1.3",
"release-it": "^15.10.3", "release-it": "^15.10.3",
"sharp": "^0.32.6", "sharp": "^0.32.6",

View File

@@ -318,7 +318,7 @@ export const extractGroupMetadata = (result: BinaryNode) => {
const memberAddMode = getBinaryNodeChildString(group, 'member_add_mode') === 'all_member_add' const memberAddMode = getBinaryNodeChildString(group, 'member_add_mode') === 'all_member_add'
const metadata: GroupMetadata = { const metadata: GroupMetadata = {
id: groupId, id: groupId,
addressingMode: group.attrs.addressing_mode as "pn" | "lid", addressingMode: group.attrs.addressing_mode as 'pn' | 'lid',
subject: group.attrs.subject, subject: group.attrs.subject,
subjectOwner: group.attrs.s_o, subjectOwner: group.attrs.s_o,
subjectTime: +group.attrs.s_t, subjectTime: +group.attrs.s_t,

View File

@@ -634,10 +634,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
isLid ? authState.creds.me?.lid : authState.creds.me?.id isLid ? authState.creds.me?.lid : authState.creds.me?.id
) )
const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient
const fromMe = !attrs.recipient || ( const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe)
(attrs.type === 'retry' || attrs.type === 'sender')
&& isNodeFromMe
)
const key: proto.IMessageKey = { const key: proto.IMessageKey = {
remoteJid, remoteJid,

View File

@@ -264,7 +264,10 @@ export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions &
userJid: string 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 = { export type MediaGenerationOptions = {
logger?: ILogger logger?: ILogger

View File

@@ -3,7 +3,17 @@ import { createHash } from 'crypto'
import { createWriteStream, promises as fs } from 'fs' import { createWriteStream, promises as fs } from 'fs'
import { tmpdir } from 'os' import { tmpdir } from 'os'
import { join } from 'path' 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 { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../WABinary'
import { generateMessageIDV2 } from './generics' import { generateMessageIDV2 } from './generics'
import { getStream, getUrlFromDirectPath } from './messages-media' import { getStream, getUrlFromDirectPath } from './messages-media'
@@ -245,22 +255,16 @@ export const uploadingNecessaryImages = async (
const sha = hasher.digest('base64') const sha = hasher.digest('base64')
const { directPath } = await waUploadToServer( const { directPath } = await waUploadToServer(filePath, {
filePath,
{
mediaType: 'product-catalog-image', mediaType: 'product-catalog-image',
fileEncSha256B64: sha, fileEncSha256B64: sha,
timeoutMs timeoutMs
} })
)
await fs await fs.unlink(filePath).catch(err => console.log('Error deleting temp file ', err))
.unlink(filePath)
.catch(err => console.log('Error deleting temp file ', err))
return { url: getUrlFromDirectPath(directPath) } return { url: getUrlFromDirectPath(directPath) }
} })
)
) )
return results return results
} }

View File

@@ -11,7 +11,19 @@ import { Readable, Transform } from 'stream'
import { URL } from 'url' import { URL } from 'url'
import { proto } from '../../WAProto' import { proto } from '../../WAProto'
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults' import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults'
import { BaileysEventMap, DownloadableMessage, MediaConnInfo, MediaDecryptionKeyInfo, MediaType, MessageType, SocketConfig, WAGenericMediaMessage, 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 { BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto' import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
import { generateMessageIDV2 } from './generics' import { generateMessageIDV2 } from './generics'
@@ -327,20 +339,14 @@ export const encryptedStream = async (
const mediaKey = Crypto.randomBytes(32) const mediaKey = Crypto.randomBytes(32)
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType) const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
const encFilePath = join( const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc')
getTmpFilesDirectory(),
mediaType + generateMessageIDV2() + '-enc'
)
const encFileWriteStream = createWriteStream(encFilePath) const encFileWriteStream = createWriteStream(encFilePath)
let originalFileStream: WriteStream | undefined let originalFileStream: WriteStream | undefined
let originalFilePath: string | undefined let originalFilePath: string | undefined
if (saveOriginalFileIfRequired) { if (saveOriginalFileIfRequired) {
originalFilePath = join( originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original')
getTmpFilesDirectory(),
mediaType + generateMessageIDV2() + '-original'
)
originalFileStream = createWriteStream(originalFilePath) originalFileStream = createWriteStream(originalFilePath)
} }
@@ -411,7 +417,6 @@ export const encryptedStream = async (
sha256Enc.destroy() sha256Enc.destroy()
stream.destroy() stream.destroy()
try { try {
await fs.unlink(encFilePath) await fs.unlink(encFilePath)
if (originalFilePath) { if (originalFilePath) {
@@ -589,25 +594,20 @@ export const getWAUploadToServer = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
let result: any let result: any
try { try {
const body = await axios.post(url, createReadStream(filePath), {
const body = await axios.post(
url,
createReadStream(filePath),
{
...options, ...options,
maxRedirects: 0, maxRedirects: 0,
headers: { headers: {
...options.headers || { }, ...(options.headers || {}),
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'Origin': DEFAULT_ORIGIN Origin: DEFAULT_ORIGIN
}, },
httpsAgent: fetchAgent, httpsAgent: fetchAgent,
timeout: timeoutMs, timeout: timeoutMs,
responseType: 'json', responseType: 'json',
maxBodyLength: Infinity, maxBodyLength: Infinity,
maxContentLength: Infinity, maxContentLength: Infinity
} })
)
result = body.data result = body.data
if (result?.url || result?.directPath) { if (result?.url || result?.directPath) {

View File

@@ -165,39 +165,35 @@ export const prepareWAMessageMedia = async (message: AnyMediaMessageContent, opt
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation
const { const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(
mediaKey,
encFilePath,
originalFilePath,
fileEncSha256,
fileSha256,
fileLength
} = await encryptedStream(
uploadData.media, uploadData.media,
options.mediaTypeOverride || mediaType, options.mediaTypeOverride || mediaType,
{ {
logger, logger,
saveOriginalFileIfRequired: requiresOriginalForSomeProcessing, saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
opts: options.options opts: options.options
}) }
)
// url safe Base64 encode the SHA256 hash of the body // url safe Base64 encode the SHA256 hash of the body
const fileEncSha256B64 = fileEncSha256.toString('base64') const fileEncSha256B64 = fileEncSha256.toString('base64')
const [{ mediaUrl, directPath }] = await Promise.all([ const [{ mediaUrl, directPath }] = await Promise.all([
(async () => { (async () => {
const result = await options.upload( const result = await options.upload(encFilePath, {
encFilePath, fileEncSha256B64,
{ fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs } mediaType,
) timeoutMs: options.mediaUploadTimeoutMs
})
logger?.debug({ mediaType, cacheableKey }, 'uploaded media') logger?.debug({ mediaType, cacheableKey }, 'uploaded media')
return result return result
})(), })(),
(async () => { (async () => {
try { try {
if (requiresThumbnailComputation) { if (requiresThumbnailComputation) {
const { const { thumbnail, originalImageDimensions } = await generateThumbnail(
thumbnail, originalFilePath!,
originalImageDimensions mediaType as 'image' | 'video',
} = await generateThumbnail(originalFilePath!, mediaType as 'image' | 'video', options) options
)
uploadData.jpegThumbnail = thumbnail uploadData.jpegThumbnail = thumbnail
if (!uploadData.width && originalImageDimensions) { if (!uploadData.width && originalImageDimensions) {
uploadData.width = originalImageDimensions.width uploadData.width = originalImageDimensions.width
@@ -225,10 +221,8 @@ export const prepareWAMessageMedia = async (message: AnyMediaMessageContent, opt
} catch (error) { } catch (error) {
logger?.warn({ trace: error.stack }, 'failed to obtain extra info') logger?.warn({ trace: error.stack }, 'failed to obtain extra info')
} }
})(), })()
]) ]).finally(async () => {
.finally(
async() => {
try { try {
await fs.unlink(encFilePath) await fs.unlink(encFilePath)
if (originalFilePath) { if (originalFilePath) {
@@ -239,8 +233,7 @@ export const prepareWAMessageMedia = async (message: AnyMediaMessageContent, opt
} catch (error) { } catch (error) {
logger?.warn('failed to remove tmp file') logger?.warn('failed to remove tmp file')
} }
} })
)
const obj = WAProto.Message.fromObject({ const obj = WAProto.Message.fromObject({
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({

1691
yarn.lock

File diff suppressed because it is too large Load Diff