@vanzxy/baileys 1.4.1 → 1.4.2
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.
Potentially problematic release.
This version of @vanzxy/baileys might be problematic. Click here for more details.
- package/cjs/WAProto/index.js +106053 -0
- package/cjs/lib/Defaults/index.js +168 -0
- package/cjs/lib/Signal/Group/ciphertext-message.js +16 -0
- package/cjs/lib/Signal/Group/group-session-builder.js +67 -0
- package/cjs/lib/Signal/Group/group_cipher.js +86 -0
- package/cjs/lib/Signal/Group/index.js +58 -0
- package/cjs/lib/Signal/Group/keyhelper.js +56 -0
- package/cjs/lib/Signal/Group/sender-chain-key.js +30 -0
- package/cjs/lib/Signal/Group/sender-key-distribution-message.js +67 -0
- package/cjs/lib/Signal/Group/sender-key-message.js +70 -0
- package/cjs/lib/Signal/Group/sender-key-name.js +52 -0
- package/cjs/lib/Signal/Group/sender-key-record.js +45 -0
- package/cjs/lib/Signal/Group/sender-key-state.js +88 -0
- package/cjs/lib/Signal/Group/sender-message-key.js +30 -0
- package/cjs/lib/Signal/libsignal.js +467 -0
- package/cjs/lib/Signal/lid-mapping.js +281 -0
- package/cjs/lib/Socket/Client/index.js +19 -0
- package/cjs/lib/Socket/Client/types.js +15 -0
- package/cjs/lib/Socket/Client/websocket.js +61 -0
- package/cjs/lib/Socket/business.js +384 -0
- package/cjs/lib/Socket/chats.js +1257 -0
- package/cjs/lib/Socket/communities.js +442 -0
- package/cjs/lib/Socket/dugong.js +753 -0
- package/cjs/lib/Socket/groups.js +360 -0
- package/cjs/lib/Socket/index.js +19 -0
- package/cjs/lib/Socket/messages-recv.js +1790 -0
- package/cjs/lib/Socket/messages-send.js +1390 -0
- package/cjs/lib/Socket/mex.js +46 -0
- package/cjs/lib/Socket/newsletter.js +340 -0
- package/cjs/lib/Socket/socket.js +1007 -0
- package/cjs/lib/Store/index.js +20 -0
- package/cjs/lib/Store/make-in-memory-store.js +438 -0
- package/cjs/lib/Store/make-ordered-dictionary.js +82 -0
- package/cjs/lib/Store/object-repository.js +28 -0
- package/cjs/lib/Types/Auth.js +3 -0
- package/cjs/lib/Types/Bussines.js +3 -0
- package/cjs/lib/Types/Call.js +3 -0
- package/cjs/lib/Types/Chat.js +11 -0
- package/cjs/lib/Types/Contact.js +3 -0
- package/cjs/lib/Types/Events.js +4 -0
- package/cjs/lib/Types/GroupMetadata.js +3 -0
- package/cjs/lib/Types/Label.js +26 -0
- package/cjs/lib/Types/LabelAssociation.js +8 -0
- package/cjs/lib/Types/Message.js +19 -0
- package/cjs/lib/Types/Mex.js +40 -0
- package/cjs/lib/Types/Product.js +3 -0
- package/cjs/lib/Types/RichType.js +24 -0
- package/cjs/lib/Types/Signal.js +4 -0
- package/cjs/lib/Types/Socket.js +4 -0
- package/cjs/lib/Types/State.js +54 -0
- package/cjs/lib/Types/USync.js +4 -0
- package/cjs/lib/Types/index.js +42 -0
- package/cjs/lib/Utils/MessageBuilder.js +2164 -0
- package/cjs/lib/Utils/auth-utils.js +312 -0
- package/cjs/lib/Utils/browser-utils.js +32 -0
- package/cjs/lib/Utils/business.js +245 -0
- package/cjs/lib/Utils/chat-utils.js +937 -0
- package/cjs/lib/Utils/companion-reg-client-utils.js +45 -0
- package/cjs/lib/Utils/crypto.js +196 -0
- package/cjs/lib/Utils/decode-wa-message.js +324 -0
- package/cjs/lib/Utils/event-buffer.js +643 -0
- package/cjs/lib/Utils/generics.js +429 -0
- package/cjs/lib/Utils/history.js +151 -0
- package/cjs/lib/Utils/identity-change-handler.js +56 -0
- package/cjs/lib/Utils/index.js +42 -0
- package/cjs/lib/Utils/link-preview.js +122 -0
- package/cjs/lib/Utils/logger.js +8 -0
- package/cjs/lib/Utils/lt-hash.js +62 -0
- package/cjs/lib/Utils/make-mutex.js +38 -0
- package/cjs/lib/Utils/message-retry-manager.js +267 -0
- package/cjs/lib/Utils/messages-media.js +933 -0
- package/cjs/lib/Utils/messages.js +2175 -0
- package/cjs/lib/Utils/noise-handler.js +205 -0
- package/cjs/lib/Utils/offline-node-processor.js +43 -0
- package/cjs/lib/Utils/pre-key-manager.js +113 -0
- package/cjs/lib/Utils/process-message.js +772 -0
- package/cjs/lib/Utils/reporting-utils.js +263 -0
- package/cjs/lib/Utils/rich-message-utils.js +439 -0
- package/cjs/lib/Utils/signal.js +214 -0
- package/cjs/lib/Utils/stanza-ack.js +41 -0
- package/cjs/lib/Utils/sync-action-utils.js +54 -0
- package/cjs/lib/Utils/tc-token-utils.js +174 -0
- package/cjs/lib/Utils/use-multi-file-auth-state.js +125 -0
- package/cjs/lib/Utils/use-single-file-auth-state.js +121 -0
- package/cjs/lib/Utils/use-sqlite-auth-state.js +182 -0
- package/cjs/lib/Utils/validate-connection.js +210 -0
- package/cjs/lib/WABinary/constants.js +1470 -0
- package/cjs/lib/WABinary/decode.js +301 -0
- package/cjs/lib/WABinary/encode.js +257 -0
- package/cjs/lib/WABinary/generic-utils.js +274 -0
- package/cjs/lib/WABinary/index.js +22 -0
- package/cjs/lib/WABinary/jid-utils.js +114 -0
- package/cjs/lib/WABinary/types.js +37 -0
- package/cjs/lib/WAM/BinaryInfo.js +14 -0
- package/cjs/lib/WAM/constants.js +22856 -0
- package/cjs/lib/WAM/encode.js +154 -0
- package/cjs/lib/WAM/index.js +20 -0
- package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
- package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +67 -0
- package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
- package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
- package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +55 -0
- package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +33 -0
- package/cjs/lib/WAUSync/Protocols/index.js +24 -0
- package/cjs/lib/WAUSync/USyncQuery.js +126 -0
- package/cjs/lib/WAUSync/USyncUser.js +35 -0
- package/cjs/lib/WAUSync/index.js +20 -0
- package/cjs/lib/index.js +34 -0
- package/cjs/package.json +1 -0
- package/package.json +16 -5
|
@@ -0,0 +1,933 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.uploadWithNodeHttp = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.DEF_MEDIA_HOST = exports.encryptedStream = exports.getHttpStream = exports.getStream = exports.toBuffer = exports.toReadable = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.extractVideoThumb = exports.getRawMediaUploadData = exports.hkdfInfoKey = exports.getImageProcessingLibrary = void 0;
|
|
37
|
+
exports.getMediaKeys = getMediaKeys;
|
|
38
|
+
exports.getAudioDuration = getAudioDuration;
|
|
39
|
+
exports.getAudioWaveform = getAudioWaveform;
|
|
40
|
+
exports.generateThumbnail = generateThumbnail;
|
|
41
|
+
exports.extensionForMediaMessage = extensionForMediaMessage;
|
|
42
|
+
const boom_1 = require("@hapi/boom");
|
|
43
|
+
const child_process_1 = require("child_process");
|
|
44
|
+
const Crypto = __importStar(require("crypto"));
|
|
45
|
+
const events_1 = require("events");
|
|
46
|
+
const fs_1 = require("fs");
|
|
47
|
+
const os_1 = require("os");
|
|
48
|
+
const path_1 = require("path");
|
|
49
|
+
const stream_1 = require("stream");
|
|
50
|
+
const url_1 = require("url");
|
|
51
|
+
const index_js_1 = require("../../WAProto/index.js");
|
|
52
|
+
const index_js_2 = require("../Defaults/index.js");
|
|
53
|
+
const index_js_3 = require("../WABinary/index.js");
|
|
54
|
+
const crypto_js_1 = require("./crypto.js");
|
|
55
|
+
const generics_js_1 = require("./generics.js");
|
|
56
|
+
const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
|
|
57
|
+
let imageProcessingLibrary;
|
|
58
|
+
let _imageLibInitPromise = null; // Vanz@Fix (bug 22): deduplicate parallel init calls
|
|
59
|
+
const getImageProcessingLibrary = async () => {
|
|
60
|
+
if (imageProcessingLibrary) {
|
|
61
|
+
return imageProcessingLibrary;
|
|
62
|
+
}
|
|
63
|
+
if (!_imageLibInitPromise) {
|
|
64
|
+
_imageLibInitPromise = (async () => {
|
|
65
|
+
//@ts-ignore
|
|
66
|
+
const [sharp, image, jimp] = await Promise.all([
|
|
67
|
+
Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }),
|
|
68
|
+
Promise.resolve().then(() => __importStar(require('@napi-rs/image'))).catch(() => { }),
|
|
69
|
+
Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { })
|
|
70
|
+
]);
|
|
71
|
+
if (sharp) {
|
|
72
|
+
imageProcessingLibrary = { sharp };
|
|
73
|
+
}
|
|
74
|
+
else if (image) {
|
|
75
|
+
imageProcessingLibrary = { image };
|
|
76
|
+
}
|
|
77
|
+
else if (jimp) {
|
|
78
|
+
imageProcessingLibrary = { jimp };
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
throw new boom_1.Boom('No image processing library available');
|
|
82
|
+
}
|
|
83
|
+
return imageProcessingLibrary;
|
|
84
|
+
})();
|
|
85
|
+
}
|
|
86
|
+
return _imageLibInitPromise;
|
|
87
|
+
};
|
|
88
|
+
exports.getImageProcessingLibrary = getImageProcessingLibrary;
|
|
89
|
+
const hkdfInfoKey = (type) => {
|
|
90
|
+
const hkdfInfo = index_js_2.MEDIA_HKDF_KEY_MAPPING[type];
|
|
91
|
+
return `WhatsApp ${hkdfInfo} Keys`;
|
|
92
|
+
};
|
|
93
|
+
exports.hkdfInfoKey = hkdfInfoKey;
|
|
94
|
+
const getRawMediaUploadData = async (media, mediaType, logger) => {
|
|
95
|
+
const { stream } = await (0, exports.getStream)(media);
|
|
96
|
+
logger?.debug('got stream for raw upload');
|
|
97
|
+
const hasher = Crypto.createHash('sha256');
|
|
98
|
+
const filePath = (0, path_1.join)((0, os_1.tmpdir)(), mediaType + (0, generics_js_1.generateMessageIDV2)());
|
|
99
|
+
const fileWriteStream = (0, fs_1.createWriteStream)(filePath);
|
|
100
|
+
let fileLength = 0;
|
|
101
|
+
try {
|
|
102
|
+
for await (const data of stream) {
|
|
103
|
+
fileLength += data.length;
|
|
104
|
+
hasher.update(data);
|
|
105
|
+
if (!fileWriteStream.write(data)) {
|
|
106
|
+
await (0, events_1.once)(fileWriteStream, 'drain');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
fileWriteStream.end();
|
|
110
|
+
await (0, events_1.once)(fileWriteStream, 'finish');
|
|
111
|
+
stream.destroy();
|
|
112
|
+
const fileSha256 = hasher.digest();
|
|
113
|
+
logger?.debug('hashed data for raw upload');
|
|
114
|
+
return {
|
|
115
|
+
filePath: filePath,
|
|
116
|
+
fileSha256,
|
|
117
|
+
fileLength
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
fileWriteStream.destroy();
|
|
122
|
+
stream.destroy();
|
|
123
|
+
try {
|
|
124
|
+
await fs_1.promises.unlink(filePath);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
//
|
|
128
|
+
}
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
exports.getRawMediaUploadData = getRawMediaUploadData;
|
|
133
|
+
/** generates all the keys required to encrypt/decrypt & sign a media message */
|
|
134
|
+
async function getMediaKeys(buffer, mediaType) {
|
|
135
|
+
if (!buffer) {
|
|
136
|
+
throw new boom_1.Boom('Cannot derive from empty media key');
|
|
137
|
+
}
|
|
138
|
+
if (typeof buffer === 'string') {
|
|
139
|
+
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
|
|
140
|
+
}
|
|
141
|
+
// expand using HKDF to 112 bytes, also pass in the relevant app info
|
|
142
|
+
const expandedMediaKey = (0, crypto_js_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
|
|
143
|
+
return {
|
|
144
|
+
iv: expandedMediaKey.slice(0, 16),
|
|
145
|
+
cipherKey: expandedMediaKey.slice(16, 48),
|
|
146
|
+
macKey: expandedMediaKey.slice(48, 80)
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/** Extracts video thumb using FFMPEG */
|
|
150
|
+
const extractVideoThumb = async (path, time, size) => {
|
|
151
|
+
const ffmpeg = (0, child_process_1.spawn)('ffmpeg', [
|
|
152
|
+
'-loglevel', 'error',
|
|
153
|
+
'-ss', String(time),
|
|
154
|
+
'-i', path,
|
|
155
|
+
'-an', '-sn', '-dn',
|
|
156
|
+
'-map_metadata', '-1',
|
|
157
|
+
'-vf', `scale=${size.width}:-1`,
|
|
158
|
+
'-frames:v', '1',
|
|
159
|
+
'-c:v', 'mjpeg',
|
|
160
|
+
'-f', 'image2pipe',
|
|
161
|
+
'pipe:1'
|
|
162
|
+
], {
|
|
163
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
164
|
+
});
|
|
165
|
+
let buffer = Buffer.alloc(0);
|
|
166
|
+
const stderrChunks = [];
|
|
167
|
+
ffmpeg.stdout.on('data', (chunk) => {
|
|
168
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
169
|
+
});
|
|
170
|
+
ffmpeg.stderr.on('data', (chunk) => stderrChunks.push(chunk));
|
|
171
|
+
const [code] = await (0, events_1.once)(ffmpeg, 'close');
|
|
172
|
+
if (code !== 0) {
|
|
173
|
+
throw new boom_1.Boom(`FFmpeg failed (code ${code}):\n` +
|
|
174
|
+
Buffer.concat(stderrChunks).toString('utf8'));
|
|
175
|
+
}
|
|
176
|
+
return buffer;
|
|
177
|
+
};
|
|
178
|
+
exports.extractVideoThumb = extractVideoThumb;
|
|
179
|
+
const extractImageThumb = async (bufferOrFilePath, width = 32) => {
|
|
180
|
+
// TODO: Move entirely to sharp, removing jimp as it supports readable streams
|
|
181
|
+
// This will have positive speed and performance impacts as well as minimizing RAM usage.
|
|
182
|
+
if (bufferOrFilePath instanceof stream_1.Readable) {
|
|
183
|
+
bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
|
|
184
|
+
}
|
|
185
|
+
const lib = await (0, exports.getImageProcessingLibrary)();
|
|
186
|
+
if ('sharp' in lib && lib.sharp?.default) {
|
|
187
|
+
const img = lib.sharp.default(bufferOrFilePath);
|
|
188
|
+
const dimensions = await img.metadata();
|
|
189
|
+
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
|
|
190
|
+
return {
|
|
191
|
+
buffer,
|
|
192
|
+
original: {
|
|
193
|
+
width: dimensions.width,
|
|
194
|
+
height: dimensions.height
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
else if ('image' in lib && lib.image?.Transformer) {
|
|
199
|
+
if (!Buffer.isBuffer(bufferOrFilePath)) {
|
|
200
|
+
bufferOrFilePath = await fs_1.promises.readFile(bufferOrFilePath);
|
|
201
|
+
}
|
|
202
|
+
const img = new lib.image.Transformer(bufferOrFilePath);
|
|
203
|
+
const dimensions = await img.metadata();
|
|
204
|
+
const buffer = await img.resize(width, undefined, 0).jpeg(50);
|
|
205
|
+
return {
|
|
206
|
+
buffer,
|
|
207
|
+
original: {
|
|
208
|
+
width: dimensions.width,
|
|
209
|
+
height: dimensions.height
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
else if ('jimp' in lib && lib.jimp?.Jimp) {
|
|
214
|
+
const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
|
|
215
|
+
const dimensions = {
|
|
216
|
+
width: jimp.width,
|
|
217
|
+
height: jimp.height
|
|
218
|
+
};
|
|
219
|
+
const buffer = await jimp
|
|
220
|
+
.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
|
|
221
|
+
.getBuffer('image/jpeg', { quality: 50 });
|
|
222
|
+
return {
|
|
223
|
+
buffer,
|
|
224
|
+
original: dimensions
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
throw new boom_1.Boom('No image processing library available');
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
exports.extractImageThumb = extractImageThumb;
|
|
232
|
+
const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
|
|
233
|
+
exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
|
|
234
|
+
const generateProfilePicture = async (mediaUpload, dimensions) => {
|
|
235
|
+
let buffer;
|
|
236
|
+
const { width: w = 720, height: h = 720 } = dimensions || {};
|
|
237
|
+
if (Buffer.isBuffer(mediaUpload)) {
|
|
238
|
+
buffer = mediaUpload;
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
// Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
|
|
242
|
+
const { stream } = await (0, exports.getStream)(mediaUpload);
|
|
243
|
+
// Convert the resulting stream to a buffer
|
|
244
|
+
buffer = await (0, exports.toBuffer)(stream);
|
|
245
|
+
}
|
|
246
|
+
const lib = await (0, exports.getImageProcessingLibrary)();
|
|
247
|
+
let img;
|
|
248
|
+
if ('sharp' in lib && lib.sharp?.default) {
|
|
249
|
+
img = lib.sharp
|
|
250
|
+
.default(buffer)
|
|
251
|
+
.resize(w, h)
|
|
252
|
+
.jpeg({
|
|
253
|
+
quality: 80
|
|
254
|
+
})
|
|
255
|
+
.toBuffer();
|
|
256
|
+
}
|
|
257
|
+
else if ('image' in lib && lib.image?.Transformer) {
|
|
258
|
+
img = new lib.image
|
|
259
|
+
.Transformer(buffer)
|
|
260
|
+
.resize(w, h, 0)
|
|
261
|
+
.jpeg(80);
|
|
262
|
+
}
|
|
263
|
+
else if ('jimp' in lib && lib.jimp?.Jimp) {
|
|
264
|
+
const jimp = await lib.jimp.Jimp.read(buffer);
|
|
265
|
+
const min = Math.min(jimp.width, jimp.height);
|
|
266
|
+
const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
|
|
267
|
+
img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 80 });
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
throw new boom_1.Boom('No image processing library available');
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
img: await img
|
|
274
|
+
};
|
|
275
|
+
};
|
|
276
|
+
exports.generateProfilePicture = generateProfilePicture;
|
|
277
|
+
/** gets the SHA256 of the given media message */
|
|
278
|
+
const mediaMessageSHA256B64 = (message) => {
|
|
279
|
+
const media = Object.values(message)[0];
|
|
280
|
+
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
|
|
281
|
+
};
|
|
282
|
+
exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
|
|
283
|
+
async function getAudioDuration(buffer) {
|
|
284
|
+
const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
|
|
285
|
+
let metadata;
|
|
286
|
+
const options = {
|
|
287
|
+
duration: true
|
|
288
|
+
};
|
|
289
|
+
if (Buffer.isBuffer(buffer)) {
|
|
290
|
+
metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
|
|
291
|
+
}
|
|
292
|
+
else if (typeof buffer === 'string') {
|
|
293
|
+
metadata = await musicMetadata.parseFile(buffer, options);
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
metadata = await musicMetadata.parseStream(buffer, undefined, options);
|
|
297
|
+
}
|
|
298
|
+
return metadata.format.duration;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
|
|
302
|
+
*/
|
|
303
|
+
async function getAudioWaveform(buffer, logger) {
|
|
304
|
+
try {
|
|
305
|
+
// @ts-ignore
|
|
306
|
+
const { default: decoder } = await Promise.resolve().then(() => __importStar(require('audio-decode')));
|
|
307
|
+
let audioData;
|
|
308
|
+
if (Buffer.isBuffer(buffer)) {
|
|
309
|
+
audioData = buffer;
|
|
310
|
+
}
|
|
311
|
+
else if (typeof buffer === 'string') {
|
|
312
|
+
const rStream = (0, fs_1.createReadStream)(buffer);
|
|
313
|
+
audioData = await (0, exports.toBuffer)(rStream);
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
audioData = await (0, exports.toBuffer)(buffer);
|
|
317
|
+
}
|
|
318
|
+
const audioBuffer = await decoder(audioData);
|
|
319
|
+
const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
|
|
320
|
+
const samples = 64; // Number of samples we want to have in our final data set
|
|
321
|
+
const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
|
|
322
|
+
const filteredData = [];
|
|
323
|
+
for (let i = 0; i < samples; i++) {
|
|
324
|
+
const blockStart = blockSize * i; // the location of the first sample in the block
|
|
325
|
+
let sum = 0;
|
|
326
|
+
for (let j = 0; j < blockSize; j++) {
|
|
327
|
+
sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
|
|
328
|
+
}
|
|
329
|
+
filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
|
|
330
|
+
}
|
|
331
|
+
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
|
332
|
+
const multiplier = Math.pow(Math.max(...filteredData), -1);
|
|
333
|
+
const normalizedData = filteredData.map(n => n * multiplier);
|
|
334
|
+
// Generate waveform like WhatsApp
|
|
335
|
+
const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
|
|
336
|
+
return waveform;
|
|
337
|
+
}
|
|
338
|
+
catch (e) {
|
|
339
|
+
logger?.debug('Failed to generate waveform: ' + e);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const toReadable = (buffer) => {
|
|
343
|
+
const readable = new stream_1.Readable({ read: () => { } });
|
|
344
|
+
readable.push(buffer);
|
|
345
|
+
readable.push(null);
|
|
346
|
+
return readable;
|
|
347
|
+
};
|
|
348
|
+
exports.toReadable = toReadable;
|
|
349
|
+
const toBuffer = async (stream) => {
|
|
350
|
+
const chunks = [];
|
|
351
|
+
for await (const chunk of stream) {
|
|
352
|
+
chunks.push(chunk);
|
|
353
|
+
}
|
|
354
|
+
stream.destroy();
|
|
355
|
+
return Buffer.concat(chunks);
|
|
356
|
+
};
|
|
357
|
+
exports.toBuffer = toBuffer;
|
|
358
|
+
const getStream = async (item, opts) => {
|
|
359
|
+
if (Buffer.isBuffer(item)) {
|
|
360
|
+
return { stream: (0, exports.toReadable)(item), type: 'buffer' };
|
|
361
|
+
}
|
|
362
|
+
if ('stream' in item) {
|
|
363
|
+
return { stream: item.stream, type: 'readable' };
|
|
364
|
+
}
|
|
365
|
+
const urlStr = item.url.toString();
|
|
366
|
+
if (urlStr.startsWith('data:')) {
|
|
367
|
+
const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
|
|
368
|
+
return { stream: (0, exports.toReadable)(buffer), type: 'buffer' };
|
|
369
|
+
}
|
|
370
|
+
if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
|
|
371
|
+
return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
|
|
372
|
+
}
|
|
373
|
+
return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
|
|
374
|
+
};
|
|
375
|
+
exports.getStream = getStream;
|
|
376
|
+
/** generates a thumbnail for a given media, if required */
|
|
377
|
+
async function generateThumbnail(file, mediaType, options) {
|
|
378
|
+
let thumbnail;
|
|
379
|
+
let originalImageDimensions;
|
|
380
|
+
if (mediaType === 'image') {
|
|
381
|
+
const { buffer, original } = await (0, exports.extractImageThumb)(file);
|
|
382
|
+
thumbnail = buffer.toString('base64');
|
|
383
|
+
if (original.width && original.height) {
|
|
384
|
+
originalImageDimensions = {
|
|
385
|
+
width: original.width,
|
|
386
|
+
height: original.height
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
else if (mediaType === 'video') {
|
|
391
|
+
try {
|
|
392
|
+
const buff = await (0, exports.extractVideoThumb)(file, '00:00:00', { width: 32, height: 32 });
|
|
393
|
+
thumbnail = buff.toString('base64');
|
|
394
|
+
}
|
|
395
|
+
catch (err) {
|
|
396
|
+
options.logger?.debug('could not generate video thumb: ' + err);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return {
|
|
400
|
+
thumbnail,
|
|
401
|
+
originalImageDimensions
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
const getHttpStream = async (url, options = {}) => {
|
|
405
|
+
const response = await fetch(url.toString(), {
|
|
406
|
+
dispatcher: options.dispatcher,
|
|
407
|
+
method: 'GET',
|
|
408
|
+
headers: options.headers,
|
|
409
|
+
// Vanz@Fix (bug 26/39): no timeout = potential infinite hang on slow CDN
|
|
410
|
+
signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : AbortSignal.timeout(60000)
|
|
411
|
+
});
|
|
412
|
+
if (!response.ok) {
|
|
413
|
+
throw new boom_1.Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
|
|
414
|
+
}
|
|
415
|
+
// @ts-ignore Node18+ Readable.fromWeb exists
|
|
416
|
+
return response.body instanceof stream_1.Readable ? response.body : stream_1.Readable.fromWeb(response.body);
|
|
417
|
+
};
|
|
418
|
+
exports.getHttpStream = getHttpStream;
|
|
419
|
+
const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
420
|
+
const { stream, type } = await (0, exports.getStream)(media, opts);
|
|
421
|
+
logger?.debug('fetched media stream');
|
|
422
|
+
const mediaKey = Crypto.randomBytes(32);
|
|
423
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
|
|
424
|
+
const encFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_js_1.generateMessageIDV2)() + '-enc');
|
|
425
|
+
const encFileWriteStream = (0, fs_1.createWriteStream)(encFilePath);
|
|
426
|
+
let originalFileStream;
|
|
427
|
+
let originalFilePath;
|
|
428
|
+
if (saveOriginalFileIfRequired) {
|
|
429
|
+
originalFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_js_1.generateMessageIDV2)() + '-original');
|
|
430
|
+
originalFileStream = (0, fs_1.createWriteStream)(originalFilePath);
|
|
431
|
+
}
|
|
432
|
+
let fileLength = 0;
|
|
433
|
+
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
|
|
434
|
+
const hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
|
435
|
+
const sha256Plain = Crypto.createHash('sha256');
|
|
436
|
+
const sha256Enc = Crypto.createHash('sha256');
|
|
437
|
+
const onChunk = async (buff) => {
|
|
438
|
+
sha256Enc.update(buff);
|
|
439
|
+
hmac.update(buff);
|
|
440
|
+
// Handle backpressure: if write returns false, wait for drain
|
|
441
|
+
if (!encFileWriteStream.write(buff)) {
|
|
442
|
+
await (0, events_1.once)(encFileWriteStream, 'drain');
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
try {
|
|
446
|
+
for await (const data of stream) {
|
|
447
|
+
fileLength += data.length;
|
|
448
|
+
if (type === 'remote' &&
|
|
449
|
+
opts?.maxContentLength &&
|
|
450
|
+
fileLength + data.length > opts.maxContentLength) {
|
|
451
|
+
throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
|
|
452
|
+
data: { media, type }
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
if (originalFileStream) {
|
|
456
|
+
if (!originalFileStream.write(data)) {
|
|
457
|
+
await (0, events_1.once)(originalFileStream, 'drain');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
sha256Plain.update(data);
|
|
461
|
+
await onChunk(aes.update(data));
|
|
462
|
+
}
|
|
463
|
+
await onChunk(aes.final());
|
|
464
|
+
const mac = hmac.digest().slice(0, 10);
|
|
465
|
+
sha256Enc.update(mac);
|
|
466
|
+
const fileSha256 = sha256Plain.digest();
|
|
467
|
+
const fileEncSha256 = sha256Enc.digest();
|
|
468
|
+
encFileWriteStream.write(mac);
|
|
469
|
+
const encFinishPromise = (0, events_1.once)(encFileWriteStream, 'finish');
|
|
470
|
+
const originalFinishPromise = originalFileStream ? (0, events_1.once)(originalFileStream, 'finish') : Promise.resolve();
|
|
471
|
+
encFileWriteStream.end();
|
|
472
|
+
originalFileStream?.end?.();
|
|
473
|
+
stream.destroy();
|
|
474
|
+
// Wait for write streams to fully flush to disk
|
|
475
|
+
// This helps reduce memory pressure by allowing OS to release buffers
|
|
476
|
+
await encFinishPromise;
|
|
477
|
+
await originalFinishPromise;
|
|
478
|
+
logger?.debug('encrypted data successfully');
|
|
479
|
+
return {
|
|
480
|
+
mediaKey,
|
|
481
|
+
originalFilePath,
|
|
482
|
+
encFilePath,
|
|
483
|
+
mac,
|
|
484
|
+
fileEncSha256,
|
|
485
|
+
fileSha256,
|
|
486
|
+
fileLength
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
catch (error) {
|
|
490
|
+
// destroy all streams with error
|
|
491
|
+
encFileWriteStream.destroy();
|
|
492
|
+
originalFileStream?.destroy?.();
|
|
493
|
+
aes.destroy();
|
|
494
|
+
hmac.destroy();
|
|
495
|
+
sha256Plain.destroy();
|
|
496
|
+
sha256Enc.destroy();
|
|
497
|
+
stream.destroy();
|
|
498
|
+
try {
|
|
499
|
+
await fs_1.promises.unlink(encFilePath);
|
|
500
|
+
if (originalFilePath) {
|
|
501
|
+
await fs_1.promises.unlink(originalFilePath);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
catch (err) {
|
|
505
|
+
logger?.error({ err }, 'failed deleting tmp files');
|
|
506
|
+
}
|
|
507
|
+
throw error;
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
exports.encryptedStream = encryptedStream;
|
|
511
|
+
exports.DEF_MEDIA_HOST = 'mmg.whatsapp.net';
|
|
512
|
+
const AES_CHUNK_SIZE = 16;
|
|
513
|
+
const toSmallestChunkSize = (num) => {
|
|
514
|
+
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
|
|
515
|
+
};
|
|
516
|
+
const getUrlFromDirectPath = (directPath, host = exports.DEF_MEDIA_HOST) => `https://${host}${directPath}`;
|
|
517
|
+
exports.getUrlFromDirectPath = getUrlFromDirectPath;
|
|
518
|
+
const extractHost = (url) => {
|
|
519
|
+
if (!url)
|
|
520
|
+
return undefined;
|
|
521
|
+
try {
|
|
522
|
+
return new url_1.URL(url).host;
|
|
523
|
+
}
|
|
524
|
+
catch {
|
|
525
|
+
return undefined;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
529
|
+
// Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
|
|
530
|
+
// Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
|
|
531
|
+
const fallbackHost = opts.host ?? extractHost(url);
|
|
532
|
+
const downloadUrl = directPath ? (0, exports.getUrlFromDirectPath)(directPath, fallbackHost) : url;
|
|
533
|
+
if (!downloadUrl) {
|
|
534
|
+
throw new boom_1.Boom('No valid media URL or directPath present in message', { statusCode: 400 });
|
|
535
|
+
}
|
|
536
|
+
const keys = await getMediaKeys(mediaKey, type);
|
|
537
|
+
// Vanz@Fix (bug 24): was single-attempt only — now retries up to 3x with delay
|
|
538
|
+
const MAX_RETRIES = 3;
|
|
539
|
+
let lastErr;
|
|
540
|
+
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
|
541
|
+
try {
|
|
542
|
+
return await (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
|
|
543
|
+
}
|
|
544
|
+
catch (err) {
|
|
545
|
+
lastErr = err;
|
|
546
|
+
if (attempt < MAX_RETRIES - 1) {
|
|
547
|
+
await new Promise(r => setTimeout(r, 500 * (attempt + 1)));
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
throw lastErr;
|
|
552
|
+
};
|
|
553
|
+
exports.downloadContentFromMessage = downloadContentFromMessage;
|
|
554
|
+
/**
|
|
555
|
+
* Decrypts and downloads an AES256-CBC encrypted file given the keys.
|
|
556
|
+
* Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
|
|
557
|
+
* */
|
|
558
|
+
const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
559
|
+
let bytesFetched = 0;
|
|
560
|
+
let startChunk = 0;
|
|
561
|
+
let firstBlockIsIV = false;
|
|
562
|
+
// if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
|
|
563
|
+
if (startByte) {
|
|
564
|
+
const chunk = toSmallestChunkSize(startByte || 0);
|
|
565
|
+
if (chunk) {
|
|
566
|
+
startChunk = chunk - AES_CHUNK_SIZE;
|
|
567
|
+
bytesFetched = chunk;
|
|
568
|
+
firstBlockIsIV = true;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
|
|
572
|
+
const headersInit = options?.headers ? options.headers : undefined;
|
|
573
|
+
const headers = {
|
|
574
|
+
...(headersInit
|
|
575
|
+
? Array.isArray(headersInit)
|
|
576
|
+
? Object.fromEntries(headersInit)
|
|
577
|
+
: headersInit
|
|
578
|
+
: {}),
|
|
579
|
+
Origin: index_js_2.DEFAULT_ORIGIN
|
|
580
|
+
};
|
|
581
|
+
if (startChunk || endChunk) {
|
|
582
|
+
headers.Range = `bytes=${startChunk}-`;
|
|
583
|
+
if (endChunk) {
|
|
584
|
+
headers.Range += endChunk;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
// download the message
|
|
588
|
+
const fetched = await (0, exports.getHttpStream)(downloadUrl, {
|
|
589
|
+
...(options || {}),
|
|
590
|
+
headers
|
|
591
|
+
});
|
|
592
|
+
let remainingBytes = Buffer.from([]);
|
|
593
|
+
let aes;
|
|
594
|
+
const pushBytes = (bytes, push) => {
|
|
595
|
+
if (startByte || endByte) {
|
|
596
|
+
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
|
|
597
|
+
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
|
|
598
|
+
push(bytes.slice(start, end));
|
|
599
|
+
bytesFetched += bytes.length;
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
push(bytes);
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
const output = new stream_1.Transform({
|
|
606
|
+
transform(chunk, _, callback) {
|
|
607
|
+
let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
|
|
608
|
+
const decryptLength = toSmallestChunkSize(data.length);
|
|
609
|
+
remainingBytes = data.slice(decryptLength);
|
|
610
|
+
data = data.slice(0, decryptLength);
|
|
611
|
+
if (!aes) {
|
|
612
|
+
let ivValue = iv;
|
|
613
|
+
if (firstBlockIsIV) {
|
|
614
|
+
ivValue = data.slice(0, AES_CHUNK_SIZE);
|
|
615
|
+
data = data.slice(AES_CHUNK_SIZE);
|
|
616
|
+
}
|
|
617
|
+
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
|
|
618
|
+
// if an end byte that is not EOF is specified
|
|
619
|
+
// stop auto padding (PKCS7) -- otherwise throws an error for decryption
|
|
620
|
+
if (endByte) {
|
|
621
|
+
aes.setAutoPadding(false);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
try {
|
|
625
|
+
pushBytes(aes.update(data), b => this.push(b));
|
|
626
|
+
callback();
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
callback(error);
|
|
630
|
+
}
|
|
631
|
+
},
|
|
632
|
+
final(callback) {
|
|
633
|
+
try {
|
|
634
|
+
pushBytes(aes.final(), b => this.push(b));
|
|
635
|
+
callback();
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
callback(error);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
});
|
|
642
|
+
return fetched.pipe(output, { end: true });
|
|
643
|
+
};
|
|
644
|
+
exports.downloadEncryptedContent = downloadEncryptedContent;
|
|
645
|
+
function extensionForMediaMessage(message) {
|
|
646
|
+
const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
|
|
647
|
+
const type = Object.keys(message)[0];
|
|
648
|
+
let extension;
|
|
649
|
+
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
|
|
650
|
+
extension = '.jpeg';
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
const messageContent = message[type];
|
|
654
|
+
extension = getExtension(messageContent.mimetype);
|
|
655
|
+
}
|
|
656
|
+
return extension;
|
|
657
|
+
}
|
|
658
|
+
const isNodeRuntime = () => {
|
|
659
|
+
return (typeof process !== 'undefined' &&
|
|
660
|
+
process.versions?.node !== null &&
|
|
661
|
+
typeof process.versions.bun === 'undefined' &&
|
|
662
|
+
typeof globalThis.Deno === 'undefined');
|
|
663
|
+
};
|
|
664
|
+
const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
|
|
665
|
+
if (redirectCount > 5) {
|
|
666
|
+
throw new Error('Too many redirects');
|
|
667
|
+
}
|
|
668
|
+
const parsedUrl = new url_1.URL(url);
|
|
669
|
+
const httpModule = parsedUrl.protocol === 'https:' ? await Promise.resolve().then(() => __importStar(require('https'))) : await Promise.resolve().then(() => __importStar(require('http')));
|
|
670
|
+
// Get file size for Content-Length header (required for Node.js streaming)
|
|
671
|
+
const fileStats = await fs_1.promises.stat(filePath);
|
|
672
|
+
const fileSize = fileStats.size;
|
|
673
|
+
return new Promise((resolve, reject) => {
|
|
674
|
+
const req = httpModule.request({
|
|
675
|
+
hostname: parsedUrl.hostname,
|
|
676
|
+
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
|
677
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
678
|
+
method: 'POST',
|
|
679
|
+
headers: {
|
|
680
|
+
...headers,
|
|
681
|
+
'Content-Length': fileSize
|
|
682
|
+
},
|
|
683
|
+
agent,
|
|
684
|
+
timeout: timeoutMs
|
|
685
|
+
}, res => {
|
|
686
|
+
// Handle redirects (3xx)
|
|
687
|
+
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
688
|
+
res.resume(); // Consume response to free resources
|
|
689
|
+
const newUrl = new url_1.URL(res.headers.location, url).toString();
|
|
690
|
+
resolve((0, exports.uploadWithNodeHttp)({
|
|
691
|
+
url: newUrl,
|
|
692
|
+
filePath,
|
|
693
|
+
headers,
|
|
694
|
+
timeoutMs,
|
|
695
|
+
agent
|
|
696
|
+
}, redirectCount + 1));
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
let body = '';
|
|
700
|
+
res.on('data', chunk => (body += chunk));
|
|
701
|
+
res.on('end', () => {
|
|
702
|
+
try {
|
|
703
|
+
resolve(JSON.parse(body));
|
|
704
|
+
}
|
|
705
|
+
catch {
|
|
706
|
+
resolve(undefined);
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
});
|
|
710
|
+
req.on('error', reject);
|
|
711
|
+
req.on('timeout', () => {
|
|
712
|
+
req.destroy();
|
|
713
|
+
reject(new Error('Upload timeout'));
|
|
714
|
+
});
|
|
715
|
+
const stream = (0, fs_1.createReadStream)(filePath);
|
|
716
|
+
stream.pipe(req);
|
|
717
|
+
stream.on('error', err => {
|
|
718
|
+
req.destroy();
|
|
719
|
+
reject(err);
|
|
720
|
+
});
|
|
721
|
+
});
|
|
722
|
+
};
|
|
723
|
+
exports.uploadWithNodeHttp = uploadWithNodeHttp;
|
|
724
|
+
const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
|
|
725
|
+
// Convert Node.js Readable to Web ReadableStream
|
|
726
|
+
const nodeStream = (0, fs_1.createReadStream)(filePath);
|
|
727
|
+
const webStream = stream_1.Readable.toWeb(nodeStream);
|
|
728
|
+
// Native fetch only accepts Undici-style dispatchers, not generic https Agents.
|
|
729
|
+
const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
|
|
730
|
+
const response = await fetch(url, {
|
|
731
|
+
...(dispatcher ? { dispatcher } : {}),
|
|
732
|
+
method: 'POST',
|
|
733
|
+
body: webStream,
|
|
734
|
+
headers,
|
|
735
|
+
duplex: 'half',
|
|
736
|
+
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
737
|
+
});
|
|
738
|
+
try {
|
|
739
|
+
return (await response.json());
|
|
740
|
+
}
|
|
741
|
+
catch {
|
|
742
|
+
return undefined;
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
/**
|
|
746
|
+
* Uploads media to WhatsApp servers.
|
|
747
|
+
*
|
|
748
|
+
* ## Why we have two upload implementations:
|
|
749
|
+
*
|
|
750
|
+
* Node.js's native `fetch` (powered by undici) has a known bug where it buffers
|
|
751
|
+
* the entire request body in memory before sending, even when using streams.
|
|
752
|
+
* This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
|
|
753
|
+
* See: https://github.com/nodejs/undici/issues/4058
|
|
754
|
+
*
|
|
755
|
+
* Other runtimes (Bun, Deno, browsers) correctly stream the request body without
|
|
756
|
+
* buffering, so we can use the web-standard Fetch API there.
|
|
757
|
+
*
|
|
758
|
+
* ## Future considerations:
|
|
759
|
+
* Once the undici bug is fixed, we can simplify this to use only the Fetch API
|
|
760
|
+
* across all runtimes. Monitor the GitHub issue for updates.
|
|
761
|
+
*/
|
|
762
|
+
const uploadMedia = async (params, logger) => {
|
|
763
|
+
if (isNodeRuntime()) {
|
|
764
|
+
logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
|
|
765
|
+
return (0, exports.uploadWithNodeHttp)(params);
|
|
766
|
+
}
|
|
767
|
+
else {
|
|
768
|
+
logger?.debug('Using web-standard Fetch API for upload');
|
|
769
|
+
return uploadWithFetch(params);
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
773
|
+
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
|
|
774
|
+
// send a query JSON to obtain the url & auth token to upload our media
|
|
775
|
+
let uploadInfo = await refreshMediaConn(false);
|
|
776
|
+
let urls;
|
|
777
|
+
const hosts = [...customUploadHosts, ...uploadInfo.hosts];
|
|
778
|
+
fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
|
|
779
|
+
// Prepare common headers
|
|
780
|
+
const customHeaders = (() => {
|
|
781
|
+
const hdrs = options?.headers;
|
|
782
|
+
if (!hdrs)
|
|
783
|
+
return {};
|
|
784
|
+
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
|
|
785
|
+
})();
|
|
786
|
+
const headers = {
|
|
787
|
+
...customHeaders,
|
|
788
|
+
'Content-Type': 'application/octet-stream',
|
|
789
|
+
Origin: index_js_2.DEFAULT_ORIGIN
|
|
790
|
+
};
|
|
791
|
+
for (let hostIdx = 0; hostIdx < hosts.length; hostIdx++) {
|
|
792
|
+
const { hostname } = hosts[hostIdx];
|
|
793
|
+
logger.debug(`uploading to "${hostname}"`);
|
|
794
|
+
const auth = encodeURIComponent(uploadInfo.auth);
|
|
795
|
+
// Lia@Changes 06-02-26 --- Switch media path map for newsletter uploads
|
|
796
|
+
const mediaPathMap = newsletter ? index_js_2.NEWSLETTER_MEDIA_PATH_MAP : index_js_2.MEDIA_PATH_MAP;
|
|
797
|
+
// Lia@Changes 20-03-26 --- Add server thumb for newsletter media
|
|
798
|
+
const serverThumb = newsletter ? '&server_thumb_gen=1' : '';
|
|
799
|
+
const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`;
|
|
800
|
+
let result;
|
|
801
|
+
try {
|
|
802
|
+
result = await uploadMedia({
|
|
803
|
+
url,
|
|
804
|
+
filePath,
|
|
805
|
+
headers,
|
|
806
|
+
timeoutMs,
|
|
807
|
+
agent: fetchAgent
|
|
808
|
+
}, logger);
|
|
809
|
+
if (result?.url || result?.direct_path) {
|
|
810
|
+
urls = {
|
|
811
|
+
mediaUrl: result.url,
|
|
812
|
+
directPath: result.direct_path,
|
|
813
|
+
meta_hmac: result.meta_hmac,
|
|
814
|
+
fbid: result.fbid,
|
|
815
|
+
ts: result.ts,
|
|
816
|
+
thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
|
|
817
|
+
thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
|
|
818
|
+
};
|
|
819
|
+
break;
|
|
820
|
+
}
|
|
821
|
+
else {
|
|
822
|
+
uploadInfo = await refreshMediaConn(true);
|
|
823
|
+
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
catch (error) {
|
|
827
|
+
const isLast = hostIdx === hosts.length - 1;
|
|
828
|
+
logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
|
|
829
|
+
// Vanz@Fix (bug 23): add exponential backoff delay between hosts instead of immediate retry
|
|
830
|
+
if (!isLast) {
|
|
831
|
+
await new Promise(r => setTimeout(r, 300 * (hostIdx + 1)));
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
if (!urls) {
|
|
836
|
+
throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
|
|
837
|
+
}
|
|
838
|
+
return urls;
|
|
839
|
+
};
|
|
840
|
+
};
|
|
841
|
+
exports.getWAUploadToServer = getWAUploadToServer;
|
|
842
|
+
const getMediaRetryKey = (mediaKey) => {
|
|
843
|
+
return (0, crypto_js_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
|
|
844
|
+
};
|
|
845
|
+
/**
|
|
846
|
+
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
|
847
|
+
*/
|
|
848
|
+
const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
849
|
+
const recp = { stanzaId: key.id };
|
|
850
|
+
const recpBuffer = index_js_1.proto.ServerErrorReceipt.encode(recp).finish();
|
|
851
|
+
const iv = Crypto.randomBytes(12);
|
|
852
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
853
|
+
const ciphertext = (0, crypto_js_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
|
|
854
|
+
const req = {
|
|
855
|
+
tag: 'receipt',
|
|
856
|
+
attrs: {
|
|
857
|
+
id: key.id,
|
|
858
|
+
to: (0, index_js_3.jidNormalizedUser)(meId),
|
|
859
|
+
type: 'server-error'
|
|
860
|
+
},
|
|
861
|
+
content: [
|
|
862
|
+
// this encrypt node is actually pretty useless
|
|
863
|
+
// the media is returned even without this node
|
|
864
|
+
// keeping it here to maintain parity with WA Web
|
|
865
|
+
{
|
|
866
|
+
tag: 'encrypt',
|
|
867
|
+
attrs: {},
|
|
868
|
+
content: [
|
|
869
|
+
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
870
|
+
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
871
|
+
]
|
|
872
|
+
},
|
|
873
|
+
{
|
|
874
|
+
tag: 'rmr',
|
|
875
|
+
attrs: {
|
|
876
|
+
jid: key.remoteJid,
|
|
877
|
+
from_me: (!!key.fromMe).toString(),
|
|
878
|
+
// @ts-ignore
|
|
879
|
+
participant: key.participant || undefined
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
]
|
|
883
|
+
};
|
|
884
|
+
return req;
|
|
885
|
+
};
|
|
886
|
+
exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
|
|
887
|
+
const decodeMediaRetryNode = (node) => {
|
|
888
|
+
const rmrNode = (0, index_js_3.getBinaryNodeChild)(node, 'rmr');
|
|
889
|
+
const event = {
|
|
890
|
+
key: {
|
|
891
|
+
id: node.attrs.id,
|
|
892
|
+
remoteJid: rmrNode.attrs.jid,
|
|
893
|
+
fromMe: rmrNode.attrs.from_me === 'true',
|
|
894
|
+
participant: rmrNode.attrs.participant
|
|
895
|
+
}
|
|
896
|
+
};
|
|
897
|
+
const errorNode = (0, index_js_3.getBinaryNodeChild)(node, 'error');
|
|
898
|
+
if (errorNode) {
|
|
899
|
+
const errorCode = +errorNode.attrs.code;
|
|
900
|
+
event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, {
|
|
901
|
+
data: errorNode.attrs,
|
|
902
|
+
statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode)
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
else {
|
|
906
|
+
const encryptedInfoNode = (0, index_js_3.getBinaryNodeChild)(node, 'encrypt');
|
|
907
|
+
const ciphertext = (0, index_js_3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
|
|
908
|
+
const iv = (0, index_js_3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
|
|
909
|
+
if (ciphertext && iv) {
|
|
910
|
+
event.media = { ciphertext, iv };
|
|
911
|
+
}
|
|
912
|
+
else {
|
|
913
|
+
event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
return event;
|
|
917
|
+
};
|
|
918
|
+
exports.decodeMediaRetryNode = decodeMediaRetryNode;
|
|
919
|
+
const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
920
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
921
|
+
const plaintext = (0, crypto_js_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
|
|
922
|
+
return index_js_1.proto.MediaRetryNotification.decode(plaintext);
|
|
923
|
+
};
|
|
924
|
+
exports.decryptMediaRetryData = decryptMediaRetryData;
|
|
925
|
+
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
|
|
926
|
+
exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
|
|
927
|
+
const MEDIA_RETRY_STATUS_MAP = {
|
|
928
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
929
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
930
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
931
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
932
|
+
};
|
|
933
|
+
//# sourceMappingURL=messages-media.js.map
|