@zervonexx/baileys 0.0.0-stage → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +4112 -2
- package/WAProto/WAProtoCompile.js +323 -0
- package/WAProto/fetcher.js +68 -0
- package/WAProto/index.js +96 -0
- package/WAProto/parser.js +334 -0
- package/lib/Builders/AIRich.js +674 -0
- package/lib/Builders/auto.js +50 -0
- package/lib/Builders/base.js +145 -0
- package/lib/Builders/builders.js +589 -0
- package/lib/Builders/index.js +4 -0
- package/lib/Defaults/index.js +248 -0
- package/lib/Signal/index.js +2 -0
- package/lib/Signal/libsignal.js +527 -0
- package/lib/Signal/lid-mapping.js +283 -0
- package/lib/Socket/Client/index.js +2 -0
- package/lib/Socket/Client/types.js +10 -0
- package/lib/Socket/Client/websocket.js +84 -0
- package/lib/Socket/business.js +152 -0
- package/lib/Socket/chats.js +855 -0
- package/lib/Socket/communities.js +147 -0
- package/lib/Socket/groups.js +294 -0
- package/lib/Socket/index.js +15 -0
- package/lib/Socket/messages-recv.js +994 -0
- package/lib/Socket/messages-send.js +723 -0
- package/lib/Socket/mex.js +34 -0
- package/lib/Socket/newsletter.js +784 -0
- package/lib/Socket/registration.js +155 -0
- package/lib/Socket/socket.js +798 -0
- package/lib/Socket/spam-report.js +144 -0
- package/lib/Socket/username.js +82 -0
- package/lib/Socket/zervonex-handler.js +58 -0
- package/lib/Store/index.js +6 -0
- package/lib/Store/make-cache-manager-store.js +80 -0
- package/lib/Store/make-in-memory-store.js +426 -0
- package/lib/Store/make-ordered-dictionary.js +82 -0
- package/lib/Store/object-repository.js +31 -0
- package/lib/Store/reporting-info-store.js +38 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +8 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.js +25 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/Message.js +15 -0
- package/lib/Types/Newsletter.js +100 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +14 -0
- package/lib/Types/State.js +26 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +30 -0
- package/lib/Utils/auth-utils.js +159 -0
- package/lib/Utils/baileys-event-stream.js +33 -0
- package/lib/Utils/bot-capabilities.js +41 -0
- package/lib/Utils/bot-planning-replay.js +44 -0
- package/lib/Utils/browser-utils.js +30 -0
- package/lib/Utils/business.js +75 -0
- package/lib/Utils/chat-utils.js +317 -0
- package/lib/Utils/companion-reg-client-utils.js +20 -0
- package/lib/Utils/consumer-application.js +38 -0
- package/lib/Utils/crypto.js +53 -0
- package/lib/Utils/cstoken.js +15 -0
- package/lib/Utils/decode-wa-message.js +200 -0
- package/lib/Utils/event-buffer.js +273 -0
- package/lib/Utils/extras.js +186 -0
- package/lib/Utils/generics.js +195 -0
- package/lib/Utils/history.js +51 -0
- package/lib/Utils/identity-change-handler.js +19 -0
- package/lib/Utils/index.js +40 -0
- package/lib/Utils/link-preview.js +51 -0
- package/lib/Utils/logger.js +3 -0
- package/lib/Utils/lt-hash.js +3 -0
- package/lib/Utils/make-mutex.js +16 -0
- package/lib/Utils/message-composer.js +62 -0
- package/lib/Utils/message-retry-manager.js +48 -0
- package/lib/Utils/messages-media.js +502 -0
- package/lib/Utils/messages.js +943 -0
- package/lib/Utils/meta-ai-msmsg.js +122 -0
- package/lib/Utils/meta-compositing.js +75 -0
- package/lib/Utils/modern-messages.js +235 -0
- package/lib/Utils/native-flow.js +81 -0
- package/lib/Utils/noise-handler.js +161 -0
- package/lib/Utils/pre-key-manager.js +76 -0
- package/lib/Utils/process-message.js +401 -0
- package/lib/Utils/reporting-utils.js +171 -0
- package/lib/Utils/signal.js +167 -0
- package/lib/Utils/spam-report-utils.js +166 -0
- package/lib/Utils/sync-action-utils.js +33 -0
- package/lib/Utils/tc-token-utils.js +154 -0
- package/lib/Utils/use-keyv-auth-state.js +200 -0
- package/lib/Utils/use-multi-file-auth-state.js +84 -0
- package/lib/Utils/validate-connection.js +172 -0
- package/lib/WABinary/constants.js +1321 -0
- package/lib/WABinary/decode.js +152 -0
- package/lib/WABinary/encode.js +140 -0
- package/lib/WABinary/generic-utils.js +203 -0
- package/lib/WABinary/index.js +6 -0
- package/lib/WABinary/jid-utils.js +235 -0
- package/lib/WABinary/types.js +4 -0
- package/lib/WAM/BinaryInfo.js +10 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/encode.js +150 -0
- package/lib/WAM/index.js +3 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
- package/lib/WAUSync/Protocols/index.js +12 -0
- package/lib/WAUSync/USyncQuery.js +88 -0
- package/lib/WAUSync/USyncUser.js +20 -0
- package/lib/WAUSync/index.js +3 -0
- package/lib/index.js +67 -0
- package/package.json +189 -4
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { generateMessageIDV2, tokenizeCode } from './generics.js'
|
|
2
|
+
import { RichSubMessageType } from './bot-capabilities.js'
|
|
3
|
+
import { proto } from '../../WAProto/index.js'
|
|
4
|
+
|
|
5
|
+
const buildRichContextInfo = (quoted, options = {}) => {
|
|
6
|
+
const ctx = { forwardingScore: 1, isForwarded: true, forwardedAiBotMessageInfo: { botJid: options.botJid || '867051314767696@bot' }, forwardOrigin: 4, ...(options.mentions ? { mentionedJid: options.mentions } : {}) }
|
|
7
|
+
if (quoted?.key) { ctx.stanzaId = quoted.key.id; ctx.participant = quoted.key.participant || quoted.sender || quoted.key.remoteJid; ctx.quotedMessage = quoted.message }
|
|
8
|
+
return ctx
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const buildBotForwardedMessage = (submessages, contextInfo, unifiedResponse) => {
|
|
12
|
+
const rich = { messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD, submessages, contextInfo }
|
|
13
|
+
if (unifiedResponse) rich.unifiedResponse = unifiedResponse
|
|
14
|
+
return { botForwardedMessage: { message: { richResponseMessage: rich } } }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const wrap = (sub, quoted, options) => ({ message: buildBotForwardedMessage(sub, buildRichContextInfo(quoted, options)), messageId: generateMessageIDV2() })
|
|
18
|
+
const text = msg => ({ messageType: RichSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: msg })
|
|
19
|
+
const table = (title, rows) => ({ messageType: RichSubMessageType.AI_RICH_RESPONSE_TABLE, tableMetadata: { title, rows } })
|
|
20
|
+
|
|
21
|
+
export const generateTableContent = (title, headers, rows, quoted, options = {}) => {
|
|
22
|
+
const { footer, headerText } = options
|
|
23
|
+
const sub = [...(headerText ? [text(headerText)] : []), table(title, [{ items: headers, isHeading: true }, ...rows.map(row => ({ items: row.map(String) }))]), ...(footer ? [text(footer)] : [])]
|
|
24
|
+
return wrap(sub, quoted, options)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const generateListContent = (title, items, quoted, options = {}) => {
|
|
28
|
+
const { footer, headerText } = options
|
|
29
|
+
const sub = [...(headerText ? [text(headerText)] : []), table(title, items.map(item => ({ items: Array.isArray(item) ? item.map(String) : [String(item)] }))), ...(footer ? [text(footer)] : [])]
|
|
30
|
+
return wrap(sub, quoted, options)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const generateCodeBlockContent = (code, quoted, options = {}) => {
|
|
34
|
+
const { title, footer, language = 'javascript' } = options
|
|
35
|
+
const { codeBlocks } = tokenizeCode(code, language)
|
|
36
|
+
const sub = [...(title ? [text(title)] : []), { messageType: RichSubMessageType.AI_RICH_RESPONSE_CODE, codeMetadata: { codeLanguage: language, codeBlocks } }, ...(footer ? [text(footer)] : [])]
|
|
37
|
+
return wrap(sub, quoted, options)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const generateLatexContent = (quoted, options = {}) => {
|
|
41
|
+
const { text: txt, expressions = [], headerText, footer } = options
|
|
42
|
+
const latexExpressions = expressions.map(({ latexExpression, url, width, height, fontHeight, imageTopPadding, imageLeadingPadding, imageBottomPadding, imageTrailingPadding }) => {
|
|
43
|
+
const e = { latexExpression, url, width, height }
|
|
44
|
+
if (fontHeight !== undefined) e.fontHeight = fontHeight
|
|
45
|
+
if (imageTopPadding !== undefined) e.imageTopPadding = imageTopPadding
|
|
46
|
+
if (imageLeadingPadding !== undefined) e.imageLeadingPadding = imageLeadingPadding
|
|
47
|
+
if (imageBottomPadding !== undefined) e.imageBottomPadding = imageBottomPadding
|
|
48
|
+
if (imageTrailingPadding !== undefined) e.imageTrailingPadding = imageTrailingPadding
|
|
49
|
+
return e
|
|
50
|
+
})
|
|
51
|
+
const sub = [...(headerText ? [text(headerText)] : []), { messageType: RichSubMessageType.AI_RICH_RESPONSE_LATEX, latexMetadata: { text: txt || '', expressions: latexExpressions } }, ...(footer ? [text(footer)] : [])]
|
|
52
|
+
return wrap(sub, quoted, options)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const captureUnifiedResponse = msg => {
|
|
56
|
+
const rich = msg?.botForwardedMessage?.message?.richResponseMessage
|
|
57
|
+
if (!rich?.unifiedResponse?.data) return null
|
|
58
|
+
return { unifiedResponse: { data: rich.unifiedResponse.data }, submessages: rich.submessages || [], contextInfo: rich.contextInfo || {} }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const generateUnifiedResponseContent = (quoted, captured) => wrap(captured.submessages, quoted, { unifiedResponse: captured.unifiedResponse })
|
|
62
|
+
export const generateRichMessageContent = (submessages, quoted, options) => wrap(submessages, quoted, options)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { LRUCache } from 'lru-cache'
|
|
2
|
+
|
|
3
|
+
const RECENT_MESSAGES_SIZE = 512
|
|
4
|
+
const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
|
|
5
|
+
const PHONE_REQUEST_DELAY = 3000
|
|
6
|
+
|
|
7
|
+
export class MessageRetryManager {
|
|
8
|
+
constructor(logger, maxMsgRetryCount) {
|
|
9
|
+
this.logger = logger
|
|
10
|
+
this.maxMsgRetryCount = maxMsgRetryCount
|
|
11
|
+
this.recentMessagesMap = new LRUCache({ max: RECENT_MESSAGES_SIZE })
|
|
12
|
+
this.sessionRecreateHistory = new LRUCache({ ttl: RECREATE_SESSION_TIMEOUT * 2, ttlAutopurge: true })
|
|
13
|
+
this.retryCounters = new LRUCache({ ttl: 15 * 60 * 1000, ttlAutopurge: true, updateAgeOnGet: true })
|
|
14
|
+
this.pendingPhoneRequests = {}
|
|
15
|
+
this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
keyToString(key) { return `${key.to}:${key.id}` }
|
|
19
|
+
|
|
20
|
+
addRecentMessage(to, id, message) { this.recentMessagesMap.set(this.keyToString({ to, id }), { message, timestamp: Date.now() }) }
|
|
21
|
+
getRecentMessage(to, id) { return this.recentMessagesMap.get(this.keyToString({ to, id })) }
|
|
22
|
+
|
|
23
|
+
shouldRecreateSession(jid, retryCount, hasSession) {
|
|
24
|
+
if (!hasSession) { this.sessionRecreateHistory.set(jid, Date.now()); this.statistics.sessionRecreations++; return { reason: "we don't have a Signal session with them", recreate: true } }
|
|
25
|
+
if (retryCount < 2) return { reason: '', recreate: false }
|
|
26
|
+
const now = Date.now()
|
|
27
|
+
const prevTime = this.sessionRecreateHistory.get(jid)
|
|
28
|
+
if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) { this.sessionRecreateHistory.set(jid, now); this.statistics.sessionRecreations++; return { reason: 'retry count > 1 and over an hour since last recreation', recreate: true } }
|
|
29
|
+
return { reason: '', recreate: false }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
incrementRetryCount(messageId) { this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1); this.statistics.totalRetries++; return this.retryCounters.get(messageId) }
|
|
33
|
+
getRetryCount(messageId) { return this.retryCounters.get(messageId) || 0 }
|
|
34
|
+
hasExceededMaxRetries(messageId) { return this.getRetryCount(messageId) >= this.maxMsgRetryCount }
|
|
35
|
+
|
|
36
|
+
markRetrySuccess(messageId) { this.statistics.successfulRetries++; this.retryCounters.delete(messageId); this.cancelPendingPhoneRequest(messageId) }
|
|
37
|
+
markRetryFailed(messageId) { this.statistics.failedRetries++; this.retryCounters.delete(messageId) }
|
|
38
|
+
|
|
39
|
+
schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
|
|
40
|
+
this.cancelPendingPhoneRequest(messageId)
|
|
41
|
+
this.pendingPhoneRequests[messageId] = setTimeout(() => { delete this.pendingPhoneRequests[messageId]; this.statistics.phoneRequests++; callback() }, delay)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
cancelPendingPhoneRequest(messageId) {
|
|
45
|
+
const timeout = this.pendingPhoneRequests[messageId]
|
|
46
|
+
if (timeout) { clearTimeout(timeout); delete this.pendingPhoneRequests[messageId] }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
import { Boom } from '@hapi/boom'
|
|
2
|
+
import { spawn } from 'child_process'
|
|
3
|
+
import * as Crypto from 'crypto'
|
|
4
|
+
import { once } from 'events'
|
|
5
|
+
import { createWriteStream, createReadStream, mkdirSync, promises as fs } from 'fs'
|
|
6
|
+
import { join } from 'path'
|
|
7
|
+
import { Transform } from 'stream'
|
|
8
|
+
import urlRegexSafe from 'url-regex-safe'
|
|
9
|
+
import { tmpdir as osTmpdir } from 'os'
|
|
10
|
+
import { fileTypeFromBuffer } from 'file-type'
|
|
11
|
+
import intoStream from 'into-stream'
|
|
12
|
+
import { getStreamAsBuffer } from 'get-stream'
|
|
13
|
+
import got from 'got'
|
|
14
|
+
import { temporaryFile, temporaryDirectory } from 'tempy'
|
|
15
|
+
import { proto } from '../../WAProto/index.js'
|
|
16
|
+
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults/index.js'
|
|
17
|
+
import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js'
|
|
18
|
+
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js'
|
|
19
|
+
import { generateMessageIDV2 } from './generics.js'
|
|
20
|
+
|
|
21
|
+
// ─── TMP ──────────────────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
const BAILEYS_TMP_DIR = (() => {
|
|
24
|
+
for (const dir of [join(process.cwd(), '.b-tmp'), join(osTmpdir(), '.b-tmp')]) {
|
|
25
|
+
try {
|
|
26
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
27
|
+
process.env.TMPDIR = dir
|
|
28
|
+
process.env.VIPS_TMPDIR = dir
|
|
29
|
+
process.env.VIPS_DISC_THRESHOLD = '999999999999'
|
|
30
|
+
return dir
|
|
31
|
+
} catch { }
|
|
32
|
+
}
|
|
33
|
+
throw new Error('No writable tmp directory found')
|
|
34
|
+
})()
|
|
35
|
+
|
|
36
|
+
export const tmpdir = () => BAILEYS_TMP_DIR
|
|
37
|
+
const _tmpFile = (ext = '') => temporaryFile({ rootDirectory: BAILEYS_TMP_DIR, ...(ext && { extension: ext.replace('.', '') }) })
|
|
38
|
+
const _tmpDir = (prefix = '') => temporaryDirectory({ rootDirectory: BAILEYS_TMP_DIR, ...(prefix && { prefix }) })
|
|
39
|
+
const _cleanupFiles = async (...paths) => Promise.all(paths.map(p => p ? fs.unlink(p).catch(() => { }) : Promise.resolve()))
|
|
40
|
+
|
|
41
|
+
// ─── FFMPEG ───────────────────────────────────────────────────────────────────
|
|
42
|
+
|
|
43
|
+
let _ffmpegPath = null
|
|
44
|
+
const getFfmpegPath = async () => {
|
|
45
|
+
if (_ffmpegPath) return _ffmpegPath
|
|
46
|
+
try { const { default: p } = await import('ffmpeg-static'); if (p) return (_ffmpegPath = p) } catch { }
|
|
47
|
+
return (_ffmpegPath = 'ffmpeg')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const _spawnFfmpeg = (ffmpegPath, args) => new Promise((resolve, reject) => {
|
|
51
|
+
const ff = spawn(ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'] })
|
|
52
|
+
let stderr = ''
|
|
53
|
+
ff.stderr.on('data', d => { stderr += d })
|
|
54
|
+
ff.on('close', code => code === 0 ? resolve() : reject(new Error(`FFmpeg exited ${code}: ${stderr.slice(-500)}`)))
|
|
55
|
+
ff.on('error', reject)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const _tmpConvert = async (buffer, inSuffix, outSuffix, ffmpegArgs) => {
|
|
59
|
+
const inputPath = _tmpFile(inSuffix)
|
|
60
|
+
const outputPath = _tmpFile(outSuffix)
|
|
61
|
+
await fs.writeFile(inputPath, buffer)
|
|
62
|
+
try { await _spawnFfmpeg(await getFfmpegPath(), ['-y', '-i', inputPath, ...ffmpegArgs, outputPath]); return await fs.readFile(outputPath) }
|
|
63
|
+
finally { await _cleanupFiles(inputPath, outputPath) }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const _animatedWebpToMp4 = async (buffer, ffmpegPath) => {
|
|
67
|
+
const { default: sharp } = await import('sharp')
|
|
68
|
+
const meta = await sharp(buffer, { animated: true }).metadata()
|
|
69
|
+
const pages = meta.pages ?? 1, pageH = meta.pageHeight ?? Math.round(meta.height / pages)
|
|
70
|
+
const delays = meta.delay?.length === pages ? meta.delay : Array(pages).fill(100)
|
|
71
|
+
const frameDir = _tmpDir('webp-frames'), concatFile = _tmpFile('txt'), outputPath = _tmpFile('mp4')
|
|
72
|
+
await fs.mkdir(frameDir, { recursive: true })
|
|
73
|
+
try {
|
|
74
|
+
const { data, info } = await sharp(buffer, { animated: true }).raw().toBuffer({ resolveWithObject: true })
|
|
75
|
+
const frameSize = info.width * pageH * info.channels
|
|
76
|
+
const framePaths = []
|
|
77
|
+
for (let i = 0; i < pages; i++) {
|
|
78
|
+
const fp = join(frameDir, `f${i}.png`)
|
|
79
|
+
await sharp(data.subarray(i * frameSize, (i + 1) * frameSize), { raw: { width: info.width, height: pageH, channels: info.channels } }).png().toFile(fp)
|
|
80
|
+
framePaths.push(fp)
|
|
81
|
+
}
|
|
82
|
+
const lines = framePaths.flatMap((p, i) => [`file '${p}'`, `duration ${(delays[i] / 1000).toFixed(6)}`])
|
|
83
|
+
lines.push(`file '${framePaths[framePaths.length - 1]}'`)
|
|
84
|
+
await fs.writeFile(concatFile, lines.join('\n'))
|
|
85
|
+
await _spawnFfmpeg(ffmpegPath, ['-y', '-f', 'concat', '-safe', '0', '-i', concatFile, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', '-movflags', '+faststart', '-map_metadata', '-1', outputPath])
|
|
86
|
+
return await fs.readFile(outputPath)
|
|
87
|
+
} finally {
|
|
88
|
+
const files = await fs.readdir(frameDir).catch(() => [])
|
|
89
|
+
await Promise.all(files.map(f => fs.unlink(join(frameDir, f)).catch(() => { })))
|
|
90
|
+
await fs.rmdir(frameDir).catch(() => { })
|
|
91
|
+
await _cleanupFiles(concatFile, outputPath)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const convertToOpusBuffer = async (buffer, logger) => {
|
|
96
|
+
const detected = await fileTypeFromBuffer(buffer)
|
|
97
|
+
if (detected?.ext === 'opus') return buffer
|
|
98
|
+
return _tmpConvert(buffer, detected?.ext ? `.${detected.ext}` : '', '.ogg', ['-vn', '-c:a', 'libopus', '-b:a', '128k', '-ar', '48000', '-ac', '1', '-vbr', 'on', '-compression_level', '10', '-frame_duration', '20', '-application', 'audio', '-map_metadata', '-1'])
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const convertToMp4Buffer = async (buffer, logger) => {
|
|
102
|
+
try {
|
|
103
|
+
const { default: sharp } = await import('sharp')
|
|
104
|
+
const meta = await sharp(buffer, { animated: true }).metadata()
|
|
105
|
+
if (meta.format === 'webp' && (meta.pages ?? 1) > 1) return await _animatedWebpToMp4(buffer, await getFfmpegPath())
|
|
106
|
+
} catch { }
|
|
107
|
+
const detected = await fileTypeFromBuffer(buffer)
|
|
108
|
+
return _tmpConvert(buffer, detected?.ext ? `.${detected.ext}` : '', '.mp4', ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', '-map_metadata', '-1'])
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ─── IMAGE ────────────────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
export const getImageProcessingLibrary = async () => {
|
|
114
|
+
const [jimp, sharp] = await Promise.all([import('jimp').catch(() => null), import('sharp').catch(() => null)])
|
|
115
|
+
if (sharp) return { sharp }
|
|
116
|
+
if (jimp) return { jimp }
|
|
117
|
+
throw new Boom('No image processing library available')
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
|
|
121
|
+
if (!Buffer.isBuffer(bufferOrFilePath)) bufferOrFilePath = await normalizeToBuffer(bufferOrFilePath)
|
|
122
|
+
const lib = await getImageProcessingLibrary()
|
|
123
|
+
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
124
|
+
const img = lib.sharp.default(bufferOrFilePath)
|
|
125
|
+
const { width: w, height: h } = await img.metadata()
|
|
126
|
+
return { buffer: await img.resize(width).jpeg({ quality: 95 }).toBuffer(), original: { width: w, height: h } }
|
|
127
|
+
}
|
|
128
|
+
if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
|
|
129
|
+
const jimp = await lib.jimp.Jimp.read(bufferOrFilePath)
|
|
130
|
+
return { buffer: await jimp.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 95 }), original: { width: jimp.width, height: jimp.height } }
|
|
131
|
+
}
|
|
132
|
+
throw new Boom('No image processing library available')
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export const generateProfilePicture = async mediaUpload => {
|
|
136
|
+
const src = await normalizeToBuffer(mediaUpload)
|
|
137
|
+
const lib = await getImageProcessingLibrary()
|
|
138
|
+
if ('sharp' in lib && typeof lib.sharp?.default === 'function') return { img: await lib.sharp.default(src).resize(720, 720, { fit: 'inside' }).jpeg({ quality: 80 }).toBuffer() }
|
|
139
|
+
if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
|
140
|
+
const { read, MIME_JPEG } = lib.jimp
|
|
141
|
+
const image = await read(src)
|
|
142
|
+
return { img: await image.crop(0, 0, image.getWidth(), image.getHeight()).scaleToFit(720, 720).getBufferAsync(MIME_JPEG) }
|
|
143
|
+
}
|
|
144
|
+
throw new Boom('No image processing library available')
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export const generateThumbnail = async (file, mediaType, options) => {
|
|
148
|
+
if (mediaType === 'image') {
|
|
149
|
+
const { buffer, original } = await extractImageThumb(file)
|
|
150
|
+
return { thumbnail: buffer.toString('base64'), originalImageDimensions: (original.width && original.height) ? original : undefined }
|
|
151
|
+
}
|
|
152
|
+
if (mediaType === 'video') {
|
|
153
|
+
const imgFilename = join(tmpdir(), generateMessageIDV2() + '.jpg')
|
|
154
|
+
try {
|
|
155
|
+
const ff = await getFfmpegPath()
|
|
156
|
+
await new Promise((resolve, reject) => {
|
|
157
|
+
const proc = spawn(ff, ['-ss', '00:00:00', '-i', file, '-y', '-vf', 'scale=32:-1', '-vframes', '1', '-f', 'image2', imgFilename])
|
|
158
|
+
proc.on('close', code => code === 0 ? resolve() : reject(new Error(`FFmpeg thumb exit ${code}`)))
|
|
159
|
+
proc.on('error', reject)
|
|
160
|
+
})
|
|
161
|
+
const thumbnail = (await fs.readFile(imgFilename)).toString('base64')
|
|
162
|
+
await fs.unlink(imgFilename).catch(() => { })
|
|
163
|
+
return { thumbnail, originalImageDimensions: undefined }
|
|
164
|
+
} catch (err) { options.logger?.debug('could not generate video thumb: ' + err) }
|
|
165
|
+
}
|
|
166
|
+
return { thumbnail: undefined, originalImageDimensions: undefined }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ─── STREAM ───────────────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
export const toReadable = input => intoStream(input)
|
|
172
|
+
export const getHttpStream = (url, options = {}) => got.stream(url.toString(), { headers: { ...(options.headers ?? {}), Origin: DEFAULT_ORIGIN } })
|
|
173
|
+
export const isHttpUrl = (() => {
|
|
174
|
+
const r = urlRegexSafe({ exact: true, auth: true })
|
|
175
|
+
return str => typeof str === 'string' && r.test(str)
|
|
176
|
+
})()
|
|
177
|
+
|
|
178
|
+
export const getStream = async (item, opts) => {
|
|
179
|
+
if (!item) throw new Boom('Item is required for getStream', { statusCode: 400 })
|
|
180
|
+
if (Buffer.isBuffer(item)) return { stream: intoStream(item), type: 'buffer' }
|
|
181
|
+
if (item?.type === 'Buffer' && Array.isArray(item?.data)) return { stream: intoStream(Buffer.from(item.data)), type: 'buffer' }
|
|
182
|
+
if (ArrayBuffer.isView(item)) return { stream: intoStream(Buffer.from(item.buffer, item.byteOffset, item.byteLength)), type: 'buffer' }
|
|
183
|
+
if (item instanceof ArrayBuffer) return { stream: intoStream(Buffer.from(item)), type: 'buffer' }
|
|
184
|
+
if (Array.isArray(item)) return { stream: intoStream(Buffer.from(item)), type: 'buffer' }
|
|
185
|
+
if (typeof item?.pipe === 'function' || typeof item?.[Symbol.asyncIterator] === 'function') return { stream: intoStream(await getStreamAsBuffer(item)), type: 'buffer' }
|
|
186
|
+
if (item?.url && Buffer.isBuffer(item.url)) return { stream: intoStream(item.url), type: 'buffer' }
|
|
187
|
+
if (item?.url && typeof item.url === 'string' && item.url.startsWith('data:')) return { stream: intoStream(Buffer.from(item.url.split(',')[1], 'base64')), type: 'buffer' }
|
|
188
|
+
const u = item?.url ? item.url.toString() : typeof item === 'string' ? item : null
|
|
189
|
+
if (u) {
|
|
190
|
+
if (u.startsWith('data:')) return { stream: intoStream(Buffer.from(u.split(',')[1], 'base64')), type: 'buffer' }
|
|
191
|
+
if (isHttpUrl(u)) return { stream: intoStream(await getStreamAsBuffer(got.stream(u, { headers: { ...(opts?.headers ?? {}), Origin: DEFAULT_ORIGIN } }))), type: 'remote' }
|
|
192
|
+
if (/^(?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(u)) return { stream: intoStream(Buffer.from(u, 'base64')), type: 'buffer' }
|
|
193
|
+
return { stream: createReadStream(u), type: 'file' }
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
return { stream: intoStream(item), type: 'buffer' }
|
|
197
|
+
} catch {
|
|
198
|
+
throw new Boom(`Invalid input type for getStream: ${typeof item}`, { statusCode: 400 })
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export const toBuffer = async stream => {
|
|
203
|
+
if (Buffer.isBuffer(stream)) return stream
|
|
204
|
+
const { stream: resolved } = await getStream(stream)
|
|
205
|
+
return getStreamAsBuffer(resolved)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export const normalizeToBuffer = async input => {
|
|
209
|
+
if (!input) return undefined
|
|
210
|
+
return toBuffer(input)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export const resolveToMediaUrl = async input => {
|
|
214
|
+
if (isHttpUrl(input)) return input
|
|
215
|
+
if (isHttpUrl(input?.url)) return input.url
|
|
216
|
+
const buf = await normalizeToBuffer(input)
|
|
217
|
+
if (!buf) throw new TypeError('Could not resolve input to buffer')
|
|
218
|
+
const { Catbox, Pomf, Quax, Cloudku, Litterbox } = await import('@zanixongroup/uploader')
|
|
219
|
+
const providers = [Catbox, Pomf, Quax, Cloudku, Litterbox].sort(() => Math.random() - 0.5)
|
|
220
|
+
let lastError
|
|
221
|
+
for (const provider of providers) {
|
|
222
|
+
try { const url = await provider(buf); if (url) return url } catch (err) { lastError = err }
|
|
223
|
+
}
|
|
224
|
+
throw new TypeError(`All providers failed: ${lastError?.message}`)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ─── HKDF ─────────────────────────────────────────────────────────────────────
|
|
228
|
+
|
|
229
|
+
export const hkdfInfoKey = type => `WhatsApp ${MEDIA_HKDF_KEY_MAPPING[type]} Keys`
|
|
230
|
+
|
|
231
|
+
export const getMediaKeys = async (buffer, mediaType) => {
|
|
232
|
+
if (!buffer) throw new Boom('Cannot derive from empty media key')
|
|
233
|
+
buffer = await normalizeToBuffer(buffer)
|
|
234
|
+
if (!buffer?.length) throw new Boom('Cannot derive from empty media key')
|
|
235
|
+
const k = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
|
|
236
|
+
return { iv: k.subarray(0, 16), cipherKey: k.subarray(16, 48), macKey: k.subarray(48, 80) }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ─── AUDIO ────────────────────────────────────────────────────────────────────
|
|
240
|
+
|
|
241
|
+
export const mediaMessageSHA256B64 = message => { const media = Object.values(message)[0]; return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64') }
|
|
242
|
+
|
|
243
|
+
export const getAudioDuration = async (buffer, logger) => {
|
|
244
|
+
try {
|
|
245
|
+
const mm = await import('music-metadata')
|
|
246
|
+
if (Buffer.isBuffer(buffer)) return (await mm.parseBuffer(buffer, undefined, { duration: true })).format.duration
|
|
247
|
+
if (typeof buffer === 'string') return (await mm.parseFile(buffer, { duration: true })).format.duration
|
|
248
|
+
return (await mm.parseStream(buffer, undefined, { duration: true })).format.duration
|
|
249
|
+
} catch (e) { logger?.debug({ trace: e?.stack || e }, 'failed to determine audio duration'); return undefined }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export const getAudioWaveform = async (buffer, logger) => {
|
|
253
|
+
const fallback = new Uint8Array([0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99])
|
|
254
|
+
try {
|
|
255
|
+
const rawPCM = await new Promise(async (resolve, reject) => {
|
|
256
|
+
const chunks = [], ff = spawn(await getFfmpegPath(), ['-i', 'pipe:0', '-f', 's16le', '-ac', '1', '-ar', '16000', 'pipe:1'], { stdio: ['pipe', 'pipe', 'pipe'] })
|
|
257
|
+
let stderr = ''
|
|
258
|
+
ff.stdout.on('data', d => chunks.push(d))
|
|
259
|
+
ff.stderr.on('data', d => { stderr += d })
|
|
260
|
+
ff.on('close', code => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`FFmpeg waveform exit ${code}: ${stderr.slice(-300)}`)))
|
|
261
|
+
ff.on('error', reject)
|
|
262
|
+
ff.stdin.end(Buffer.isBuffer(buffer) ? buffer : typeof buffer === 'string' ? await fs.readFile(buffer) : await toBuffer(buffer))
|
|
263
|
+
})
|
|
264
|
+
if (!rawPCM.length) throw new Error('empty PCM output')
|
|
265
|
+
const samples = rawPCM.length >> 1
|
|
266
|
+
const blockSize = Math.max(1, Math.floor(samples / 64))
|
|
267
|
+
const blockSums = new Float64Array(64)
|
|
268
|
+
for (let i = 0; i < samples; i++) blockSums[Math.min(63, Math.floor(i / blockSize))] += Math.abs(rawPCM.readInt16LE(i * 2))
|
|
269
|
+
const avg = Array.from(blockSums, sum => sum / blockSize / 32768)
|
|
270
|
+
const max = Math.max(...avg, 0.0001)
|
|
271
|
+
return new Uint8Array(avg.map(v => Math.max(0, Math.min(100, Math.round((v / max) * 100)))))
|
|
272
|
+
} catch (e) { logger?.debug({ trace: e?.stack || e }, 'failed to generate waveform, using fallback'); return fallback }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ─── PREPARE / ENCRYPT ────────────────────────────────────────────────────────
|
|
276
|
+
|
|
277
|
+
export const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, convertVideo } = {}) => {
|
|
278
|
+
const { stream, type } = await getStream(media, opts)
|
|
279
|
+
let buffer = await toBuffer(stream)
|
|
280
|
+
if (mediaType === 'video' && convertVideo) {
|
|
281
|
+
try { buffer = await convertToMp4Buffer(buffer, logger) } catch (e) { logger?.error('failed to convert video:', e) }
|
|
282
|
+
}
|
|
283
|
+
let bodyPath, didSaveToTmpPath = false
|
|
284
|
+
try {
|
|
285
|
+
if (type === 'file') bodyPath = typeof media === 'string' ? media : media.url
|
|
286
|
+
else if (saveOriginalFileIfRequired) { bodyPath = join(tmpdir(), mediaType + generateMessageIDV2()); await fs.writeFile(bodyPath, buffer); didSaveToTmpPath = true }
|
|
287
|
+
return {
|
|
288
|
+
mediaKey: undefined, encWriteStream: buffer, fileLength: buffer.length,
|
|
289
|
+
fileSha256: Crypto.createHash('sha256').update(buffer).digest(),
|
|
290
|
+
fileEncSha256: undefined, bodyPath, didSaveToTmpPath,
|
|
291
|
+
cleanup: async () => { if (didSaveToTmpPath && bodyPath) await fs.unlink(bodyPath).catch(() => { }) },
|
|
292
|
+
}
|
|
293
|
+
} catch (error) {
|
|
294
|
+
if (didSaveToTmpPath && bodyPath) await fs.unlink(bodyPath).catch(() => { })
|
|
295
|
+
throw error
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, mediaKey: providedMediaKey, isPtt, forceOpus, convertVideo } = {}) => {
|
|
300
|
+
const { stream, type } = await getStream(media, opts)
|
|
301
|
+
let finalStream = stream, opusConverted = false
|
|
302
|
+
if (mediaType === 'audio' && (isPtt === true || forceOpus === true)) {
|
|
303
|
+
try { finalStream = toReadable(await convertToOpusBuffer(await toBuffer(stream), logger)); opusConverted = true }
|
|
304
|
+
catch { finalStream = (await getStream(media, opts)).stream }
|
|
305
|
+
}
|
|
306
|
+
if (mediaType === 'video' && convertVideo === true) finalStream = toReadable(await convertToMp4Buffer(await toBuffer(finalStream), logger))
|
|
307
|
+
|
|
308
|
+
const mediaKey = providedMediaKey || Crypto.randomBytes(32)
|
|
309
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
|
|
310
|
+
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv)
|
|
311
|
+
const hmac = Crypto.createHmac('sha256', macKey).update(iv)
|
|
312
|
+
const sha256Plain = Crypto.createHash('sha256'), sha256Enc = Crypto.createHash('sha256')
|
|
313
|
+
const encChunks = [], plainChunks = saveOriginalFileIfRequired ? [] : null
|
|
314
|
+
let fileLength = 0, encFilePath = null, originalFilePath = null
|
|
315
|
+
|
|
316
|
+
try {
|
|
317
|
+
for await (const data of finalStream) {
|
|
318
|
+
fileLength += data.length
|
|
319
|
+
if (type === 'remote' && opts?.maxContentLength && fileLength > opts.maxContentLength) throw new Boom('content length exceeded', { data: { media, type } })
|
|
320
|
+
plainChunks?.push(data)
|
|
321
|
+
sha256Plain.update(data)
|
|
322
|
+
const encrypted = aes.update(data)
|
|
323
|
+
sha256Enc.update(encrypted); hmac.update(encrypted); encChunks.push(encrypted)
|
|
324
|
+
}
|
|
325
|
+
const finalData = aes.final()
|
|
326
|
+
sha256Enc.update(finalData); hmac.update(finalData); encChunks.push(finalData)
|
|
327
|
+
const mac = hmac.digest().subarray(0, 10)
|
|
328
|
+
sha256Enc.update(mac); encChunks.push(mac)
|
|
329
|
+
finalStream.destroy()
|
|
330
|
+
|
|
331
|
+
const encBuffer = Buffer.concat(encChunks)
|
|
332
|
+
const fileEncSha256 = sha256Enc.digest()
|
|
333
|
+
const fileSha256 = sha256Plain.digest()
|
|
334
|
+
|
|
335
|
+
if (plainChunks) {
|
|
336
|
+
try { originalFilePath = join(tmpdir(), mediaType + generateMessageIDV2() + '-original'); await fs.writeFile(originalFilePath, Buffer.concat(plainChunks)) }
|
|
337
|
+
catch { originalFilePath = null }
|
|
338
|
+
}
|
|
339
|
+
let useMemory = false
|
|
340
|
+
try { encFilePath = join(tmpdir(), mediaType + generateMessageIDV2() + '-enc'); await fs.writeFile(encFilePath, encBuffer) }
|
|
341
|
+
catch { encFilePath = null; useMemory = true }
|
|
342
|
+
|
|
343
|
+
return { mediaKey, bodyPath: originalFilePath, encFilePath, encBuffer: useMemory ? encBuffer : null, mac, fileEncSha256, fileSha256, fileLength, opusConverted, cleanup: async () => _cleanupFiles(encFilePath, originalFilePath) }
|
|
344
|
+
} catch (error) {
|
|
345
|
+
aes.destroy(); hmac.destroy(); sha256Plain.destroy(); sha256Enc.destroy(); finalStream.destroy()
|
|
346
|
+
await _cleanupFiles(encFilePath, originalFilePath)
|
|
347
|
+
throw error
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ─── RAW UPLOAD ───────────────────────────────────────────────────────────────
|
|
352
|
+
|
|
353
|
+
export const getRawMediaUploadData = async (media, mediaType) => {
|
|
354
|
+
const { stream } = await getStream(media)
|
|
355
|
+
const hasher = Crypto.createHash('sha256')
|
|
356
|
+
const filePath = join(tmpdir(), mediaType + generateMessageIDV2())
|
|
357
|
+
const fileWriteStream = createWriteStream(filePath)
|
|
358
|
+
let fileLength = 0
|
|
359
|
+
try {
|
|
360
|
+
for await (const data of stream) { fileLength += data.length; hasher.update(data); if (!fileWriteStream.write(data)) await once(fileWriteStream, 'drain') }
|
|
361
|
+
fileWriteStream.end()
|
|
362
|
+
await once(fileWriteStream, 'finish')
|
|
363
|
+
stream.destroy()
|
|
364
|
+
return { filePath, fileSha256: hasher.digest(), fileLength }
|
|
365
|
+
} catch (error) {
|
|
366
|
+
fileWriteStream.destroy(); stream.destroy()
|
|
367
|
+
await fs.unlink(filePath).catch(() => { })
|
|
368
|
+
throw error
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ─── DOWNLOAD ─────────────────────────────────────────────────────────────────
|
|
373
|
+
|
|
374
|
+
const DEF_HOST = 'mmg.whatsapp.net'
|
|
375
|
+
const AES_CHUNK_SIZE = 16
|
|
376
|
+
const toSmallestChunkSize = num => Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
|
|
377
|
+
|
|
378
|
+
export const getUrlFromDirectPath = directPath => directPath ? (directPath.startsWith('http') ? directPath : `https://${DEF_HOST}${directPath.startsWith('/') ? '' : '/'}${directPath}`) : undefined
|
|
379
|
+
|
|
380
|
+
export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
381
|
+
const downloadUrl = url?.startsWith('https://mmg.whatsapp.net/') ? url : getUrlFromDirectPath(directPath)
|
|
382
|
+
if (!downloadUrl) throw new Boom('No valid media URL or directPath present', { statusCode: 400 })
|
|
383
|
+
return downloadEncryptedContent(downloadUrl, await getMediaKeys(mediaKey, type), opts)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
387
|
+
let bytesFetched = 0, startChunk = 0, firstBlockIsIV = false
|
|
388
|
+
if (startByte) {
|
|
389
|
+
const chunk = toSmallestChunkSize(startByte || 0)
|
|
390
|
+
if (chunk) { startChunk = chunk - AES_CHUNK_SIZE; bytesFetched = chunk; firstBlockIsIV = true }
|
|
391
|
+
}
|
|
392
|
+
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
|
393
|
+
const headers = { ...(options?.headers ? (Array.isArray(options.headers) ? Object.fromEntries(options.headers) : options.headers) : {}), Origin: DEFAULT_ORIGIN }
|
|
394
|
+
if (startChunk || endChunk) headers.Range = `bytes=${startChunk}-${endChunk || ''}`
|
|
395
|
+
const fetched = getHttpStream(downloadUrl, { ...(options || {}), headers })
|
|
396
|
+
let remainingBytes = Buffer.from([]), aes
|
|
397
|
+
const pushBytes = (bytes, push) => {
|
|
398
|
+
if (startByte || endByte) {
|
|
399
|
+
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
|
|
400
|
+
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
|
|
401
|
+
push(bytes.subarray(start, end)); bytesFetched += bytes.length
|
|
402
|
+
} else push(bytes)
|
|
403
|
+
}
|
|
404
|
+
return fetched.pipe(new Transform({
|
|
405
|
+
transform(chunk, _, callback) {
|
|
406
|
+
let data = Buffer.concat([remainingBytes, chunk])
|
|
407
|
+
const decryptLength = toSmallestChunkSize(data.length)
|
|
408
|
+
remainingBytes = data.subarray(decryptLength); data = data.subarray(0, decryptLength)
|
|
409
|
+
if (!aes) {
|
|
410
|
+
let ivValue = iv
|
|
411
|
+
if (firstBlockIsIV) { ivValue = data.subarray(0, AES_CHUNK_SIZE); data = data.subarray(AES_CHUNK_SIZE) }
|
|
412
|
+
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
|
413
|
+
if (endByte) aes.setAutoPadding(false)
|
|
414
|
+
}
|
|
415
|
+
try { pushBytes(aes.update(data), b => this.push(b)); callback() } catch (error) { callback(error) }
|
|
416
|
+
},
|
|
417
|
+
final(callback) { try { pushBytes(aes.final(), b => this.push(b)); callback() } catch (error) { callback(error) } }
|
|
418
|
+
}), { end: true })
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ─── UPLOAD ───────────────────────────────────────────────────────────────────
|
|
422
|
+
|
|
423
|
+
export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''))
|
|
424
|
+
|
|
425
|
+
export const extensionForMediaMessage = message => {
|
|
426
|
+
const type = Object.keys(message)[0]
|
|
427
|
+
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') return '.jpeg'
|
|
428
|
+
return message[type].mimetype.split(';')[0]?.split('/')[1]
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const httpsPost = async (url, body, headers, signal) => {
|
|
432
|
+
const response = await got.post(url, { body: Buffer.isBuffer(body) ? body : await getStreamAsBuffer(body), headers: { ...headers, Origin: DEFAULT_ORIGIN }, signal, throwHttpErrors: false })
|
|
433
|
+
let json = null
|
|
434
|
+
try { json = JSON.parse(response.body) } catch { }
|
|
435
|
+
return { status: response.statusCode, ok: response.statusCode >= 200 && response.statusCode < 300, json: async () => json }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export const getWAUploadToServer = ({ customUploadHosts, logger, options }, refreshMediaConn) => async (stream, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
|
|
439
|
+
let reqBody
|
|
440
|
+
try { reqBody = await toBuffer(stream) } catch (err) { logger?.error({ err: err.message }, 'failed to prepare upload body'); throw err }
|
|
441
|
+
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
|
442
|
+
let media = MEDIA_PATH_MAP[mediaType]
|
|
443
|
+
if (newsletter) media = media?.replace('/mms/', '/newsletter/newsletter-')
|
|
444
|
+
if (!media) throw new Boom(`No media path found for type: ${mediaType}`, { statusCode: 400 })
|
|
445
|
+
let uploadInfo = await refreshMediaConn(false)
|
|
446
|
+
const hosts = [...(customUploadHosts ?? []), ...(uploadInfo.hosts ?? [])]
|
|
447
|
+
if (!hosts.length) throw new Boom('No upload hosts available', { statusCode: 503 })
|
|
448
|
+
let urls, lastError
|
|
449
|
+
for (const { hostname, maxContentLengthBytes } of hosts) {
|
|
450
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
451
|
+
try {
|
|
452
|
+
if (attempt > 1) { uploadInfo = await refreshMediaConn(true); reqBody = await toBuffer(stream) }
|
|
453
|
+
if (maxContentLengthBytes && Buffer.isBuffer(reqBody) && reqBody.length > maxContentLengthBytes) break
|
|
454
|
+
const auth = encodeURIComponent(uploadInfo.auth)
|
|
455
|
+
const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
|
|
456
|
+
const controller = new AbortController()
|
|
457
|
+
const timer = timeoutMs ? setTimeout(() => controller.abort(), timeoutMs) : null
|
|
458
|
+
let response
|
|
459
|
+
try { response = await httpsPost(url, reqBody, { ...(Array.isArray(options?.headers) ? Object.fromEntries(options.headers) : (options?.headers ?? {})), 'Content-Type': 'application/octet-stream', Origin: DEFAULT_ORIGIN }, controller.signal) }
|
|
460
|
+
finally { if (timer) clearTimeout(timer) }
|
|
461
|
+
const result = await response.json().catch(() => null)
|
|
462
|
+
if (result?.url || result?.directPath) { urls = { mediaUrl: result.url, directPath: result.direct_path, handle: result.handle }; break }
|
|
463
|
+
lastError = new Error(`${hostname} rejected upload (HTTP ${response.status}): ${JSON.stringify(result)}`)
|
|
464
|
+
} catch (err) { lastError = err; if (attempt < 2) await new Promise(r => setTimeout(r, 500 * attempt)) }
|
|
465
|
+
}
|
|
466
|
+
if (urls) break
|
|
467
|
+
}
|
|
468
|
+
if (!urls) throw new Boom(`Media upload failed on all hosts. Last error: ${lastError?.message ?? 'unknown'}`, { statusCode: 500, data: { lastError: lastError?.message } })
|
|
469
|
+
return urls
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// ─── MEDIA RETRY ──────────────────────────────────────────────────────────────
|
|
473
|
+
|
|
474
|
+
const getMediaRetryKey = mediaKey => hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
|
|
475
|
+
|
|
476
|
+
export const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
|
|
477
|
+
const iv = Crypto.randomBytes(12)
|
|
478
|
+
const ciphertext = aesEncryptGCM(proto.ServerErrorReceipt.encode({ stanzaId: key.id }).finish(), await getMediaRetryKey(mediaKey), iv, Buffer.from(key.id))
|
|
479
|
+
return { tag: 'receipt', attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' }, content: [{ tag: 'encrypt', attrs: {}, content: [{ tag: 'enc_p', attrs: {}, content: ciphertext }, { tag: 'enc_iv', attrs: {}, content: iv }] }, { tag: 'rmr', attrs: { jid: key.remoteJid, from_me: (!!key.fromMe).toString(), participant: key.participant } }] }
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export const decodeMediaRetryNode = node => {
|
|
483
|
+
const rmrNode = getBinaryNodeChild(node, 'rmr')
|
|
484
|
+
const event = { key: { id: node.attrs.id, remoteJid: rmrNode.attrs.jid, fromMe: rmrNode.attrs.from_me === 'true', participant: rmrNode.attrs.participant } }
|
|
485
|
+
const errorNode = getBinaryNodeChild(node, 'error')
|
|
486
|
+
if (errorNode) { event.error = new Boom(`Failed to re-upload media (${+errorNode.attrs.code})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(+errorNode.attrs.code) }); return event }
|
|
487
|
+
const encNode = getBinaryNodeChild(node, 'encrypt')
|
|
488
|
+
const ciphertext = getBinaryNodeChildBuffer(encNode, 'enc_p')
|
|
489
|
+
const iv = getBinaryNodeChildBuffer(encNode, 'enc_iv')
|
|
490
|
+
event[ciphertext && iv ? 'media' : 'error'] = ciphertext && iv ? { ciphertext, iv } : new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
|
491
|
+
return event
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => proto.MediaRetryNotification.decode(aesDecryptGCM(ciphertext, await getMediaRetryKey(mediaKey), iv, Buffer.from(msgId)))
|
|
495
|
+
|
|
496
|
+
export const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code]
|
|
497
|
+
const MEDIA_RETRY_STATUS_MAP = {
|
|
498
|
+
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
499
|
+
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
500
|
+
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
501
|
+
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
502
|
+
}
|