mod-baileys 1.0.3 → 2.0.0
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/README.md +5 -4
- package/lib/Defaults/constants.js +74 -0
- package/lib/Defaults/media.js +48 -0
- package/lib/Utils/messages-media.js +830 -590
- package/lib/Utils/messages.js +1539 -497
- package/lib/WABinary/jid-utils.js +3 -0
- package/package.json +2 -2
|
@@ -1,286 +1,319 @@
|
|
|
1
|
-
"use strict"
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true })
|
|
4
|
+
|
|
5
|
+
const { Boom } = require("@hapi/boom")
|
|
6
|
+
const { exec } = require("child_process")
|
|
7
|
+
const { once } = require("events")
|
|
8
|
+
const {
|
|
9
|
+
createHash,
|
|
10
|
+
randomBytes,
|
|
11
|
+
createHmac,
|
|
12
|
+
createCipheriv,
|
|
13
|
+
createDecipheriv
|
|
14
|
+
} = require("crypto")
|
|
15
|
+
const {
|
|
16
|
+
promises,
|
|
17
|
+
createReadStream,
|
|
18
|
+
createWriteStream
|
|
19
|
+
} = require("fs")
|
|
20
|
+
const {
|
|
21
|
+
parseBuffer,
|
|
22
|
+
parseFile,
|
|
23
|
+
parseStream
|
|
24
|
+
} = require('music-metadata')
|
|
25
|
+
const { tmpdir } = require("os")
|
|
26
|
+
const { join } = require("path")
|
|
27
|
+
const {
|
|
28
|
+
Readable,
|
|
29
|
+
Transform
|
|
30
|
+
} = require("stream")
|
|
31
|
+
const { proto } = require("../../WAProto")
|
|
32
|
+
const {
|
|
33
|
+
MEDIA_PATH_MAP,
|
|
34
|
+
MEDIA_HKDF_KEY_MAPPING
|
|
35
|
+
} = require("../Defaults/media")
|
|
36
|
+
const { DEFAULT_ORIGIN } = require("../Defaults/constants")
|
|
37
|
+
const {
|
|
38
|
+
getBinaryNodeChild,
|
|
39
|
+
getBinaryNodeChildBuffer,
|
|
40
|
+
jidNormalizedUser
|
|
41
|
+
} = require("../WABinary")
|
|
42
|
+
const {
|
|
43
|
+
aesDecryptGCM,
|
|
44
|
+
aesEncryptGCM,
|
|
45
|
+
hkdf
|
|
46
|
+
} = require("./crypto")
|
|
47
|
+
const { generateMessageID } = require("./generics")
|
|
48
|
+
|
|
49
|
+
const getTmpFilesDirectory = () => tmpdir()
|
|
50
|
+
|
|
51
|
+
const getImageProcessingLibrary = () => {
|
|
52
|
+
let sharp, jimp
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
sharp = require('sharp')
|
|
56
|
+
} catch {}
|
|
57
|
+
|
|
54
58
|
if (sharp) {
|
|
55
|
-
return { sharp }
|
|
59
|
+
return { sharp }
|
|
56
60
|
}
|
|
57
|
-
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
jimp = require('jimp')
|
|
64
|
+
} catch {}
|
|
65
|
+
|
|
58
66
|
if (jimp) {
|
|
59
|
-
return { jimp }
|
|
67
|
+
return { jimp }
|
|
60
68
|
}
|
|
61
|
-
|
|
62
|
-
|
|
69
|
+
|
|
70
|
+
throw new Boom('No image processing library available')
|
|
71
|
+
}
|
|
72
|
+
|
|
63
73
|
const hkdfInfoKey = (type) => {
|
|
64
|
-
const hkdfInfo =
|
|
65
|
-
return `WhatsApp ${hkdfInfo} Keys
|
|
66
|
-
}
|
|
67
|
-
|
|
74
|
+
const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type]
|
|
75
|
+
return `WhatsApp ${hkdfInfo} Keys`
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const getRawMediaUploadData = async (media, mediaType, logger) => {
|
|
79
|
+
const { stream } = await getStream(media)
|
|
80
|
+
|
|
81
|
+
logger?.debug('got stream for raw upload')
|
|
82
|
+
|
|
83
|
+
const hasher = createHash('sha256')
|
|
84
|
+
const filePath = join(getTmpFilesDirectory(), mediaType + generateMessageID())
|
|
85
|
+
const fileWriteStream = createWriteStream(filePath)
|
|
86
|
+
|
|
87
|
+
let fileLength = 0
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
for await (const data of stream) {
|
|
91
|
+
fileLength += data.length
|
|
92
|
+
hasher.update(data)
|
|
93
|
+
|
|
94
|
+
if (!fileWriteStream.write(data)) {
|
|
95
|
+
await once(fileWriteStream, 'drain')
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
fileWriteStream.end()
|
|
100
|
+
await once(fileWriteStream, 'finish')
|
|
101
|
+
stream.destroy()
|
|
102
|
+
|
|
103
|
+
const fileSha256 = hasher.digest()
|
|
104
|
+
|
|
105
|
+
logger?.debug('hashed data for raw upload')
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
filePath: filePath,
|
|
109
|
+
fileSha256,
|
|
110
|
+
fileLength
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
fileWriteStream.destroy()
|
|
115
|
+
stream.destroy()
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
await promises.unlink(filePath)
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
//
|
|
122
|
+
}
|
|
123
|
+
throw error
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
68
127
|
/** generates all the keys required to encrypt/decrypt & sign a media message */
|
|
69
|
-
function getMediaKeys(buffer, mediaType) {
|
|
128
|
+
async function getMediaKeys(buffer, mediaType) {
|
|
70
129
|
if (!buffer) {
|
|
71
|
-
throw new
|
|
130
|
+
throw new Boom('Cannot derive from empty media key')
|
|
72
131
|
}
|
|
73
132
|
if (typeof buffer === 'string') {
|
|
74
|
-
buffer = Buffer.from(buffer.replace('data
|
|
133
|
+
buffer = Buffer.from(buffer.replace('data:base64,', ''), 'base64')
|
|
75
134
|
}
|
|
76
135
|
// expand using HKDF to 112 bytes, also pass in the relevant app info
|
|
77
|
-
const expandedMediaKey =
|
|
136
|
+
const expandedMediaKey = await hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
|
|
78
137
|
return {
|
|
79
138
|
iv: expandedMediaKey.slice(0, 16),
|
|
80
139
|
cipherKey: expandedMediaKey.slice(16, 48),
|
|
81
|
-
macKey: expandedMediaKey.slice(48, 80)
|
|
82
|
-
}
|
|
140
|
+
macKey: expandedMediaKey.slice(48, 80)
|
|
141
|
+
}
|
|
83
142
|
}
|
|
84
|
-
|
|
143
|
+
|
|
85
144
|
/** Extracts video thumb using FFMPEG */
|
|
86
145
|
const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
|
|
87
|
-
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}
|
|
88
|
-
|
|
146
|
+
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`
|
|
147
|
+
exec(cmd, err => {
|
|
89
148
|
if (err) {
|
|
90
|
-
reject(err)
|
|
149
|
+
reject(err)
|
|
91
150
|
}
|
|
92
151
|
else {
|
|
93
|
-
resolve()
|
|
94
|
-
}
|
|
95
|
-
})
|
|
96
|
-
})
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
152
|
+
resolve()
|
|
153
|
+
}
|
|
154
|
+
})
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
const extractImageThumb = async (bufferOrFilePath, width = 32, quality = 50) => {
|
|
158
|
+
// TODO: Move entirely to sharp, removing jimp as it supports readable streams
|
|
159
|
+
// This will have positive speed and performance impacts as well as minimizing RAM usage.
|
|
160
|
+
if (bufferOrFilePath instanceof Readable) {
|
|
161
|
+
bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const lib = await getImageProcessingLibrary()
|
|
165
|
+
|
|
166
|
+
if ('sharp' in lib && typeof lib.sharp === 'function') {
|
|
167
|
+
const img = lib.sharp(bufferOrFilePath)
|
|
168
|
+
const dimensions = await img.metadata()
|
|
169
|
+
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer()
|
|
110
170
|
return {
|
|
111
171
|
buffer,
|
|
112
172
|
original: {
|
|
113
173
|
width: dimensions.width,
|
|
114
|
-
height: dimensions.height
|
|
115
|
-
}
|
|
116
|
-
}
|
|
174
|
+
height: dimensions.height
|
|
175
|
+
}
|
|
176
|
+
}
|
|
117
177
|
}
|
|
118
|
-
else if ('jimp' in lib && typeof
|
|
119
|
-
|
|
120
|
-
const jimp = await read(bufferOrFilePath)
|
|
178
|
+
else if ('jimp' in lib && typeof lib.jimp.read === 'function') {
|
|
179
|
+
const { read, MIME_JPEG, RESIZE_BEZIER, AUTO } = lib.jimp
|
|
180
|
+
const jimp = await read(bufferOrFilePath)
|
|
121
181
|
const dimensions = {
|
|
122
182
|
width: jimp.getWidth(),
|
|
123
|
-
height: jimp.getHeight()
|
|
124
|
-
}
|
|
183
|
+
height: jimp.getHeight()
|
|
184
|
+
}
|
|
125
185
|
const buffer = await jimp
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
186
|
+
.quality(quality)
|
|
187
|
+
.resize(width, AUTO, RESIZE_BEZIER)
|
|
188
|
+
.getBufferAsync(MIME_JPEG)
|
|
129
189
|
return {
|
|
130
190
|
buffer,
|
|
131
191
|
original: dimensions
|
|
132
|
-
}
|
|
192
|
+
}
|
|
133
193
|
}
|
|
134
194
|
else {
|
|
135
|
-
throw new
|
|
195
|
+
throw new Boom('No image processing library available')
|
|
136
196
|
}
|
|
137
|
-
}
|
|
138
|
-
|
|
197
|
+
}
|
|
198
|
+
|
|
139
199
|
const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
|
|
140
200
|
.replace(/\+/g, '-')
|
|
141
201
|
.replace(/\//g, '_')
|
|
142
|
-
.replace(/\=+$/, '')))
|
|
143
|
-
|
|
144
|
-
const generateProfilePicture = async (mediaUpload) => {
|
|
145
|
-
|
|
146
|
-
|
|
202
|
+
.replace(/\=+$/, '')))
|
|
203
|
+
|
|
204
|
+
const generateProfilePicture = async (mediaUpload, dimensions) => {
|
|
205
|
+
let buffer
|
|
206
|
+
|
|
207
|
+
const { width: w = 640, height: h = 640 } = dimensions || {}
|
|
208
|
+
|
|
147
209
|
if (Buffer.isBuffer(mediaUpload)) {
|
|
148
|
-
|
|
149
|
-
}
|
|
150
|
-
else if ('url' in mediaUpload) {
|
|
151
|
-
bufferOrFilePath = mediaUpload.url.toString();
|
|
210
|
+
buffer = mediaUpload
|
|
152
211
|
}
|
|
153
212
|
else {
|
|
154
|
-
|
|
213
|
+
// Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
|
|
214
|
+
const { stream } = await getStream(mediaUpload)
|
|
215
|
+
// Convert the resulting stream to a buffer
|
|
216
|
+
buffer = await toBuffer(stream)
|
|
155
217
|
}
|
|
156
|
-
const lib = await getImageProcessingLibrary()
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
218
|
+
const lib = await getImageProcessingLibrary()
|
|
219
|
+
|
|
220
|
+
let img
|
|
221
|
+
|
|
222
|
+
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
223
|
+
img = lib.sharp
|
|
224
|
+
.default(buffer)
|
|
225
|
+
.resize(w, h)
|
|
161
226
|
.jpeg({
|
|
162
|
-
quality: 50
|
|
163
|
-
})
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
const cropped = jimp.crop(0, 0, min, min);
|
|
171
|
-
img = cropped
|
|
172
|
-
.quality(50)
|
|
173
|
-
.resize(640, 640, RESIZE_BILINEAR)
|
|
174
|
-
.getBufferAsync(MIME_JPEG);
|
|
227
|
+
quality: 50
|
|
228
|
+
}).toBuffer()
|
|
229
|
+
}
|
|
230
|
+
else if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
|
231
|
+
const jimp = await lib.jimp.read(buffer)
|
|
232
|
+
const min = Math.min(jimp.width, jimp.height)
|
|
233
|
+
const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min })
|
|
234
|
+
img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 })
|
|
175
235
|
}
|
|
176
236
|
else {
|
|
177
|
-
throw new
|
|
237
|
+
throw new Boom('No image processing library available');
|
|
178
238
|
}
|
|
179
239
|
return {
|
|
180
|
-
img: await img
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
|
|
240
|
+
img: await img
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
184
244
|
/** gets the SHA256 of the given media message */
|
|
185
245
|
const mediaMessageSHA256B64 = (message) => {
|
|
186
|
-
const media = Object.values(message)[0]
|
|
187
|
-
return
|
|
188
|
-
}
|
|
189
|
-
|
|
246
|
+
const media = Object.values(message)[0]
|
|
247
|
+
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64')
|
|
248
|
+
}
|
|
249
|
+
|
|
190
250
|
async function getAudioDuration(buffer) {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
ff(inputStream)
|
|
200
|
-
.ffprobe((err, data) => {
|
|
201
|
-
if (err) reject(err);
|
|
202
|
-
else resolve(data.format.duration);
|
|
203
|
-
});
|
|
204
|
-
});
|
|
205
|
-
} catch (error) {
|
|
206
|
-
const musicMetadata = await import('music-metadata');
|
|
207
|
-
let metadata;
|
|
208
|
-
if (Buffer.isBuffer(buffer)) {
|
|
209
|
-
metadata = await musicMetadata.parseBuffer(buffer, undefined, {
|
|
210
|
-
duration: true
|
|
211
|
-
});
|
|
212
|
-
} else if (typeof buffer === 'string') {
|
|
213
|
-
const rStream = (0, fs_1.createReadStream)(buffer);
|
|
214
|
-
try {
|
|
215
|
-
metadata = await musicMetadata.parseStream(rStream, undefined, {
|
|
216
|
-
duration: true
|
|
217
|
-
});
|
|
218
|
-
} finally {
|
|
219
|
-
rStream.destroy();
|
|
220
|
-
}
|
|
221
|
-
} else {
|
|
222
|
-
metadata = await musicMetadata.parseStream(buffer, undefined, {
|
|
223
|
-
duration: true
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
return metadata.format.duration;
|
|
251
|
+
const options = {
|
|
252
|
+
duration: true
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
let metadata
|
|
256
|
+
|
|
257
|
+
if (Buffer.isBuffer(buffer)) {
|
|
258
|
+
metadata = await parseBuffer(buffer, undefined, options)
|
|
227
259
|
}
|
|
260
|
+
else if (typeof buffer === 'string') {
|
|
261
|
+
metadata = await parseFile(buffer, options)
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
metadata = await parseStream(buffer, undefined, options)
|
|
265
|
+
}
|
|
266
|
+
return metadata.format?.duration
|
|
228
267
|
}
|
|
229
|
-
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
|
|
271
|
+
*/
|
|
230
272
|
async function getAudioWaveform(buffer, logger) {
|
|
231
273
|
try {
|
|
232
|
-
const {
|
|
233
|
-
const ff = require('fluent-ffmpeg');
|
|
274
|
+
const { default: decoder } = await eval('import(\'audio-decode\')')
|
|
234
275
|
|
|
235
|
-
let audioData
|
|
276
|
+
let audioData
|
|
277
|
+
|
|
236
278
|
if (Buffer.isBuffer(buffer)) {
|
|
237
|
-
audioData = buffer
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
279
|
+
audioData = buffer
|
|
280
|
+
}
|
|
281
|
+
else if (typeof buffer === 'string') {
|
|
282
|
+
const rStream = createReadStream(buffer)
|
|
283
|
+
audioData = await toBuffer(rStream)
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
audioData = await toBuffer(buffer)
|
|
243
287
|
}
|
|
244
288
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
.
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
const max = Math.max(...avg);
|
|
273
|
-
const normalized = avg.map(v => Math.floor((v / max) * 100));
|
|
274
|
-
resolve(new Uint8Array(normalized));
|
|
275
|
-
})
|
|
276
|
-
.pipe()
|
|
277
|
-
.on('data', chunk => chunks.push(chunk));
|
|
278
|
-
});
|
|
279
|
-
} catch (e) {
|
|
280
|
-
logger?.debug(e);
|
|
289
|
+
const audioBuffer = await decoder(audioData)
|
|
290
|
+
const rawData = audioBuffer.getChannelData(0) // We only need to work with one channel of data
|
|
291
|
+
const samples = 64 // Number of samples we want to have in our final data set
|
|
292
|
+
const blockSize = Math.floor(rawData.length / samples) // the number of samples in each subdivision
|
|
293
|
+
const filteredData = []
|
|
294
|
+
|
|
295
|
+
for (let i = 0; i < samples; i++) {
|
|
296
|
+
const blockStart = blockSize * i // the location of the first sample in the block
|
|
297
|
+
let sum = 0
|
|
298
|
+
for (let j = 0; j < blockSize; j++) {
|
|
299
|
+
sum = sum + Math.abs(rawData[blockStart + j]) // find the sum of all the samples in the block
|
|
300
|
+
}
|
|
301
|
+
filteredData.push(sum / blockSize) // divide the sum by the block size to get the average
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
|
305
|
+
const multiplier = Math.pow(Math.max(...filteredData), -1)
|
|
306
|
+
const normalizedData = filteredData.map((n) => n * multiplier)
|
|
307
|
+
|
|
308
|
+
// Generate waveform like WhatsApp
|
|
309
|
+
const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)))
|
|
310
|
+
return waveform
|
|
311
|
+
}
|
|
312
|
+
catch (e) {
|
|
313
|
+
logger?.debug('Failed to generate waveform: ' + e)
|
|
281
314
|
}
|
|
282
315
|
}
|
|
283
|
-
|
|
316
|
+
|
|
284
317
|
async function convertToOpusBuffer(buffer, logger) {
|
|
285
318
|
try {
|
|
286
319
|
const { PassThrough } = require('stream');
|
|
@@ -319,479 +352,659 @@ async function convertToOpusBuffer(buffer, logger) {
|
|
|
319
352
|
throw e;
|
|
320
353
|
}
|
|
321
354
|
}
|
|
322
|
-
|
|
355
|
+
|
|
323
356
|
const toReadable = (buffer) => {
|
|
324
|
-
const readable = new
|
|
325
|
-
readable.push(buffer)
|
|
326
|
-
readable.push(null)
|
|
327
|
-
return readable
|
|
328
|
-
}
|
|
329
|
-
|
|
357
|
+
const readable = new Readable({ read: () => { } })
|
|
358
|
+
readable.push(buffer)
|
|
359
|
+
readable.push(null)
|
|
360
|
+
return readable
|
|
361
|
+
}
|
|
362
|
+
|
|
330
363
|
const toBuffer = async (stream) => {
|
|
331
|
-
const chunks = []
|
|
364
|
+
const chunks = []
|
|
332
365
|
for await (const chunk of stream) {
|
|
333
|
-
chunks.push(chunk)
|
|
366
|
+
chunks.push(chunk)
|
|
334
367
|
}
|
|
335
|
-
stream.destroy()
|
|
336
|
-
return Buffer.concat(chunks)
|
|
337
|
-
}
|
|
338
|
-
|
|
368
|
+
stream.destroy()
|
|
369
|
+
return Buffer.concat(chunks)
|
|
370
|
+
}
|
|
371
|
+
|
|
339
372
|
const getStream = async (item, opts) => {
|
|
340
373
|
if (Buffer.isBuffer(item)) {
|
|
341
|
-
return { stream:
|
|
374
|
+
return { stream: toReadable(item), type: 'buffer' }
|
|
342
375
|
}
|
|
376
|
+
|
|
343
377
|
if ('stream' in item) {
|
|
344
|
-
return { stream: item.stream, type: 'readable' }
|
|
378
|
+
return { stream: item.stream, type: 'readable' }
|
|
345
379
|
}
|
|
346
|
-
|
|
347
|
-
|
|
380
|
+
|
|
381
|
+
const urlStr = item.url.toString()
|
|
382
|
+
|
|
383
|
+
if (urlStr.startsWith('data:')) {
|
|
384
|
+
const buffer = Buffer.from(urlStr.split(',')[1], 'base64')
|
|
385
|
+
return { stream: await toReadable(buffer), type: 'buffer' }
|
|
348
386
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
387
|
+
|
|
388
|
+
if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
|
|
389
|
+
return { stream: await getHttpStream(item.url, opts), type: 'remote' }
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
return { stream: createReadStream(item.url), type: 'file' }
|
|
393
|
+
}
|
|
394
|
+
|
|
352
395
|
/** generates a thumbnail for a given media, if required */
|
|
353
396
|
async function generateThumbnail(file, mediaType, options) {
|
|
354
|
-
|
|
355
|
-
let
|
|
356
|
-
|
|
397
|
+
let thumbnail
|
|
398
|
+
let originalImageDimensions
|
|
399
|
+
|
|
357
400
|
if (mediaType === 'image') {
|
|
358
|
-
const { buffer, original } = await
|
|
359
|
-
|
|
401
|
+
const { buffer, original } = await extractImageThumb(file)
|
|
402
|
+
|
|
403
|
+
thumbnail = buffer.toString('base64')
|
|
404
|
+
|
|
360
405
|
if (original.width && original.height) {
|
|
361
406
|
originalImageDimensions = {
|
|
362
407
|
width: original.width,
|
|
363
|
-
height: original.height
|
|
364
|
-
}
|
|
408
|
+
height: original.height
|
|
409
|
+
}
|
|
365
410
|
}
|
|
366
411
|
}
|
|
367
412
|
else if (mediaType === 'video') {
|
|
368
|
-
const imgFilename =
|
|
413
|
+
const imgFilename = join(getTmpFilesDirectory(), generateMessageID() + '.jpg')
|
|
369
414
|
try {
|
|
370
|
-
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 })
|
|
371
|
-
const buff = await
|
|
372
|
-
|
|
373
|
-
|
|
415
|
+
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 })
|
|
416
|
+
const buff = await promises.readFile(imgFilename)
|
|
417
|
+
|
|
418
|
+
thumbnail = buff.toString('base64')
|
|
419
|
+
|
|
420
|
+
await promises.unlink(imgFilename)
|
|
374
421
|
}
|
|
375
422
|
catch (err) {
|
|
376
|
-
|
|
423
|
+
options.logger?.debug('could not generate video thumb: ' + err)
|
|
377
424
|
}
|
|
378
425
|
}
|
|
379
426
|
return {
|
|
380
427
|
thumbnail,
|
|
381
428
|
originalImageDimensions
|
|
382
|
-
}
|
|
429
|
+
}
|
|
383
430
|
}
|
|
384
|
-
|
|
431
|
+
|
|
385
432
|
const getHttpStream = async (url, options = {}) => {
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
433
|
+
const response = await fetch(url.toString(), {
|
|
434
|
+
dispatcher: options.dispatcher,
|
|
435
|
+
method: 'GET',
|
|
436
|
+
headers: options.headers
|
|
437
|
+
})
|
|
438
|
+
|
|
439
|
+
if (!response.ok) {
|
|
440
|
+
throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } })
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body)
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/*const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
447
|
+
const { stream, type } = await getStream(media, opts)
|
|
448
|
+
logger?.debug('fetched media stream')
|
|
449
|
+
|
|
450
|
+
const encFilePath = join(tmpdir(), mediaType + generateMessageID() + '-plain')
|
|
451
|
+
const encFileWriteStream = createWriteStream(encFilePath)
|
|
452
|
+
|
|
453
|
+
let originalFilePath
|
|
454
|
+
let originalFileStream
|
|
455
|
+
|
|
456
|
+
if (type === 'file') {
|
|
457
|
+
originalFilePath = media.url.toString()
|
|
458
|
+
} else if (saveOriginalFileIfRequired) {
|
|
459
|
+
originalFilePath = join(tmpdir(), mediaType + generateMessageID() + '-original')
|
|
460
|
+
originalFileStream = createWriteStream(originalFilePath)
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
let fileLength = 0
|
|
464
|
+
const sha256 = createHash('sha256')
|
|
465
|
+
|
|
396
466
|
try {
|
|
397
|
-
if (type === 'file') {
|
|
398
|
-
bodyPath = media.url;
|
|
399
|
-
}
|
|
400
|
-
else {
|
|
401
|
-
bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageID)());
|
|
402
|
-
didSaveToTmpPath = true;
|
|
403
|
-
}
|
|
404
|
-
const writeStream = didSaveToTmpPath ? (0, fs_1.createWriteStream)(bodyPath) : undefined;
|
|
405
|
-
let fileLength = 0;
|
|
406
|
-
const fileSha256Hash = Crypto.createHash('sha256');
|
|
407
467
|
for await (const data of stream) {
|
|
408
|
-
fileLength += data.length
|
|
409
|
-
|
|
410
|
-
if (
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
}
|
|
468
|
+
fileLength += data.length
|
|
469
|
+
|
|
470
|
+
if (type === 'remote'
|
|
471
|
+
&& opts?.maxContentLength
|
|
472
|
+
&& fileLength + data.length > opts.maxContentLength) {
|
|
473
|
+
throw new Boom(`content length exceeded when preparing "${type}"`, {
|
|
474
|
+
data: { media, type }
|
|
475
|
+
})
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
sha256.update(data)
|
|
479
|
+
encFileWriteStream.write(data)
|
|
480
|
+
|
|
481
|
+
if (originalFileStream && !originalFileStream.write(data)) {
|
|
482
|
+
await once(originalFileStream, 'drain')
|
|
414
483
|
}
|
|
415
484
|
}
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
logger === null || logger === void 0 ? void 0 : logger.debug('prepare stream data successfully');
|
|
485
|
+
|
|
486
|
+
const fileSha256 = sha256.digest()
|
|
487
|
+
encFileWriteStream.end()
|
|
488
|
+
originalFileStream?.end?.call(originalFileStream)
|
|
489
|
+
stream.destroy()
|
|
490
|
+
|
|
491
|
+
logger?.debug('prepared plain stream successfully')
|
|
492
|
+
|
|
425
493
|
return {
|
|
426
494
|
mediaKey: undefined,
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
495
|
+
originalFilePath,
|
|
496
|
+
encFilePath,
|
|
497
|
+
mac: undefined,
|
|
430
498
|
fileEncSha256: undefined,
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
}
|
|
499
|
+
fileSha256,
|
|
500
|
+
fileLength
|
|
501
|
+
}
|
|
434
502
|
}
|
|
435
503
|
catch (error) {
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
504
|
+
encFileWriteStream.destroy()
|
|
505
|
+
originalFileStream?.destroy?.call(originalFileStream)
|
|
506
|
+
sha256.destroy()
|
|
507
|
+
stream.destroy()
|
|
508
|
+
try {
|
|
509
|
+
await promises.unlink(encFilePath)
|
|
510
|
+
if (originalFilePath && didSaveToTmpPath) {
|
|
511
|
+
await promises.unlink(originalFilePath)
|
|
444
512
|
}
|
|
513
|
+
} catch (err) {
|
|
514
|
+
logger?.error({ err }, 'failed deleting tmp files')
|
|
445
515
|
}
|
|
446
|
-
throw error
|
|
516
|
+
throw error
|
|
447
517
|
}
|
|
448
|
-
}
|
|
449
|
-
|
|
518
|
+
}*/
|
|
519
|
+
|
|
450
520
|
const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
|
|
451
|
-
const { stream, type } = await
|
|
521
|
+
const { stream, type } = await getStream(media, opts)
|
|
452
522
|
|
|
453
523
|
let finalStream = stream;
|
|
454
524
|
if (mediaType === 'audio' && (isPtt === true || forceOpus === true)) {
|
|
455
525
|
try {
|
|
456
|
-
const buffer = await
|
|
457
|
-
const opusBuffer = await
|
|
458
|
-
finalStream =
|
|
526
|
+
const buffer = await toBuffer(stream);
|
|
527
|
+
const opusBuffer = await convertToOpusBuffer(buffer, logger);
|
|
528
|
+
finalStream = toReadable(opusBuffer);
|
|
459
529
|
} catch (error) {
|
|
460
|
-
|
|
530
|
+
if (isPtt) {
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
533
|
+
const { stream: newStream } = await getStream(media, opts);
|
|
461
534
|
finalStream = newStream;
|
|
462
535
|
}
|
|
463
536
|
}
|
|
464
537
|
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
const
|
|
468
|
-
const
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
538
|
+
logger?.debug('fetched media stream')
|
|
539
|
+
|
|
540
|
+
const mediaKey = randomBytes(32)
|
|
541
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
|
|
542
|
+
const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageID() + '-enc')
|
|
543
|
+
const encFileWriteStream = createWriteStream(encFilePath)
|
|
544
|
+
|
|
545
|
+
let originalFileStream;
|
|
546
|
+
let originalFilePath
|
|
547
|
+
|
|
548
|
+
if (saveOriginalFileIfRequired) {
|
|
549
|
+
originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageID() + '-original')
|
|
550
|
+
originalFileStream = createWriteStream(originalFilePath)
|
|
475
551
|
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
552
|
+
|
|
553
|
+
let fileLength = 0
|
|
554
|
+
|
|
555
|
+
const aes = createCipheriv('aes-256-cbc', cipherKey, iv)
|
|
556
|
+
const hmac = createHmac('sha256', macKey).update(iv)
|
|
557
|
+
const sha256Plain = createHash('sha256');
|
|
558
|
+
const sha256Enc = createHash('sha256')
|
|
559
|
+
|
|
560
|
+
const onChunk = async (buff) => {
|
|
561
|
+
sha256Enc.update(buff)
|
|
562
|
+
hmac.update(buff)
|
|
563
|
+
|
|
564
|
+
// Handle backpressure: if write returns false, wait for drain
|
|
565
|
+
if (!encFileWriteStream.write(buff)) {
|
|
566
|
+
await once(encFileWriteStream, 'drain')
|
|
567
|
+
}
|
|
480
568
|
}
|
|
481
|
-
|
|
482
|
-
let fileLength = 0;
|
|
483
|
-
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
|
|
484
|
-
let hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
|
485
|
-
let sha256Plain = Crypto.createHash('sha256');
|
|
486
|
-
let sha256Enc = Crypto.createHash('sha256');
|
|
487
|
-
|
|
569
|
+
|
|
488
570
|
try {
|
|
489
|
-
for await (const data of
|
|
490
|
-
fileLength += data.length
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
571
|
+
for await (const data of stream) {
|
|
572
|
+
fileLength += data.length
|
|
573
|
+
|
|
574
|
+
if (type === 'remote' &&
|
|
575
|
+
opts?.maxContentLength &&
|
|
576
|
+
fileLength + data.length > opts.maxContentLength) {
|
|
577
|
+
throw new Boom(`content length exceeded when encrypting "${type}"`, {
|
|
495
578
|
data: { media, type }
|
|
496
|
-
})
|
|
579
|
+
})
|
|
497
580
|
}
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
await (0, events_1.once)(writeStream, 'drain');
|
|
581
|
+
|
|
582
|
+
if (originalFileStream) {
|
|
583
|
+
if (!originalFileStream.write(data)) {
|
|
584
|
+
await once(originalFileStream, 'drain')
|
|
503
585
|
}
|
|
504
586
|
}
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
await (0, events_1.once)(encWriteStream, 'drain');
|
|
510
|
-
}
|
|
587
|
+
|
|
588
|
+
sha256Plain.update(data)
|
|
589
|
+
|
|
590
|
+
await onChunk(aes.update(data))
|
|
511
591
|
}
|
|
512
|
-
|
|
513
|
-
const encFinal = aes.final();
|
|
514
|
-
sha256Enc = sha256Enc.update(encFinal);
|
|
515
|
-
hmac = hmac.update(encFinal);
|
|
516
|
-
if (!encWriteStream.write(encFinal)) {
|
|
517
|
-
await (0, events_1.once)(encWriteStream, 'drain');
|
|
518
|
-
}
|
|
519
|
-
const mac = hmac.digest().slice(0, 10);
|
|
520
|
-
sha256Enc = sha256Enc.update(mac);
|
|
521
|
-
const fileSha256 = sha256Plain.digest();
|
|
522
|
-
const fileEncSha256 = sha256Enc.digest();
|
|
523
|
-
|
|
524
|
-
encWriteStream.write(mac);
|
|
525
|
-
encWriteStream.end();
|
|
526
|
-
|
|
527
|
-
writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
|
|
528
|
-
|
|
529
|
-
await new Promise((resolve, reject) => {
|
|
530
|
-
encWriteStream.on('finish', resolve);
|
|
531
|
-
encWriteStream.on('error', reject);
|
|
532
|
-
});
|
|
533
592
|
|
|
534
|
-
|
|
535
|
-
|
|
593
|
+
await onChunk(aes.final())
|
|
594
|
+
const mac = hmac.digest().slice(0, 10)
|
|
595
|
+
|
|
596
|
+
sha256Enc.update(mac)
|
|
597
|
+
|
|
598
|
+
const fileSha256 = sha256Plain.digest()
|
|
599
|
+
const fileEncSha256 = sha256Enc.digest()
|
|
600
|
+
|
|
601
|
+
encFileWriteStream.write(mac)
|
|
602
|
+
|
|
603
|
+
const encFinishPromise = once(encFileWriteStream, 'finish')
|
|
604
|
+
const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve()
|
|
605
|
+
|
|
606
|
+
encFileWriteStream.end()
|
|
607
|
+
originalFileStream?.end?.()
|
|
608
|
+
stream.destroy()
|
|
609
|
+
|
|
610
|
+
// Wait for write streams to fully flush to disk
|
|
611
|
+
// This helps reduce memory pressure by allowing OS to release buffers
|
|
612
|
+
await encFinishPromise
|
|
613
|
+
await originalFinishPromise
|
|
614
|
+
|
|
615
|
+
logger?.debug('encrypted data successfully')
|
|
616
|
+
|
|
536
617
|
return {
|
|
537
618
|
mediaKey,
|
|
538
|
-
|
|
539
|
-
|
|
619
|
+
originalFilePath,
|
|
620
|
+
encFilePath,
|
|
540
621
|
mac,
|
|
541
622
|
fileEncSha256,
|
|
542
623
|
fileSha256,
|
|
543
|
-
fileLength
|
|
544
|
-
|
|
545
|
-
};
|
|
624
|
+
fileLength
|
|
625
|
+
}
|
|
546
626
|
}
|
|
547
627
|
catch (error) {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
628
|
+
// destroy all streams with error
|
|
629
|
+
encFileWriteStream.destroy()
|
|
630
|
+
originalFileStream?.destroy?.()
|
|
631
|
+
aes.destroy()
|
|
632
|
+
hmac.destroy()
|
|
633
|
+
sha256Plain.destroy()
|
|
634
|
+
sha256Enc.destroy()
|
|
635
|
+
stream.destroy()
|
|
636
|
+
|
|
556
637
|
try {
|
|
557
|
-
await
|
|
558
|
-
}
|
|
559
|
-
catch (err) {
|
|
560
|
-
}
|
|
638
|
+
await promises.unlink(encFilePath)
|
|
561
639
|
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
await fs_1.promises.unlink(bodyPath);
|
|
565
|
-
}
|
|
566
|
-
catch (err) {
|
|
640
|
+
if (originalFilePath) {
|
|
641
|
+
await promises.unlink(originalFilePath)
|
|
567
642
|
}
|
|
568
643
|
}
|
|
569
|
-
|
|
644
|
+
catch (err) {
|
|
645
|
+
logger?.error({ err }, 'failed deleting tmp files')
|
|
646
|
+
}
|
|
647
|
+
throw error
|
|
570
648
|
}
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
const DEF_HOST = 'mmg.whatsapp.net'
|
|
574
|
-
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const DEF_HOST = 'mmg.whatsapp.net'
|
|
652
|
+
|
|
653
|
+
const AES_CHUNK_SIZE = 16
|
|
654
|
+
|
|
575
655
|
const toSmallestChunkSize = (num) => {
|
|
576
|
-
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
|
|
577
|
-
}
|
|
578
|
-
const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}
|
|
579
|
-
|
|
580
|
-
const downloadContentFromMessage = ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
581
|
-
|
|
582
|
-
const
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
656
|
+
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
|
|
657
|
+
}
|
|
658
|
+
const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`
|
|
659
|
+
|
|
660
|
+
const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
661
|
+
const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/')
|
|
662
|
+
const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath)
|
|
663
|
+
|
|
664
|
+
if (!downloadUrl) {
|
|
665
|
+
throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 })
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const keys = await getMediaKeys(mediaKey, type)
|
|
669
|
+
return downloadEncryptedContent(downloadUrl, keys, opts)
|
|
670
|
+
}
|
|
671
|
+
|
|
586
672
|
/**
|
|
587
673
|
* Decrypts and downloads an AES256-CBC encrypted file given the keys.
|
|
588
674
|
* Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
|
|
589
675
|
* */
|
|
590
676
|
const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
591
|
-
let bytesFetched = 0
|
|
592
|
-
let startChunk = 0
|
|
593
|
-
let firstBlockIsIV = false
|
|
677
|
+
let bytesFetched = 0
|
|
678
|
+
let startChunk = 0
|
|
679
|
+
let firstBlockIsIV = false
|
|
680
|
+
|
|
594
681
|
// if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
|
|
595
682
|
if (startByte) {
|
|
596
|
-
const chunk = toSmallestChunkSize(startByte || 0)
|
|
683
|
+
const chunk = toSmallestChunkSize(startByte || 0)
|
|
684
|
+
|
|
597
685
|
if (chunk) {
|
|
598
|
-
startChunk = chunk - AES_CHUNK_SIZE
|
|
599
|
-
bytesFetched = chunk
|
|
600
|
-
firstBlockIsIV = true
|
|
686
|
+
startChunk = chunk - AES_CHUNK_SIZE
|
|
687
|
+
bytesFetched = chunk
|
|
688
|
+
firstBlockIsIV = true
|
|
601
689
|
}
|
|
602
690
|
}
|
|
603
|
-
|
|
691
|
+
|
|
692
|
+
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
|
693
|
+
const headersInit = options?.headers ? options.headers : undefined
|
|
604
694
|
const headers = {
|
|
605
|
-
...(
|
|
606
|
-
|
|
607
|
-
|
|
695
|
+
...(headersInit
|
|
696
|
+
? Array.isArray(headersInit)
|
|
697
|
+
? Object.fromEntries(headersInit)
|
|
698
|
+
: headersInit
|
|
699
|
+
: {}),
|
|
700
|
+
Origin: DEFAULT_ORIGIN
|
|
701
|
+
}
|
|
702
|
+
|
|
608
703
|
if (startChunk || endChunk) {
|
|
609
|
-
headers.Range = `bytes=${startChunk}
|
|
704
|
+
headers.Range = `bytes=${startChunk}-`
|
|
705
|
+
|
|
610
706
|
if (endChunk) {
|
|
611
|
-
headers.Range += endChunk
|
|
707
|
+
headers.Range += endChunk
|
|
612
708
|
}
|
|
613
709
|
}
|
|
710
|
+
|
|
614
711
|
// download the message
|
|
615
|
-
const fetched = await
|
|
616
|
-
...options || {},
|
|
617
|
-
headers
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
let
|
|
622
|
-
|
|
712
|
+
const fetched = await getHttpStream(downloadUrl, {
|
|
713
|
+
...(options || {}),
|
|
714
|
+
headers
|
|
715
|
+
})
|
|
716
|
+
|
|
717
|
+
let remainingBytes = Buffer.from([])
|
|
718
|
+
let aes
|
|
719
|
+
|
|
623
720
|
const pushBytes = (bytes, push) => {
|
|
624
721
|
if (startByte || endByte) {
|
|
625
|
-
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
|
|
626
|
-
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
|
|
627
|
-
|
|
628
|
-
|
|
722
|
+
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
|
|
723
|
+
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
|
|
724
|
+
|
|
725
|
+
push(bytes.slice(start, end))
|
|
726
|
+
bytesFetched += bytes.length
|
|
629
727
|
}
|
|
630
728
|
else {
|
|
631
|
-
push(bytes)
|
|
729
|
+
push(bytes)
|
|
632
730
|
}
|
|
633
|
-
}
|
|
634
|
-
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const output = new Transform({
|
|
635
734
|
transform(chunk, _, callback) {
|
|
636
|
-
let data = Buffer.concat([remainingBytes, chunk])
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
735
|
+
let data = Buffer.concat([remainingBytes, chunk])
|
|
736
|
+
|
|
737
|
+
const decryptLength = toSmallestChunkSize(data.length)
|
|
738
|
+
|
|
739
|
+
remainingBytes = data.slice(decryptLength)
|
|
740
|
+
data = data.slice(0, decryptLength)
|
|
741
|
+
|
|
640
742
|
if (!aes) {
|
|
641
|
-
let ivValue = iv
|
|
743
|
+
let ivValue = iv
|
|
744
|
+
|
|
642
745
|
if (firstBlockIsIV) {
|
|
643
|
-
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
|
644
|
-
data = data.slice(AES_CHUNK_SIZE)
|
|
746
|
+
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
|
747
|
+
data = data.slice(AES_CHUNK_SIZE)
|
|
645
748
|
}
|
|
646
|
-
|
|
749
|
+
|
|
750
|
+
aes = createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
|
751
|
+
|
|
647
752
|
// if an end byte that is not EOF is specified
|
|
648
753
|
// stop auto padding (PKCS7) -- otherwise throws an error for decryption
|
|
649
754
|
if (endByte) {
|
|
650
|
-
aes.setAutoPadding(false)
|
|
755
|
+
aes.setAutoPadding(false)
|
|
651
756
|
}
|
|
652
757
|
}
|
|
653
758
|
try {
|
|
654
|
-
pushBytes(aes.update(data), b => this.push(b))
|
|
655
|
-
callback()
|
|
759
|
+
pushBytes(aes.update(data), b => this.push(b))
|
|
760
|
+
callback()
|
|
656
761
|
}
|
|
657
762
|
catch (error) {
|
|
658
|
-
callback(error)
|
|
763
|
+
callback(error)
|
|
659
764
|
}
|
|
660
765
|
},
|
|
661
766
|
final(callback) {
|
|
662
767
|
try {
|
|
663
|
-
pushBytes(aes.final(), b => this.push(b))
|
|
664
|
-
callback()
|
|
768
|
+
pushBytes(aes.final(), b => this.push(b))
|
|
769
|
+
callback()
|
|
665
770
|
}
|
|
666
771
|
catch (error) {
|
|
667
|
-
callback(error)
|
|
772
|
+
callback(error)
|
|
668
773
|
}
|
|
669
|
-
}
|
|
670
|
-
})
|
|
671
|
-
|
|
672
|
-
}
|
|
673
|
-
|
|
774
|
+
}
|
|
775
|
+
})
|
|
776
|
+
|
|
777
|
+
return fetched.pipe(output, { end: true })
|
|
778
|
+
}
|
|
779
|
+
|
|
674
780
|
function extensionForMediaMessage(message) {
|
|
675
|
-
const getExtension = (mimetype) => mimetype.split('
|
|
676
|
-
const type = Object.keys(message)[0]
|
|
677
|
-
let extension
|
|
781
|
+
const getExtension = (mimetype) => mimetype.split('')[0].split('/')[1]
|
|
782
|
+
const type = Object.keys(message)[0]
|
|
783
|
+
let extension
|
|
678
784
|
if (type === 'locationMessage' ||
|
|
679
785
|
type === 'liveLocationMessage' ||
|
|
680
786
|
type === 'productMessage') {
|
|
681
|
-
extension = '.jpeg'
|
|
787
|
+
extension = '.jpeg'
|
|
682
788
|
}
|
|
683
789
|
else {
|
|
684
|
-
const messageContent = message[type]
|
|
685
|
-
extension = getExtension(messageContent.mimetype)
|
|
790
|
+
const messageContent = message[type]
|
|
791
|
+
extension = getExtension(messageContent.mimetype)
|
|
686
792
|
}
|
|
687
|
-
return extension
|
|
793
|
+
return extension
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const isNodeRuntime = () => {
|
|
797
|
+
return (typeof process !== 'undefined' &&
|
|
798
|
+
process.versions?.node !== null &&
|
|
799
|
+
typeof process.versions.bun === 'undefined' &&
|
|
800
|
+
typeof globalThis.Deno === 'undefined')
|
|
688
801
|
}
|
|
689
|
-
|
|
802
|
+
|
|
803
|
+
const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
|
|
804
|
+
if (redirectCount > 5) {
|
|
805
|
+
throw new Error('Too many redirects')
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
const parsedUrl = new URL(url)
|
|
809
|
+
const httpModule = parsedUrl.protocol === 'https:' ? require('https') : require('http')
|
|
810
|
+
|
|
811
|
+
// Get file size for Content-Length header (required for Node.js streaming)
|
|
812
|
+
const fileStats = await promises.stat(filePath)
|
|
813
|
+
const fileSize = fileStats.size
|
|
814
|
+
|
|
815
|
+
return new Promise((resolve, reject) => {
|
|
816
|
+
const req = httpModule.request({
|
|
817
|
+
hostname: parsedUrl.hostname,
|
|
818
|
+
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
|
819
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
820
|
+
method: 'POST',
|
|
821
|
+
headers: {
|
|
822
|
+
...headers,
|
|
823
|
+
'Content-Length': fileSize
|
|
824
|
+
},
|
|
825
|
+
agent,
|
|
826
|
+
timeout: timeoutMs
|
|
827
|
+
}, res => {
|
|
828
|
+
// Handle redirects (3xx)
|
|
829
|
+
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
830
|
+
res.resume() // Consume response to free resources
|
|
831
|
+
|
|
832
|
+
const newUrl = new URL(res.headers.location, url).toString()
|
|
833
|
+
|
|
834
|
+
resolve(uploadWithNodeHttp({
|
|
835
|
+
url: newUrl,
|
|
836
|
+
filePath,
|
|
837
|
+
headers,
|
|
838
|
+
timeoutMs,
|
|
839
|
+
agent
|
|
840
|
+
}, redirectCount + 1))
|
|
841
|
+
return
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
let body = ''
|
|
845
|
+
|
|
846
|
+
res.on('data', chunk => (body += chunk))
|
|
847
|
+
res.on('end', () => {
|
|
848
|
+
try {
|
|
849
|
+
resolve(JSON.parse(body))
|
|
850
|
+
}
|
|
851
|
+
catch {
|
|
852
|
+
resolve(undefined)
|
|
853
|
+
}
|
|
854
|
+
})
|
|
855
|
+
})
|
|
856
|
+
|
|
857
|
+
req.on('error', reject)
|
|
858
|
+
req.on('timeout', () => {
|
|
859
|
+
req.destroy()
|
|
860
|
+
reject(new Error('Upload timeout'))
|
|
861
|
+
})
|
|
862
|
+
|
|
863
|
+
const stream = createReadStream(filePath)
|
|
864
|
+
|
|
865
|
+
stream.pipe(req)
|
|
866
|
+
stream.on('error', err => {
|
|
867
|
+
req.destroy()
|
|
868
|
+
reject(err)
|
|
869
|
+
})
|
|
870
|
+
})
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
|
|
874
|
+
// Convert Node.js Readable to Web ReadableStream
|
|
875
|
+
const nodeStream = createReadStream(filePath)
|
|
876
|
+
const webStream = Readable.toWeb(nodeStream)
|
|
877
|
+
const response = await fetch(url, {
|
|
878
|
+
dispatcher: agent,
|
|
879
|
+
method: 'POST',
|
|
880
|
+
body: webStream,
|
|
881
|
+
headers,
|
|
882
|
+
duplex: 'half',
|
|
883
|
+
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
884
|
+
})
|
|
885
|
+
|
|
886
|
+
try {
|
|
887
|
+
return (await response.json())
|
|
888
|
+
}
|
|
889
|
+
catch {
|
|
890
|
+
return undefined
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
* Uploads media to WhatsApp servers.
|
|
896
|
+
*
|
|
897
|
+
* ## Why we have two upload implementations:
|
|
898
|
+
*
|
|
899
|
+
* Node.js's native `fetch` (powered by undici) has a known bug where it buffers
|
|
900
|
+
* the entire request body in memory before sending, even when using streams.
|
|
901
|
+
* This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
|
|
902
|
+
* See: https://github.com/nodejs/undici/issues/4058
|
|
903
|
+
*
|
|
904
|
+
* Other runtimes (Bun, Deno, browsers) correctly stream the request body without
|
|
905
|
+
* buffering, so we can use the web-standard Fetch API there.
|
|
906
|
+
*
|
|
907
|
+
* ## Future considerations:
|
|
908
|
+
* Once the undici bug is fixed, we can simplify this to use only the Fetch API
|
|
909
|
+
* across all runtimes. Monitor the GitHub issue for updates.
|
|
910
|
+
*/
|
|
911
|
+
const uploadMedia = async (params, logger) => {
|
|
912
|
+
if (isNodeRuntime()) {
|
|
913
|
+
logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)')
|
|
914
|
+
return uploadWithNodeHttp(params)
|
|
915
|
+
}
|
|
916
|
+
else {
|
|
917
|
+
logger?.debug('Using web-standard Fetch API for upload');
|
|
918
|
+
return uploadWithFetch(params)
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
690
922
|
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
691
|
-
return async (
|
|
692
|
-
var _a, _b;
|
|
693
|
-
const { default: axios } = await import('axios');
|
|
923
|
+
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
|
694
924
|
// send a query JSON to obtain the url & auth token to upload our media
|
|
695
|
-
let uploadInfo = await refreshMediaConn(false)
|
|
696
|
-
let urls
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
const auth = encodeURIComponent(uploadInfo.auth); // the auth token
|
|
725
|
-
const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
|
|
726
|
-
let result;
|
|
925
|
+
let uploadInfo = await refreshMediaConn(false)
|
|
926
|
+
let urls
|
|
927
|
+
|
|
928
|
+
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
|
929
|
+
|
|
930
|
+
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
|
931
|
+
|
|
932
|
+
// Prepare common headers
|
|
933
|
+
const customHeaders = (() => {
|
|
934
|
+
const hdrs = options?.headers;
|
|
935
|
+
if (!hdrs)
|
|
936
|
+
return {};
|
|
937
|
+
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs
|
|
938
|
+
})()
|
|
939
|
+
|
|
940
|
+
const headers = {
|
|
941
|
+
...customHeaders,
|
|
942
|
+
'Content-Type': 'application/octet-stream',
|
|
943
|
+
Origin: DEFAULT_ORIGIN
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
for (const { hostname } of hosts) {
|
|
947
|
+
logger.debug(`uploading to "${hostname}"`)
|
|
948
|
+
|
|
949
|
+
const auth = encodeURIComponent(uploadInfo.auth)
|
|
950
|
+
const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
|
|
951
|
+
|
|
952
|
+
let result
|
|
953
|
+
|
|
727
954
|
try {
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
const body = await axios.post(url, reqBody, {
|
|
737
|
-
...options,
|
|
738
|
-
headers: {
|
|
739
|
-
...options.headers || {},
|
|
740
|
-
'Content-Type': 'application/octet-stream',
|
|
741
|
-
'Origin': Defaults_1.DEFAULT_ORIGIN
|
|
742
|
-
},
|
|
743
|
-
httpsAgent: fetchAgent,
|
|
744
|
-
timeout: timeoutMs,
|
|
745
|
-
responseType: 'json',
|
|
746
|
-
maxBodyLength: Infinity,
|
|
747
|
-
maxContentLength: Infinity,
|
|
748
|
-
});
|
|
749
|
-
result = body.data;
|
|
750
|
-
if ((result === null || result === void 0 ? void 0 : result.url) || (result === null || result === void 0 ? void 0 : result.directPath)) {
|
|
955
|
+
result = await uploadMedia({
|
|
956
|
+
url,
|
|
957
|
+
filePath,
|
|
958
|
+
headers,
|
|
959
|
+
timeoutMs,
|
|
960
|
+
agent: fetchAgent
|
|
961
|
+
}, logger);
|
|
962
|
+
if (result?.url || result?.direct_path) {
|
|
751
963
|
urls = {
|
|
752
964
|
mediaUrl: result.url,
|
|
753
965
|
directPath: result.direct_path,
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
966
|
+
meta_hmac: result.meta_hmac,
|
|
967
|
+
fbid: result.fbid,
|
|
968
|
+
ts: result.ts
|
|
969
|
+
}
|
|
970
|
+
break
|
|
757
971
|
}
|
|
758
972
|
else {
|
|
759
|
-
uploadInfo = await refreshMediaConn(true)
|
|
760
|
-
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
|
973
|
+
uploadInfo = await refreshMediaConn(true)
|
|
974
|
+
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
|
761
975
|
}
|
|
762
976
|
}
|
|
763
977
|
catch (error) {
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
}
|
|
767
|
-
const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
|
|
768
|
-
logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
|
|
978
|
+
const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
|
|
979
|
+
logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`)
|
|
769
980
|
}
|
|
770
981
|
}
|
|
982
|
+
|
|
771
983
|
if (!urls) {
|
|
772
|
-
throw new
|
|
984
|
+
throw new Boom('Media upload failed on all hosts', { statusCode: 500 })
|
|
773
985
|
}
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
}
|
|
777
|
-
|
|
986
|
+
|
|
987
|
+
return urls
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
778
991
|
const getMediaRetryKey = (mediaKey) => {
|
|
779
|
-
return
|
|
780
|
-
}
|
|
992
|
+
return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
|
|
993
|
+
}
|
|
781
994
|
/**
|
|
782
995
|
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
|
783
996
|
*/
|
|
784
|
-
const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
785
|
-
const recp = { stanzaId: key.id }
|
|
786
|
-
const recpBuffer =
|
|
787
|
-
const iv =
|
|
788
|
-
const retryKey = getMediaRetryKey(mediaKey)
|
|
789
|
-
const ciphertext =
|
|
997
|
+
const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
|
|
998
|
+
const recp = { stanzaId: key.id }
|
|
999
|
+
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
|
|
1000
|
+
const iv = randomBytes(12)
|
|
1001
|
+
const retryKey = await getMediaRetryKey(mediaKey)
|
|
1002
|
+
const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id))
|
|
790
1003
|
const req = {
|
|
791
1004
|
tag: 'receipt',
|
|
792
1005
|
attrs: {
|
|
793
1006
|
id: key.id,
|
|
794
|
-
to:
|
|
1007
|
+
to: jidNormalizedUser(meId),
|
|
795
1008
|
type: 'server-error'
|
|
796
1009
|
},
|
|
797
1010
|
content: [
|
|
@@ -810,18 +1023,17 @@ const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
|
810
1023
|
tag: 'rmr',
|
|
811
1024
|
attrs: {
|
|
812
1025
|
jid: key.remoteJid,
|
|
813
|
-
|
|
814
|
-
// @ts-ignore
|
|
1026
|
+
from_me: (!!key.fromMe).toString(),
|
|
815
1027
|
participant: key.participant || undefined
|
|
816
1028
|
}
|
|
817
1029
|
}
|
|
818
1030
|
]
|
|
819
|
-
}
|
|
820
|
-
return req
|
|
821
|
-
}
|
|
822
|
-
|
|
1031
|
+
}
|
|
1032
|
+
return req
|
|
1033
|
+
}
|
|
1034
|
+
|
|
823
1035
|
const decodeMediaRetryNode = (node) => {
|
|
824
|
-
const rmrNode =
|
|
1036
|
+
const rmrNode = getBinaryNodeChild(node, 'rmr')
|
|
825
1037
|
const event = {
|
|
826
1038
|
key: {
|
|
827
1039
|
id: node.attrs.id,
|
|
@@ -829,41 +1041,69 @@ const decodeMediaRetryNode = (node) => {
|
|
|
829
1041
|
fromMe: rmrNode.attrs.from_me === 'true',
|
|
830
1042
|
participant: rmrNode.attrs.participant
|
|
831
1043
|
}
|
|
832
|
-
}
|
|
833
|
-
const errorNode =
|
|
1044
|
+
}
|
|
1045
|
+
const errorNode = getBinaryNodeChild(node, 'error')
|
|
834
1046
|
if (errorNode) {
|
|
835
|
-
const errorCode = +errorNode.attrs.code
|
|
836
|
-
event.error = new
|
|
1047
|
+
const errorCode = +errorNode.attrs.code
|
|
1048
|
+
event.error = new Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(errorCode) })
|
|
837
1049
|
}
|
|
838
1050
|
else {
|
|
839
|
-
const encryptedInfoNode =
|
|
840
|
-
const ciphertext =
|
|
841
|
-
const iv =
|
|
1051
|
+
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
|
|
1052
|
+
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
|
|
1053
|
+
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
|
|
842
1054
|
if (ciphertext && iv) {
|
|
843
|
-
event.media = { ciphertext, iv }
|
|
1055
|
+
event.media = { ciphertext, iv }
|
|
844
1056
|
}
|
|
845
1057
|
else {
|
|
846
|
-
event.error = new
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
return event
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
853
|
-
const retryKey = getMediaRetryKey(mediaKey)
|
|
854
|
-
const plaintext =
|
|
855
|
-
return
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code]
|
|
859
|
-
|
|
1058
|
+
event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
return event
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
1065
|
+
const retryKey = await getMediaRetryKey(mediaKey)
|
|
1066
|
+
const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
|
|
1067
|
+
return proto.MediaRetryNotification.decode(plaintext)
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code]
|
|
1071
|
+
|
|
860
1072
|
const MEDIA_RETRY_STATUS_MAP = {
|
|
861
|
-
[
|
|
862
|
-
[
|
|
863
|
-
[
|
|
864
|
-
[
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
1073
|
+
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
1074
|
+
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
1075
|
+
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
1076
|
+
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
module.exports = {
|
|
1080
|
+
hkdfInfoKey,
|
|
1081
|
+
getMediaKeys,
|
|
1082
|
+
extractVideoThumb,
|
|
1083
|
+
extractImageThumb,
|
|
1084
|
+
encodeBase64EncodedStringForUpload,
|
|
1085
|
+
generateProfilePicture,
|
|
1086
|
+
mediaMessageSHA256B64,
|
|
1087
|
+
getAudioDuration,
|
|
1088
|
+
getAudioWaveform,
|
|
1089
|
+
toReadable,
|
|
1090
|
+
toBuffer,
|
|
1091
|
+
getStream,
|
|
1092
|
+
generateThumbnail,
|
|
1093
|
+
getHttpStream,
|
|
1094
|
+
//prepareStream,
|
|
1095
|
+
encryptedStream,
|
|
1096
|
+
getUrlFromDirectPath,
|
|
1097
|
+
downloadContentFromMessage,
|
|
1098
|
+
downloadEncryptedContent,
|
|
1099
|
+
extensionForMediaMessage,
|
|
1100
|
+
uploadWithNodeHttp,
|
|
1101
|
+
getRawMediaUploadData,
|
|
1102
|
+
getWAUploadToServer,
|
|
1103
|
+
getMediaRetryKey,
|
|
1104
|
+
encryptMediaRetryRequest,
|
|
1105
|
+
decodeMediaRetryNode,
|
|
1106
|
+
decryptMediaRetryData,
|
|
1107
|
+
getStatusCodeForMediaRetry,
|
|
1108
|
+
MEDIA_RETRY_STATUS_MAP
|
|
869
1109
|
}
|