@itznomo/baileys 0.0.0-stage → 0.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/BUTTONS.md +153 -0
- package/Example/call-bot.mjs +38 -0
- package/Example/example.mjs +36 -0
- package/Example/full-bot-commands.mjs +319 -0
- package/Example/full-bot.mjs +77 -0
- package/LICENSE +21 -0
- package/README.md +543 -2
- package/WAProto/@dnuzi +1 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +113300 -0
- package/assets/banner.svg +17 -0
- package/assets/devider.svg +1 -0
- package/assets/features.svg +21 -0
- package/docs/CALLS.md +106 -0
- package/docs/FEATURES.md +1152 -0
- package/engine-requirements.js +19 -0
- package/index.d.ts +815 -0
- package/package.json +51 -4
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +627 -0
- package/src/constants.js +147 -0
- package/src/defaults.js +106 -0
- package/src/foundation/ai-rich.js +654 -0
- package/src/foundation/audio-duration.js +470 -0
- package/src/foundation/audio-samples.js +250 -0
- package/src/foundation/boom.js +39 -0
- package/src/foundation/builders.js +851 -0
- package/src/foundation/cache.js +134 -0
- package/src/foundation/concurrency.js +69 -0
- package/src/foundation/curve25519.js +189 -0
- package/src/foundation/image-thumb.js +65 -0
- package/src/foundation/link-preview.js +278 -0
- package/src/foundation/logger.js +78 -0
- package/src/foundation/long.js +130 -0
- package/src/foundation/performance.js +385 -0
- package/src/foundation/protobuf-minimal.js +587 -0
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +47 -0
- package/src/foundation/zip.js +108 -0
- package/src/index.js +67 -0
- package/src/signal/libsignal.js +996 -0
- package/src/signal/signal-group.js +455 -0
- package/src/signal/signal-repository.js +635 -0
- package/src/socket/business-communities.js +811 -0
- package/src/socket/chats.js +702 -0
- package/src/socket/groups-newsletter.js +524 -0
- package/src/socket/messages-recv.js +1815 -0
- package/src/socket/messages-send.js +1526 -0
- package/src/socket/socket-builder.js +131 -0
- package/src/socket/socket-core.js +913 -0
- package/src/socket/usync.js +287 -0
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +170 -0
- package/src/utils/auth-state-core.js +731 -0
- package/src/utils/auth-state-storage.js +594 -0
- package/src/utils/chat-sync.js +1046 -0
- package/src/utils/check-status.js +159 -0
- package/src/utils/cstoken.js +17 -0
- package/src/utils/media.js +807 -0
- package/src/utils/message-compose.js +1747 -0
- package/src/utils/message-processing.js +912 -0
- package/src/utils/modern-messages.js +435 -0
- package/src/utils/nomo-buttons.js +138 -0
- package/src/utils/nomo-commands.js +168 -0
- package/src/utils/spam-report-utils.js +136 -0
- package/src/utils/use-keyv-auth-state.js +307 -0
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +1227 -0
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/auto.js +139 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1727 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +730 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +22852 -0
- package/src/wam/wam.js +146 -0
- package/voip.d.ts +144 -0
|
@@ -0,0 +1,807 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { audioDuration } from '../foundation/audio-duration.js'
|
|
3
|
+
import { decodeChannel0, waveformFromSamples } from '../foundation/audio-samples.js'
|
|
4
|
+
import { getLinkPreview } from '../foundation/link-preview.js'
|
|
5
|
+
import * as Crypto from 'node:crypto'
|
|
6
|
+
import { once } from 'node:events'
|
|
7
|
+
import { createReadStream, createWriteStream, promises as fs } from 'node:fs'
|
|
8
|
+
import { tmpdir } from 'node:os'
|
|
9
|
+
import { join } from 'node:path'
|
|
10
|
+
import { Readable, Transform } from 'node:stream'
|
|
11
|
+
import { proto } from '../../WAProto/index.js'
|
|
12
|
+
import { Boom } from '../foundation/boom.js'
|
|
13
|
+
import { extractImageThumbFallback } from '../foundation/image-thumb.js'
|
|
14
|
+
import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../binary/wa-binary.js'
|
|
15
|
+
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './wa-protocol-core.js'
|
|
16
|
+
import { generateMessageIDV2 } from './wa-protocol-core.js'
|
|
17
|
+
|
|
18
|
+
const DEFAULT_ORIGIN = 'https://web.whatsapp.com'
|
|
19
|
+
|
|
20
|
+
export const MEDIA_HKDF_KEY_MAPPING = {
|
|
21
|
+
audio: 'Audio',
|
|
22
|
+
document: 'Document',
|
|
23
|
+
gif: 'Video',
|
|
24
|
+
image: 'Image',
|
|
25
|
+
ppic: '',
|
|
26
|
+
product: 'Image',
|
|
27
|
+
ptt: 'Audio',
|
|
28
|
+
'sticker-pack': 'Sticker Pack',
|
|
29
|
+
'thumbnail-sticker-pack': 'Sticker Pack Thumbnail',
|
|
30
|
+
sticker: 'Image',
|
|
31
|
+
video: 'Video',
|
|
32
|
+
'thumbnail-document': 'Document Thumbnail',
|
|
33
|
+
'thumbnail-image': 'Image Thumbnail',
|
|
34
|
+
'thumbnail-video': 'Video Thumbnail',
|
|
35
|
+
'thumbnail-link': 'Link Thumbnail',
|
|
36
|
+
'md-msg-hist': 'History',
|
|
37
|
+
'md-app-state': 'App State',
|
|
38
|
+
'product-catalog-image': 'Product Catalog Image',
|
|
39
|
+
'payment-bg-image': 'Payment Background',
|
|
40
|
+
ptv: 'Video',
|
|
41
|
+
'biz-cover-photo': 'Image',
|
|
42
|
+
location: 'Location',
|
|
43
|
+
contact: 'Contact',
|
|
44
|
+
'voip-token': 'Voip Token'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const MEDIA_PATH_MAP = {
|
|
48
|
+
image: '/mms/image',
|
|
49
|
+
video: '/mms/video',
|
|
50
|
+
document: '/mms/document',
|
|
51
|
+
audio: '/mms/audio',
|
|
52
|
+
sticker: '/mms/image',
|
|
53
|
+
'sticker-pack': '/mms/sticker-pack',
|
|
54
|
+
'thumbnail-sticker-pack': '/mms/thumbnail-sticker-pack',
|
|
55
|
+
'thumbnail-link': '/mms/image',
|
|
56
|
+
'thumbnail-image': '/mms/image',
|
|
57
|
+
'thumbnail-video': '/mms/video',
|
|
58
|
+
'thumbnail-document': '/mms/document',
|
|
59
|
+
'product-catalog-image': '/product/image',
|
|
60
|
+
'md-app-state': '',
|
|
61
|
+
'md-msg-hist': '/mms/md-app-state',
|
|
62
|
+
'biz-cover-photo': '/pps/biz-cover-photo'
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP)
|
|
66
|
+
|
|
67
|
+
const NEWSLETTER_MEDIA_PATH_MAP = {
|
|
68
|
+
image: '/newsletter/newsletter-image',
|
|
69
|
+
video: '/newsletter/newsletter-video',
|
|
70
|
+
document: '/newsletter/newsletter-document',
|
|
71
|
+
audio: '/newsletter/newsletter-audio',
|
|
72
|
+
sticker: '/newsletter/newsletter-image',
|
|
73
|
+
'thumbnail-link': '/newsletter/newsletter-thumbnail-link'
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const getTmpFilesDirectory = () => tmpdir()
|
|
77
|
+
|
|
78
|
+
let imageProcessingLibrary
|
|
79
|
+
let imageProcessingLibraryMissing = false
|
|
80
|
+
export const getImageProcessingLibrary = async () => {
|
|
81
|
+
if (imageProcessingLibrary) return imageProcessingLibrary
|
|
82
|
+
if (imageProcessingLibraryMissing) throw new Boom('No image processing library available')
|
|
83
|
+
const [sharp, image, jimp] = await Promise.all([
|
|
84
|
+
import('sharp').catch(() => {}),
|
|
85
|
+
import('@napi-rs/image').catch(() => {}),
|
|
86
|
+
import('jimp').catch(() => {})
|
|
87
|
+
])
|
|
88
|
+
if (sharp) imageProcessingLibrary = { sharp }
|
|
89
|
+
else if (image) imageProcessingLibrary = { image }
|
|
90
|
+
else if (jimp) imageProcessingLibrary = { jimp }
|
|
91
|
+
else {
|
|
92
|
+
imageProcessingLibraryMissing = true
|
|
93
|
+
throw new Boom('No image processing library available')
|
|
94
|
+
}
|
|
95
|
+
return imageProcessingLibrary
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export const hkdfInfoKey = type => `WhatsApp ${MEDIA_HKDF_KEY_MAPPING[type]} Keys`
|
|
99
|
+
|
|
100
|
+
export const getRawMediaUploadData = async (media, mediaType, logger) => {
|
|
101
|
+
const { stream } = await getStream(media)
|
|
102
|
+
logger?.debug('got stream for raw upload')
|
|
103
|
+
const hasher = Crypto.createHash('sha256')
|
|
104
|
+
const filePath = join(tmpdir(), mediaType + generateMessageIDV2())
|
|
105
|
+
const fileWriteStream = createWriteStream(filePath)
|
|
106
|
+
let fileLength = 0
|
|
107
|
+
try {
|
|
108
|
+
for await (const data of stream) {
|
|
109
|
+
fileLength += data.length
|
|
110
|
+
hasher.update(data)
|
|
111
|
+
if (!fileWriteStream.write(data)) await once(fileWriteStream, 'drain')
|
|
112
|
+
}
|
|
113
|
+
fileWriteStream.end()
|
|
114
|
+
await once(fileWriteStream, 'finish')
|
|
115
|
+
stream.destroy()
|
|
116
|
+
const fileSha256 = hasher.digest()
|
|
117
|
+
logger?.debug('hashed data for raw upload')
|
|
118
|
+
return { filePath, fileSha256, fileLength }
|
|
119
|
+
} catch (error) {
|
|
120
|
+
fileWriteStream.destroy()
|
|
121
|
+
stream.destroy()
|
|
122
|
+
try {
|
|
123
|
+
await fs.unlink(filePath)
|
|
124
|
+
} catch {
|
|
125
|
+
|
|
126
|
+
}
|
|
127
|
+
throw error
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function getMediaKeys(buffer, mediaType) {
|
|
132
|
+
if (!buffer) throw new Boom('Cannot derive from empty media key')
|
|
133
|
+
if (typeof buffer === 'string') buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64')
|
|
134
|
+
|
|
135
|
+
const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
|
|
136
|
+
return {
|
|
137
|
+
iv: expandedMediaKey.slice(0, 16),
|
|
138
|
+
cipherKey: expandedMediaKey.slice(16, 48),
|
|
139
|
+
macKey: expandedMediaKey.slice(48, 80)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export const extractVideoThumb = async (path, time, size) => {
|
|
144
|
+
const ffmpeg = spawn(
|
|
145
|
+
'ffmpeg',
|
|
146
|
+
[
|
|
147
|
+
'-loglevel',
|
|
148
|
+
'error',
|
|
149
|
+
'-ss',
|
|
150
|
+
String(time),
|
|
151
|
+
'-i',
|
|
152
|
+
path,
|
|
153
|
+
'-an',
|
|
154
|
+
'-sn',
|
|
155
|
+
'-dn',
|
|
156
|
+
'-map_metadata',
|
|
157
|
+
'-1',
|
|
158
|
+
'-vf',
|
|
159
|
+
`scale=${size.width}:-1`,
|
|
160
|
+
'-frames:v',
|
|
161
|
+
'1',
|
|
162
|
+
'-c:v',
|
|
163
|
+
'mjpeg',
|
|
164
|
+
'-f',
|
|
165
|
+
'image2pipe',
|
|
166
|
+
'pipe:1'
|
|
167
|
+
],
|
|
168
|
+
{ stdio: ['ignore', 'pipe', 'pipe'] }
|
|
169
|
+
)
|
|
170
|
+
let buffer = Buffer.alloc(0)
|
|
171
|
+
const stderrChunks = []
|
|
172
|
+
ffmpeg.stdout.on('data', chunk => {
|
|
173
|
+
buffer = Buffer.concat([buffer, chunk])
|
|
174
|
+
})
|
|
175
|
+
ffmpeg.stderr.on('data', chunk => stderrChunks.push(chunk))
|
|
176
|
+
const [code] = await once(ffmpeg, 'close')
|
|
177
|
+
if (code !== 0) throw new Boom(`FFmpeg failed (code ${code}):\n` + Buffer.concat(stderrChunks).toString('utf8'))
|
|
178
|
+
return buffer
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const thumbWithLibrary = async (lib, bufferOrFilePath, width) => {
|
|
182
|
+
if ('sharp' in lib && lib.sharp?.default) {
|
|
183
|
+
const img = lib.sharp.default(bufferOrFilePath)
|
|
184
|
+
const dimensions = await img.metadata()
|
|
185
|
+
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer()
|
|
186
|
+
return { buffer, original: { width: dimensions.width, height: dimensions.height } }
|
|
187
|
+
} else if ('image' in lib && lib.image?.Transformer) {
|
|
188
|
+
if (!Buffer.isBuffer(bufferOrFilePath)) bufferOrFilePath = await fs.readFile(bufferOrFilePath)
|
|
189
|
+
const img = new lib.image.Transformer(bufferOrFilePath)
|
|
190
|
+
const dimensions = await img.metadata()
|
|
191
|
+
const buffer = await img.resize(width, undefined, 0).jpeg(50)
|
|
192
|
+
return { buffer, original: { width: dimensions.width, height: dimensions.height } }
|
|
193
|
+
} else if ('jimp' in lib && lib.jimp?.Jimp) {
|
|
194
|
+
const jimp = await lib.jimp.Jimp.read(bufferOrFilePath)
|
|
195
|
+
const dimensions = { width: jimp.width, height: jimp.height }
|
|
196
|
+
const buffer = await jimp.resize({ w: width, mode: lib.jimp.ResizeStrategy?.BILINEAR }).getBuffer('image/jpeg', { quality: 50 })
|
|
197
|
+
return { buffer, original: dimensions }
|
|
198
|
+
} else {
|
|
199
|
+
throw new Boom('No image processing library available')
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Never leave a media message without jpegThumbnail just because sharp / @napi-rs/image / jimp is not installed:
|
|
204
|
+
// fall back to ffmpeg (see foundation/image-thumb.js).
|
|
205
|
+
export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
|
|
206
|
+
if (bufferOrFilePath instanceof Readable) bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
|
207
|
+
let libraryError
|
|
208
|
+
try {
|
|
209
|
+
return await thumbWithLibrary(await getImageProcessingLibrary(), bufferOrFilePath, width)
|
|
210
|
+
} catch (err) {
|
|
211
|
+
libraryError = err
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
return await extractImageThumbFallback(bufferOrFilePath, width)
|
|
215
|
+
} catch (err) {
|
|
216
|
+
if (libraryError && libraryError.message !== 'No image processing library available') err.message += ` (image library error: ${libraryError.message})`
|
|
217
|
+
throw err
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''))
|
|
222
|
+
|
|
223
|
+
export const generateProfilePicture = async (mediaUpload, dimensions) => {
|
|
224
|
+
let buffer
|
|
225
|
+
const { width: w = 720, height: h = 720 } = dimensions || {}
|
|
226
|
+
if (Buffer.isBuffer(mediaUpload)) {
|
|
227
|
+
buffer = mediaUpload
|
|
228
|
+
} else {
|
|
229
|
+
const { stream } = await getStream(mediaUpload)
|
|
230
|
+
buffer = await toBuffer(stream)
|
|
231
|
+
}
|
|
232
|
+
const lib = await getImageProcessingLibrary()
|
|
233
|
+
let img
|
|
234
|
+
if ('sharp' in lib && lib.sharp?.default) {
|
|
235
|
+
img = lib.sharp.default(buffer).resize(w, h).jpeg({ quality: 80 }).toBuffer()
|
|
236
|
+
} else if ('image' in lib && lib.image?.Transformer) {
|
|
237
|
+
img = new lib.image.Transformer(buffer).resize(w, h, 0).jpeg(80)
|
|
238
|
+
} else if ('jimp' in lib && lib.jimp?.Jimp) {
|
|
239
|
+
const jimp = await lib.jimp.Jimp.read(buffer)
|
|
240
|
+
const min = Math.min(jimp.width, jimp.height)
|
|
241
|
+
const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min })
|
|
242
|
+
img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy?.BILINEAR }).getBuffer('image/jpeg', { quality: 80 })
|
|
243
|
+
} else {
|
|
244
|
+
throw new Boom('No image processing library available')
|
|
245
|
+
}
|
|
246
|
+
return { img: await img }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export const mediaMessageSHA256B64 = message => {
|
|
250
|
+
const media = Object.values(message)[0]
|
|
251
|
+
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64')
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export async function getAudioDuration(buffer) {
|
|
255
|
+
if (!Buffer.isBuffer(buffer) && typeof buffer !== 'string') buffer = await toBuffer(buffer)
|
|
256
|
+
const native = await audioDuration(buffer)
|
|
257
|
+
if (typeof native === 'number' && Number.isFinite(native)) return native
|
|
258
|
+
return ffprobeDuration(buffer)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function ffprobeDuration(input) {
|
|
262
|
+
const usesStdin = Buffer.isBuffer(input)
|
|
263
|
+
const args = ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', usesStdin ? 'pipe:0' : input]
|
|
264
|
+
try {
|
|
265
|
+
const ffprobe = spawn('ffprobe', args, { stdio: [usesStdin ? 'pipe' : 'ignore', 'pipe', 'ignore'] })
|
|
266
|
+
const outChunks = []
|
|
267
|
+
ffprobe.stdout.on('data', chunk => outChunks.push(chunk))
|
|
268
|
+
if (usesStdin) ffprobe.stdin.end(input)
|
|
269
|
+
const [code] = await once(ffprobe, 'close')
|
|
270
|
+
if (code !== 0) return undefined
|
|
271
|
+
const seconds = parseFloat(Buffer.concat(outChunks).toString('utf8').trim())
|
|
272
|
+
return Number.isFinite(seconds) ? seconds : undefined
|
|
273
|
+
} catch {
|
|
274
|
+
return undefined
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const decodeChannel0WithFfmpeg = audioData =>
|
|
279
|
+
new Promise(resolve => {
|
|
280
|
+
let child
|
|
281
|
+
try {
|
|
282
|
+
child = spawn('ffmpeg', ['-v', 'error', '-i', 'pipe:0', '-af', 'pan=mono|c0=c0', '-ar', '16000', '-f', 'f32le', 'pipe:1'], { stdio: ['pipe', 'pipe', 'ignore'] })
|
|
283
|
+
} catch {
|
|
284
|
+
return resolve(undefined)
|
|
285
|
+
}
|
|
286
|
+
const out = []
|
|
287
|
+
const timer = setTimeout(() => {
|
|
288
|
+
child.kill('SIGKILL')
|
|
289
|
+
resolve(undefined)
|
|
290
|
+
}, 60000)
|
|
291
|
+
child.on('error', () => resolve(undefined))
|
|
292
|
+
child.stdin.on('error', () => {})
|
|
293
|
+
child.stdout.on('data', c => out.push(c))
|
|
294
|
+
child.on('close', code => {
|
|
295
|
+
clearTimeout(timer)
|
|
296
|
+
const raw = Buffer.concat(out)
|
|
297
|
+
if (code !== 0 || raw.length < 4) return resolve(undefined)
|
|
298
|
+
const copy = new Float32Array(Math.floor(raw.length / 4))
|
|
299
|
+
for (let i = 0; i < copy.length; i++) copy[i] = raw.readFloatLE(i * 4)
|
|
300
|
+
resolve(copy)
|
|
301
|
+
})
|
|
302
|
+
child.stdin.end(audioData)
|
|
303
|
+
})
|
|
304
|
+
|
|
305
|
+
export async function getAudioWaveform(buffer, logger) {
|
|
306
|
+
try {
|
|
307
|
+
let audioData
|
|
308
|
+
if (Buffer.isBuffer(buffer)) audioData = buffer
|
|
309
|
+
else if (typeof buffer === 'string') audioData = await toBuffer(createReadStream(buffer))
|
|
310
|
+
else audioData = await toBuffer(buffer)
|
|
311
|
+
const rawData = decodeChannel0(audioData) ?? (await decodeChannel0WithFfmpeg(audioData))
|
|
312
|
+
if (!rawData || !rawData.length) {
|
|
313
|
+
logger?.debug('Failed to generate waveform: no decoder for this audio (built-in handles WAV/FLAC; other formats need ffmpeg)')
|
|
314
|
+
return undefined
|
|
315
|
+
}
|
|
316
|
+
return waveformFromSamples(rawData)
|
|
317
|
+
} catch (e) {
|
|
318
|
+
logger?.debug('Failed to generate waveform: ' + e)
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export const toReadable = buffer => {
|
|
323
|
+
const readable = new Readable({ read: () => {} })
|
|
324
|
+
readable.push(buffer)
|
|
325
|
+
readable.push(null)
|
|
326
|
+
return readable
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export const toBuffer = async stream => {
|
|
330
|
+
const chunks = []
|
|
331
|
+
for await (const chunk of stream) chunks.push(chunk)
|
|
332
|
+
stream.destroy()
|
|
333
|
+
return Buffer.concat(chunks)
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export const getStream = async (item, opts) => {
|
|
337
|
+
if (Buffer.isBuffer(item)) return { stream: toReadable(item), type: 'buffer' }
|
|
338
|
+
if ('stream' in item) return { stream: item.stream, type: 'readable' }
|
|
339
|
+
const urlStr = item.url.toString()
|
|
340
|
+
if (urlStr.startsWith('data:')) {
|
|
341
|
+
const buffer = Buffer.from(urlStr.split(',')[1], 'base64')
|
|
342
|
+
return { stream: toReadable(buffer), type: 'buffer' }
|
|
343
|
+
}
|
|
344
|
+
if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) return { stream: await getHttpStream(item.url, opts), type: 'remote' }
|
|
345
|
+
return { stream: createReadStream(item.url), type: 'file' }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export async function generateThumbnail(file, mediaType, options) {
|
|
349
|
+
let thumbnail
|
|
350
|
+
let originalImageDimensions
|
|
351
|
+
if (mediaType === 'image') {
|
|
352
|
+
const { buffer, original } = await extractImageThumb(file)
|
|
353
|
+
thumbnail = buffer.toString('base64')
|
|
354
|
+
if (original.width && original.height) originalImageDimensions = { width: original.width, height: original.height }
|
|
355
|
+
} else if (mediaType === 'video') {
|
|
356
|
+
try {
|
|
357
|
+
const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 })
|
|
358
|
+
thumbnail = buff.toString('base64')
|
|
359
|
+
} catch (err) {
|
|
360
|
+
options.logger?.debug('could not generate video thumb: ' + err)
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return { thumbnail, originalImageDimensions }
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export const getHttpStream = async (url, options = {}) => {
|
|
367
|
+
const response = await fetch(url.toString(), { dispatcher: options.dispatcher, method: 'GET', headers: options.headers })
|
|
368
|
+
if (!response.ok) throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } })
|
|
369
|
+
return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
373
|
+
const { stream, type } = await getStream(media, opts)
|
|
374
|
+
logger?.debug('fetched media stream')
|
|
375
|
+
const mediaKey = Crypto.randomBytes(32)
|
|
376
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
|
|
377
|
+
const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc')
|
|
378
|
+
const encFileWriteStream = createWriteStream(encFilePath)
|
|
379
|
+
let originalFileStream
|
|
380
|
+
let originalFilePath
|
|
381
|
+
if (saveOriginalFileIfRequired) {
|
|
382
|
+
originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original')
|
|
383
|
+
originalFileStream = createWriteStream(originalFilePath)
|
|
384
|
+
}
|
|
385
|
+
let fileLength = 0
|
|
386
|
+
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv)
|
|
387
|
+
const hmac = Crypto.createHmac('sha256', macKey).update(iv)
|
|
388
|
+
const sha256Plain = Crypto.createHash('sha256')
|
|
389
|
+
const sha256Enc = Crypto.createHash('sha256')
|
|
390
|
+
const onChunk = async buff => {
|
|
391
|
+
sha256Enc.update(buff)
|
|
392
|
+
hmac.update(buff)
|
|
393
|
+
if (!encFileWriteStream.write(buff)) await once(encFileWriteStream, 'drain')
|
|
394
|
+
}
|
|
395
|
+
try {
|
|
396
|
+
for await (const data of stream) {
|
|
397
|
+
fileLength += data.length
|
|
398
|
+
if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
|
|
399
|
+
throw new Boom(`content length exceeded when encrypting "${type}"`, { data: { media, type } })
|
|
400
|
+
}
|
|
401
|
+
if (originalFileStream) {
|
|
402
|
+
if (!originalFileStream.write(data)) await once(originalFileStream, 'drain')
|
|
403
|
+
}
|
|
404
|
+
sha256Plain.update(data)
|
|
405
|
+
await onChunk(aes.update(data))
|
|
406
|
+
}
|
|
407
|
+
await onChunk(aes.final())
|
|
408
|
+
const mac = hmac.digest().slice(0, 10)
|
|
409
|
+
sha256Enc.update(mac)
|
|
410
|
+
const fileSha256 = sha256Plain.digest()
|
|
411
|
+
const fileEncSha256 = sha256Enc.digest()
|
|
412
|
+
encFileWriteStream.write(mac)
|
|
413
|
+
const encFinishPromise = once(encFileWriteStream, 'finish')
|
|
414
|
+
const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve()
|
|
415
|
+
encFileWriteStream.end()
|
|
416
|
+
originalFileStream?.end?.()
|
|
417
|
+
stream.destroy()
|
|
418
|
+
|
|
419
|
+
await encFinishPromise
|
|
420
|
+
await originalFinishPromise
|
|
421
|
+
logger?.debug('encrypted data successfully')
|
|
422
|
+
return { mediaKey, originalFilePath, encFilePath, mac, fileEncSha256, fileSha256, fileLength }
|
|
423
|
+
} catch (error) {
|
|
424
|
+
encFileWriteStream.destroy()
|
|
425
|
+
originalFileStream?.destroy?.()
|
|
426
|
+
aes.destroy()
|
|
427
|
+
hmac.destroy()
|
|
428
|
+
sha256Plain.destroy()
|
|
429
|
+
sha256Enc.destroy()
|
|
430
|
+
stream.destroy()
|
|
431
|
+
try {
|
|
432
|
+
await fs.unlink(encFilePath)
|
|
433
|
+
if (originalFilePath) await fs.unlink(originalFilePath)
|
|
434
|
+
} catch (err) {
|
|
435
|
+
logger?.error({ err }, 'failed deleting tmp files')
|
|
436
|
+
}
|
|
437
|
+
throw error
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
export const DEF_MEDIA_HOST = 'mmg.whatsapp.net'
|
|
442
|
+
const AES_CHUNK_SIZE = 16
|
|
443
|
+
const toSmallestChunkSize = num => Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
|
|
444
|
+
|
|
445
|
+
export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`
|
|
446
|
+
|
|
447
|
+
const extractHost = url => {
|
|
448
|
+
if (!url) return undefined
|
|
449
|
+
try {
|
|
450
|
+
return new URL(url).host
|
|
451
|
+
} catch {
|
|
452
|
+
return undefined
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
457
|
+
|
|
458
|
+
const fallbackHost = opts.host ?? extractHost(url)
|
|
459
|
+
const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url
|
|
460
|
+
if (!downloadUrl) throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 })
|
|
461
|
+
const keys = await getMediaKeys(mediaKey, type)
|
|
462
|
+
return downloadEncryptedContent(downloadUrl, keys, opts)
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
466
|
+
let bytesFetched = 0
|
|
467
|
+
let startChunk = 0
|
|
468
|
+
let firstBlockIsIV = false
|
|
469
|
+
if (startByte) {
|
|
470
|
+
const chunk = toSmallestChunkSize(startByte || 0)
|
|
471
|
+
if (chunk) {
|
|
472
|
+
startChunk = chunk - AES_CHUNK_SIZE
|
|
473
|
+
bytesFetched = chunk
|
|
474
|
+
firstBlockIsIV = true
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
|
478
|
+
const headersInit = options?.headers ? options.headers : undefined
|
|
479
|
+
const headers = {
|
|
480
|
+
...(headersInit ? (Array.isArray(headersInit) ? Object.fromEntries(headersInit) : headersInit) : {}),
|
|
481
|
+
Origin: DEFAULT_ORIGIN
|
|
482
|
+
}
|
|
483
|
+
if (startChunk || endChunk) {
|
|
484
|
+
headers.Range = `bytes=${startChunk}-`
|
|
485
|
+
if (endChunk) headers.Range += endChunk
|
|
486
|
+
}
|
|
487
|
+
const fetched = await getHttpStream(downloadUrl, { ...(options || {}), headers })
|
|
488
|
+
let remainingBytes = Buffer.from([])
|
|
489
|
+
let aes
|
|
490
|
+
|
|
491
|
+
const pushBytes = (bytes, push) => {
|
|
492
|
+
if (startByte || endByte) {
|
|
493
|
+
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
|
|
494
|
+
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
|
|
495
|
+
push(bytes.slice(start, end))
|
|
496
|
+
bytesFetched += bytes.length
|
|
497
|
+
} else {
|
|
498
|
+
push(bytes)
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const output = new Transform({
|
|
503
|
+
transform(chunk, _, callback) {
|
|
504
|
+
let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk
|
|
505
|
+
const decryptLength = toSmallestChunkSize(data.length)
|
|
506
|
+
remainingBytes = data.slice(decryptLength)
|
|
507
|
+
data = data.slice(0, decryptLength)
|
|
508
|
+
if (!aes) {
|
|
509
|
+
let ivValue = iv
|
|
510
|
+
if (firstBlockIsIV) {
|
|
511
|
+
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
|
512
|
+
data = data.slice(AES_CHUNK_SIZE)
|
|
513
|
+
}
|
|
514
|
+
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
|
515
|
+
if (endByte) aes.setAutoPadding(false)
|
|
516
|
+
}
|
|
517
|
+
try {
|
|
518
|
+
pushBytes(aes.update(data), b => this.push(b))
|
|
519
|
+
callback()
|
|
520
|
+
} catch (error) {
|
|
521
|
+
callback(error)
|
|
522
|
+
}
|
|
523
|
+
},
|
|
524
|
+
final(callback) {
|
|
525
|
+
try {
|
|
526
|
+
pushBytes(aes.final(), b => this.push(b))
|
|
527
|
+
callback()
|
|
528
|
+
} catch (error) {
|
|
529
|
+
callback(error)
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
})
|
|
533
|
+
|
|
534
|
+
fetched.on('error', err => output.destroy(err))
|
|
535
|
+
return fetched.pipe(output, { end: true })
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export function extensionForMediaMessage(message) {
|
|
539
|
+
const getExtension = mimetype => mimetype.split(';')[0]?.split('/')[1]
|
|
540
|
+
const type = Object.keys(message)[0]
|
|
541
|
+
let extension
|
|
542
|
+
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
|
|
543
|
+
extension = '.jpeg'
|
|
544
|
+
} else {
|
|
545
|
+
extension = getExtension(message[type].mimetype)
|
|
546
|
+
}
|
|
547
|
+
return extension
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const isNodeRuntime = () =>
|
|
551
|
+
typeof process !== 'undefined' && process.versions?.node !== null && typeof process.versions.bun === 'undefined' && typeof globalThis.Deno === 'undefined'
|
|
552
|
+
|
|
553
|
+
export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
|
|
554
|
+
if (redirectCount > 5) throw new Error('Too many redirects')
|
|
555
|
+
const parsedUrl = new URL(url)
|
|
556
|
+
const httpModule = parsedUrl.protocol === 'https:' ? await import('node:https') : await import('node:http')
|
|
557
|
+
const fileStats = await fs.stat(filePath)
|
|
558
|
+
const fileSize = fileStats.size
|
|
559
|
+
return new Promise((resolve, reject) => {
|
|
560
|
+
const req = httpModule.request(
|
|
561
|
+
{
|
|
562
|
+
hostname: parsedUrl.hostname,
|
|
563
|
+
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
|
564
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
565
|
+
method: 'POST',
|
|
566
|
+
headers: { ...headers, 'Content-Length': fileSize },
|
|
567
|
+
agent,
|
|
568
|
+
timeout: timeoutMs
|
|
569
|
+
},
|
|
570
|
+
res => {
|
|
571
|
+
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
572
|
+
res.resume()
|
|
573
|
+
const newUrl = new URL(res.headers.location, url).toString()
|
|
574
|
+
resolve(uploadWithNodeHttp({ url: newUrl, filePath, headers, timeoutMs, agent }, redirectCount + 1))
|
|
575
|
+
return
|
|
576
|
+
}
|
|
577
|
+
let body = ''
|
|
578
|
+
res.on('data', chunk => (body += chunk))
|
|
579
|
+
res.on('end', () => {
|
|
580
|
+
try {
|
|
581
|
+
resolve(JSON.parse(body))
|
|
582
|
+
} catch {
|
|
583
|
+
resolve(undefined)
|
|
584
|
+
}
|
|
585
|
+
})
|
|
586
|
+
}
|
|
587
|
+
)
|
|
588
|
+
req.on('error', reject)
|
|
589
|
+
req.on('timeout', () => {
|
|
590
|
+
req.destroy()
|
|
591
|
+
reject(new Error('Upload timeout'))
|
|
592
|
+
})
|
|
593
|
+
const stream = createReadStream(filePath)
|
|
594
|
+
stream.pipe(req)
|
|
595
|
+
stream.on('error', err => {
|
|
596
|
+
req.destroy()
|
|
597
|
+
reject(err)
|
|
598
|
+
})
|
|
599
|
+
})
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
|
|
603
|
+
const nodeStream = createReadStream(filePath)
|
|
604
|
+
const webStream = Readable.toWeb(nodeStream)
|
|
605
|
+
|
|
606
|
+
const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined
|
|
607
|
+
const response = await fetch(url, {
|
|
608
|
+
...(dispatcher ? { dispatcher } : {}),
|
|
609
|
+
method: 'POST',
|
|
610
|
+
body: webStream,
|
|
611
|
+
headers,
|
|
612
|
+
duplex: 'half',
|
|
613
|
+
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
614
|
+
})
|
|
615
|
+
try {
|
|
616
|
+
return await response.json()
|
|
617
|
+
} catch {
|
|
618
|
+
return undefined
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const uploadMedia = async (params, logger) => {
|
|
623
|
+
if (isNodeRuntime()) {
|
|
624
|
+
logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)')
|
|
625
|
+
return uploadWithNodeHttp(params)
|
|
626
|
+
} else {
|
|
627
|
+
logger?.debug('Using web-standard Fetch API for upload')
|
|
628
|
+
return uploadWithFetch(params)
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
633
|
+
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
|
|
634
|
+
let uploadInfo = await refreshMediaConn(false)
|
|
635
|
+
let urls
|
|
636
|
+
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
|
637
|
+
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
|
638
|
+
const customHeaders = (() => {
|
|
639
|
+
const hdrs = options?.headers
|
|
640
|
+
if (!hdrs) return {}
|
|
641
|
+
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs
|
|
642
|
+
})()
|
|
643
|
+
const headers = { ...customHeaders, 'Content-Type': 'application/octet-stream', Origin: DEFAULT_ORIGIN }
|
|
644
|
+
|
|
645
|
+
for (const { hostname } of hosts) {
|
|
646
|
+
logger.debug(`uploading to "${hostname}"`)
|
|
647
|
+
const auth = encodeURIComponent(uploadInfo.auth)
|
|
648
|
+
const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP
|
|
649
|
+
const serverThumb = newsletter ? '&server_thumb_gen=1' : ''
|
|
650
|
+
const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`
|
|
651
|
+
let result
|
|
652
|
+
try {
|
|
653
|
+
result = await uploadMedia({ url, filePath, headers, timeoutMs, agent: fetchAgent }, logger)
|
|
654
|
+
if (result?.url || result?.direct_path) {
|
|
655
|
+
urls = {
|
|
656
|
+
mediaUrl: result.url,
|
|
657
|
+
directPath: result.direct_path,
|
|
658
|
+
meta_hmac: result.meta_hmac,
|
|
659
|
+
fbid: result.fbid,
|
|
660
|
+
ts: result.ts,
|
|
661
|
+
thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
|
|
662
|
+
thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
|
|
663
|
+
}
|
|
664
|
+
break
|
|
665
|
+
} else {
|
|
666
|
+
uploadInfo = await refreshMediaConn(true)
|
|
667
|
+
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
|
668
|
+
}
|
|
669
|
+
} catch (error) {
|
|
670
|
+
const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
|
|
671
|
+
logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`)
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
if (!urls) throw new Boom('Media upload failed on all hosts', { statusCode: 500 })
|
|
675
|
+
return urls
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const getMediaRetryKey = mediaKey => hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
|
|
680
|
+
|
|
681
|
+
export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
682
|
+
const recp = { stanzaId: key.id }
|
|
683
|
+
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
|
|
684
|
+
const iv = Crypto.randomBytes(12)
|
|
685
|
+
const retryKey = getMediaRetryKey(mediaKey)
|
|
686
|
+
const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id))
|
|
687
|
+
return {
|
|
688
|
+
tag: 'receipt',
|
|
689
|
+
attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' },
|
|
690
|
+
content: [
|
|
691
|
+
|
|
692
|
+
{
|
|
693
|
+
tag: 'encrypt',
|
|
694
|
+
attrs: {},
|
|
695
|
+
content: [
|
|
696
|
+
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
697
|
+
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
698
|
+
]
|
|
699
|
+
},
|
|
700
|
+
{ tag: 'rmr', attrs: { jid: key.remoteJid, from_me: (!!key.fromMe).toString(), participant: key.participant || undefined } }
|
|
701
|
+
]
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
export const decodeMediaRetryNode = node => {
|
|
706
|
+
const rmrNode = getBinaryNodeChild(node, 'rmr')
|
|
707
|
+
const event = {
|
|
708
|
+
key: {
|
|
709
|
+
id: node.attrs.id,
|
|
710
|
+
remoteJid: rmrNode.attrs.jid,
|
|
711
|
+
fromMe: rmrNode.attrs.from_me === 'true',
|
|
712
|
+
participant: rmrNode.attrs.participant
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
const errorNode = getBinaryNodeChild(node, 'error')
|
|
716
|
+
if (errorNode) {
|
|
717
|
+
const errorCode = +errorNode.attrs.code
|
|
718
|
+
event.error = new Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(errorCode) })
|
|
719
|
+
} else {
|
|
720
|
+
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
|
|
721
|
+
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
|
|
722
|
+
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
|
|
723
|
+
if (ciphertext && iv) event.media = { ciphertext, iv }
|
|
724
|
+
else event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
|
725
|
+
}
|
|
726
|
+
return event
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
730
|
+
const retryKey = getMediaRetryKey(mediaKey)
|
|
731
|
+
const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
|
|
732
|
+
return proto.MediaRetryNotification.decode(plaintext)
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
const MEDIA_RETRY_STATUS_MAP = {
|
|
736
|
+
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
737
|
+
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
738
|
+
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
739
|
+
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
740
|
+
}
|
|
741
|
+
export const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code]
|
|
742
|
+
|
|
743
|
+
const THUMBNAIL_WIDTH_PX = 192
|
|
744
|
+
|
|
745
|
+
const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
|
|
746
|
+
const stream = await getHttpStream(url, fetchOpts)
|
|
747
|
+
return extractImageThumb(stream, thumbnailWidth)
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
export const getUrlInfo = async (text, opts = { thumbnailWidth: THUMBNAIL_WIDTH_PX, fetchOpts: { timeout: 3000 } }) => {
|
|
751
|
+
try {
|
|
752
|
+
let retries = 0
|
|
753
|
+
const maxRetry = 5
|
|
754
|
+
let previewLink = text
|
|
755
|
+
if (!text.startsWith('https://') && !text.startsWith('http://')) previewLink = 'https://' + previewLink
|
|
756
|
+
|
|
757
|
+
const info = await getLinkPreview(previewLink, {
|
|
758
|
+
...opts.fetchOpts,
|
|
759
|
+
followRedirects: 'follow',
|
|
760
|
+
handleRedirects: (baseURL, forwardedURL) => {
|
|
761
|
+
const urlObj = new URL(baseURL)
|
|
762
|
+
const forwardedURLObj = new URL(forwardedURL)
|
|
763
|
+
if (retries >= maxRetry) return false
|
|
764
|
+
if (
|
|
765
|
+
forwardedURLObj.hostname === urlObj.hostname ||
|
|
766
|
+
forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
|
|
767
|
+
'www.' + forwardedURLObj.hostname === urlObj.hostname
|
|
768
|
+
) {
|
|
769
|
+
retries += 1
|
|
770
|
+
return true
|
|
771
|
+
}
|
|
772
|
+
return false
|
|
773
|
+
},
|
|
774
|
+
headers: opts.fetchOpts?.headers
|
|
775
|
+
})
|
|
776
|
+
|
|
777
|
+
if (info && 'title' in info && info.title) {
|
|
778
|
+
const [image] = info.images
|
|
779
|
+
const urlInfo = {
|
|
780
|
+
'canonical-url': info.url,
|
|
781
|
+
'matched-text': text,
|
|
782
|
+
title: info.title,
|
|
783
|
+
description: info.description,
|
|
784
|
+
originalThumbnailUrl: image
|
|
785
|
+
}
|
|
786
|
+
if (opts.uploadImage) {
|
|
787
|
+
|
|
788
|
+
const { prepareWAMessageMedia } = await import('./message-compose.js')
|
|
789
|
+
const { imageMessage } = await prepareWAMessageMedia(
|
|
790
|
+
{ image: { url: image } },
|
|
791
|
+
{ upload: opts.uploadImage, mediaTypeOverride: 'thumbnail-link', options: opts.fetchOpts }
|
|
792
|
+
)
|
|
793
|
+
urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined
|
|
794
|
+
urlInfo.highQualityThumbnail = imageMessage || undefined
|
|
795
|
+
} else {
|
|
796
|
+
try {
|
|
797
|
+
urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined
|
|
798
|
+
} catch (error) {
|
|
799
|
+
opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail')
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
return urlInfo
|
|
803
|
+
}
|
|
804
|
+
} catch (error) {
|
|
805
|
+
if (!error.message.includes('receive a valid')) throw error
|
|
806
|
+
}
|
|
807
|
+
}
|