@genuxofficial/baileys 1.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/LICENSE +21 -0
- package/README.md +1 -0
- package/WAProto/GenerateStatics.sh +4 -0
- package/WAProto/WAProto.proto +3344 -0
- package/WAProto/index.d.ts +37016 -0
- package/WAProto/index.js +101044 -0
- package/WASignalGroup/GroupProtocol.js +1697 -0
- package/WASignalGroup/ciphertext_message.js +16 -0
- package/WASignalGroup/group_cipher.js +120 -0
- package/WASignalGroup/group_session_builder.js +46 -0
- package/WASignalGroup/index.js +5 -0
- package/WASignalGroup/keyhelper.js +21 -0
- package/WASignalGroup/protobufs.js +3 -0
- package/WASignalGroup/queue_job.js +69 -0
- package/WASignalGroup/sender_chain_key.js +50 -0
- package/WASignalGroup/sender_key_distribution_message.js +78 -0
- package/WASignalGroup/sender_key_message.js +92 -0
- package/WASignalGroup/sender_key_name.js +70 -0
- package/WASignalGroup/sender_key_record.js +56 -0
- package/WASignalGroup/sender_key_state.js +129 -0
- package/WASignalGroup/sender_message_key.js +39 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.d.ts +53 -0
- package/lib/Defaults/index.js +106 -0
- package/lib/Signal/libsignal.d.ts +3 -0
- package/lib/Signal/libsignal.js +152 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/lib/Socket/Client/index.js +18 -0
- package/lib/Socket/Client/types.d.ts +17 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.d.ts +12 -0
- package/lib/Socket/Client/websocket.js +62 -0
- package/lib/Socket/business.d.ts +149 -0
- package/lib/Socket/business.js +260 -0
- package/lib/Socket/chats.d.ts +85 -0
- package/lib/Socket/chats.js +850 -0
- package/lib/Socket/groups.d.ts +124 -0
- package/lib/Socket/groups.js +314 -0
- package/lib/Socket/index.d.ts +149 -0
- package/lib/Socket/index.js +10 -0
- package/lib/Socket/messages-recv.d.ts +136 -0
- package/lib/Socket/messages-recv.js +912 -0
- package/lib/Socket/messages-send.d.ts +130 -0
- package/lib/Socket/messages-send.js +673 -0
- package/lib/Socket/socket.d.ts +45 -0
- package/lib/Socket/socket.js +622 -0
- package/lib/Socket/usync.d.ts +38 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.d.ts +3 -0
- package/lib/Store/index.js +10 -0
- package/lib/Store/make-cache-manager-store.d.ts +14 -0
- package/lib/Store/make-cache-manager-store.js +83 -0
- package/lib/Store/make-in-memory-store.d.ts +118 -0
- package/lib/Store/make-in-memory-store.js +420 -0
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.d.ts +105 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.d.ts +13 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.d.ts +108 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.d.ts +19 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.d.ts +172 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.d.ts +56 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.d.ts +46 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.d.ts +29 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.d.ts +271 -0
- package/lib/Types/Message.js +9 -0
- package/lib/Types/Product.d.ts +78 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.d.ts +57 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.d.ts +118 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.d.ts +27 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.d.ts +25 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.d.ts +63 -0
- package/lib/Types/index.js +41 -0
- package/lib/Utils/auth-utils.d.ts +18 -0
- package/lib/Utils/auth-utils.js +200 -0
- package/lib/Utils/baileys-event-stream.d.ts +16 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.d.ts +22 -0
- package/lib/Utils/business.js +234 -0
- package/lib/Utils/chat-utils.d.ts +72 -0
- package/lib/Utils/chat-utils.js +745 -0
- package/lib/Utils/crypto.d.ts +42 -0
- package/lib/Utils/crypto.js +181 -0
- package/lib/Utils/decode-wa-message.d.ts +36 -0
- package/lib/Utils/decode-wa-message.js +205 -0
- package/lib/Utils/event-buffer.d.ts +35 -0
- package/lib/Utils/event-buffer.js +520 -0
- package/lib/Utils/generics.d.ts +94 -0
- package/lib/Utils/generics.js +433 -0
- package/lib/Utils/history.d.ts +19 -0
- package/lib/Utils/history.js +94 -0
- package/lib/Utils/index.d.ts +17 -0
- package/lib/Utils/index.js +33 -0
- package/lib/Utils/link-preview.d.ts +21 -0
- package/lib/Utils/link-preview.js +116 -0
- package/lib/Utils/logger.d.ts +11 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/lt-hash.js +51 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/messages-media.d.ts +108 -0
- package/lib/Utils/messages-media.js +667 -0
- package/lib/Utils/messages.d.ts +78 -0
- package/lib/Utils/messages.js +760 -0
- package/lib/Utils/noise-handler.d.ts +21 -0
- package/lib/Utils/noise-handler.js +150 -0
- package/lib/Utils/process-message.d.ts +42 -0
- package/lib/Utils/process-message.js +373 -0
- package/lib/Utils/signal.d.ts +33 -0
- package/lib/Utils/signal.js +153 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
- package/lib/Utils/use-multi-file-auth-state.js +94 -0
- package/lib/Utils/validate-connection.d.ts +10 -0
- package/lib/Utils/validate-connection.js +175 -0
- package/lib/WABinary/constants.d.ts +27 -0
- package/lib/WABinary/constants.js +40 -0
- package/lib/WABinary/decode.d.ts +8 -0
- package/lib/WABinary/decode.js +254 -0
- package/lib/WABinary/encode.d.ts +4 -0
- package/lib/WABinary/encode.js +234 -0
- package/lib/WABinary/generic-utils.d.ts +16 -0
- package/lib/WABinary/generic-utils.js +110 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.d.ts +31 -0
- package/lib/WABinary/jid-utils.js +62 -0
- package/lib/WABinary/types.d.ts +18 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +18 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.d.ts +39 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.d.ts +4 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/index.d.ts +4 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.d.ts +26 -0
- package/lib/WAUSync/USyncQuery.js +79 -0
- package/lib/WAUSync/USyncUser.d.ts +10 -0
- package/lib/WAUSync/USyncUser.js +22 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +31 -0
- package/package.json +104 -0
@@ -0,0 +1,667 @@
|
|
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 (mod) {
|
19
|
+
if (mod && mod.__esModule) return mod;
|
20
|
+
var result = {};
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
22
|
+
__setModuleDefault(result, mod);
|
23
|
+
return result;
|
24
|
+
};
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
27
|
+
};
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
29
|
+
exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.extensionForMediaMessage = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.getHttpStream = exports.generateThumbnail = exports.getStream = exports.toBuffer = exports.toReadable = exports.getAudioWaveform = exports.getAudioDuration = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.getMediaKeys = exports.hkdfInfoKey = void 0;
|
30
|
+
const boom_1 = require("@hapi/boom");
|
31
|
+
const axios_1 = __importDefault(require("axios"));
|
32
|
+
const child_process_1 = require("child_process");
|
33
|
+
const Crypto = __importStar(require("crypto"));
|
34
|
+
const events_1 = require("events");
|
35
|
+
const fs_1 = require("fs");
|
36
|
+
const os_1 = require("os");
|
37
|
+
const path_1 = require("path");
|
38
|
+
const stream_1 = require("stream");
|
39
|
+
const WAProto_1 = require("../../WAProto");
|
40
|
+
const Defaults_1 = require("../Defaults");
|
41
|
+
const WABinary_1 = require("../WABinary");
|
42
|
+
const crypto_1 = require("./crypto");
|
43
|
+
const generics_1 = require("./generics");
|
44
|
+
const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
|
45
|
+
const getImageProcessingLibrary = async () => {
|
46
|
+
const [_jimp, sharp] = await Promise.all([
|
47
|
+
(async () => {
|
48
|
+
const jimp = await (Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }));
|
49
|
+
return jimp;
|
50
|
+
})(),
|
51
|
+
(async () => {
|
52
|
+
const sharp = await (Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }));
|
53
|
+
return sharp;
|
54
|
+
})()
|
55
|
+
]);
|
56
|
+
if (sharp) {
|
57
|
+
return { sharp };
|
58
|
+
}
|
59
|
+
const jimp = (_jimp === null || _jimp === void 0 ? void 0 : _jimp.default) || _jimp;
|
60
|
+
if (jimp) {
|
61
|
+
return { jimp };
|
62
|
+
}
|
63
|
+
throw new boom_1.Boom('No image processing library available');
|
64
|
+
};
|
65
|
+
const hkdfInfoKey = (type) => {
|
66
|
+
const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
|
67
|
+
return `WhatsApp ${hkdfInfo} Keys`;
|
68
|
+
};
|
69
|
+
exports.hkdfInfoKey = hkdfInfoKey;
|
70
|
+
/** generates all the keys required to encrypt/decrypt & sign a media message */
|
71
|
+
async function getMediaKeys(buffer, mediaType) {
|
72
|
+
if (!buffer) {
|
73
|
+
throw new boom_1.Boom('Cannot derive from empty media key');
|
74
|
+
}
|
75
|
+
if (typeof buffer === 'string') {
|
76
|
+
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
|
77
|
+
}
|
78
|
+
// expand using HKDF to 112 bytes, also pass in the relevant app info
|
79
|
+
const expandedMediaKey = await (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
|
80
|
+
return {
|
81
|
+
iv: expandedMediaKey.slice(0, 16),
|
82
|
+
cipherKey: expandedMediaKey.slice(16, 48),
|
83
|
+
macKey: expandedMediaKey.slice(48, 80),
|
84
|
+
};
|
85
|
+
}
|
86
|
+
exports.getMediaKeys = getMediaKeys;
|
87
|
+
/** Extracts video thumb using FFMPEG */
|
88
|
+
const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
|
89
|
+
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
|
90
|
+
(0, child_process_1.exec)(cmd, (err) => {
|
91
|
+
if (err) {
|
92
|
+
reject(err);
|
93
|
+
}
|
94
|
+
else {
|
95
|
+
resolve();
|
96
|
+
}
|
97
|
+
});
|
98
|
+
});
|
99
|
+
const extractImageThumb = async (bufferOrFilePath, width = 32) => {
|
100
|
+
var _a, _b;
|
101
|
+
if (bufferOrFilePath instanceof stream_1.Readable) {
|
102
|
+
bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
|
103
|
+
}
|
104
|
+
const lib = await getImageProcessingLibrary();
|
105
|
+
if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
|
106
|
+
const img = lib.sharp.default(bufferOrFilePath);
|
107
|
+
const dimensions = await img.metadata();
|
108
|
+
const buffer = await img
|
109
|
+
.resize(width)
|
110
|
+
.jpeg({ quality: 50 })
|
111
|
+
.toBuffer();
|
112
|
+
return {
|
113
|
+
buffer,
|
114
|
+
original: {
|
115
|
+
width: dimensions.width,
|
116
|
+
height: dimensions.height,
|
117
|
+
},
|
118
|
+
};
|
119
|
+
}
|
120
|
+
else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
|
121
|
+
const { read, MIME_JPEG, RESIZE_BILINEAR, AUTO } = lib.jimp;
|
122
|
+
const jimp = await read(bufferOrFilePath);
|
123
|
+
const dimensions = {
|
124
|
+
width: jimp.getWidth(),
|
125
|
+
height: jimp.getHeight()
|
126
|
+
};
|
127
|
+
const buffer = await jimp
|
128
|
+
.quality(50)
|
129
|
+
.resize(width, AUTO, RESIZE_BILINEAR)
|
130
|
+
.getBufferAsync(MIME_JPEG);
|
131
|
+
return {
|
132
|
+
buffer,
|
133
|
+
original: dimensions
|
134
|
+
};
|
135
|
+
}
|
136
|
+
else {
|
137
|
+
throw new boom_1.Boom('No image processing library available');
|
138
|
+
}
|
139
|
+
};
|
140
|
+
exports.extractImageThumb = extractImageThumb;
|
141
|
+
const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
|
142
|
+
.replace(/\+/g, '-')
|
143
|
+
.replace(/\//g, '_')
|
144
|
+
.replace(/\=+$/, '')));
|
145
|
+
exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
|
146
|
+
const generateProfilePicture = async (mediaUpload) => {
|
147
|
+
var _a, _b;
|
148
|
+
let bufferOrFilePath;
|
149
|
+
if (Buffer.isBuffer(mediaUpload)) {
|
150
|
+
bufferOrFilePath = mediaUpload;
|
151
|
+
}
|
152
|
+
else if ('url' in mediaUpload) {
|
153
|
+
bufferOrFilePath = mediaUpload.url.toString();
|
154
|
+
}
|
155
|
+
else {
|
156
|
+
bufferOrFilePath = await (0, exports.toBuffer)(mediaUpload.stream);
|
157
|
+
}
|
158
|
+
const lib = await getImageProcessingLibrary();
|
159
|
+
let img;
|
160
|
+
if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
|
161
|
+
img = lib.sharp.default(bufferOrFilePath)
|
162
|
+
.resize(640, 640)
|
163
|
+
.jpeg({
|
164
|
+
quality: 50,
|
165
|
+
})
|
166
|
+
.toBuffer();
|
167
|
+
}
|
168
|
+
else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
|
169
|
+
const { read, MIME_JPEG, RESIZE_BILINEAR } = lib.jimp;
|
170
|
+
const jimp = await read(bufferOrFilePath);
|
171
|
+
const min = Math.min(jimp.getWidth(), jimp.getHeight());
|
172
|
+
const cropped = jimp.crop(0, 0, min, min);
|
173
|
+
img = cropped
|
174
|
+
.quality(50)
|
175
|
+
.resize(640, 640, RESIZE_BILINEAR)
|
176
|
+
.getBufferAsync(MIME_JPEG);
|
177
|
+
}
|
178
|
+
else {
|
179
|
+
throw new boom_1.Boom('No image processing library available');
|
180
|
+
}
|
181
|
+
return {
|
182
|
+
img: await img,
|
183
|
+
};
|
184
|
+
};
|
185
|
+
exports.generateProfilePicture = generateProfilePicture;
|
186
|
+
/** gets the SHA256 of the given media message */
|
187
|
+
const mediaMessageSHA256B64 = (message) => {
|
188
|
+
const media = Object.values(message)[0];
|
189
|
+
return (media === null || media === void 0 ? void 0 : media.fileSha256) && Buffer.from(media.fileSha256).toString('base64');
|
190
|
+
};
|
191
|
+
exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
|
192
|
+
async function getAudioDuration(buffer) {
|
193
|
+
const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
|
194
|
+
let metadata;
|
195
|
+
if (Buffer.isBuffer(buffer)) {
|
196
|
+
metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
|
197
|
+
}
|
198
|
+
else if (typeof buffer === 'string') {
|
199
|
+
const rStream = (0, fs_1.createReadStream)(buffer);
|
200
|
+
try {
|
201
|
+
metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true });
|
202
|
+
}
|
203
|
+
finally {
|
204
|
+
rStream.destroy();
|
205
|
+
}
|
206
|
+
}
|
207
|
+
else {
|
208
|
+
metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true });
|
209
|
+
}
|
210
|
+
return metadata.format.duration;
|
211
|
+
}
|
212
|
+
exports.getAudioDuration = getAudioDuration;
|
213
|
+
/**
|
214
|
+
referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
|
215
|
+
*/
|
216
|
+
async function getAudioWaveform(buffer, logger) {
|
217
|
+
try {
|
218
|
+
const { default: decoder } = await eval('import(\'audio-decode\')');
|
219
|
+
let audioData;
|
220
|
+
if (Buffer.isBuffer(buffer)) {
|
221
|
+
audioData = buffer;
|
222
|
+
}
|
223
|
+
else if (typeof buffer === 'string') {
|
224
|
+
const rStream = (0, fs_1.createReadStream)(buffer);
|
225
|
+
audioData = await (0, exports.toBuffer)(rStream);
|
226
|
+
}
|
227
|
+
else {
|
228
|
+
audioData = await (0, exports.toBuffer)(buffer);
|
229
|
+
}
|
230
|
+
const audioBuffer = await decoder(audioData);
|
231
|
+
const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
|
232
|
+
const samples = 64; // Number of samples we want to have in our final data set
|
233
|
+
const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
|
234
|
+
const filteredData = [];
|
235
|
+
for (let i = 0; i < samples; i++) {
|
236
|
+
const blockStart = blockSize * i; // the location of the first sample in the block
|
237
|
+
let sum = 0;
|
238
|
+
for (let j = 0; j < blockSize; j++) {
|
239
|
+
sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
|
240
|
+
}
|
241
|
+
filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
|
242
|
+
}
|
243
|
+
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
244
|
+
const multiplier = Math.pow(Math.max(...filteredData), -1);
|
245
|
+
const normalizedData = filteredData.map((n) => n * multiplier);
|
246
|
+
// Generate waveform like WhatsApp
|
247
|
+
const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)));
|
248
|
+
return waveform;
|
249
|
+
}
|
250
|
+
catch (e) {
|
251
|
+
logger === null || logger === void 0 ? void 0 : logger.debug('Failed to generate waveform: ' + e);
|
252
|
+
}
|
253
|
+
}
|
254
|
+
exports.getAudioWaveform = getAudioWaveform;
|
255
|
+
const toReadable = (buffer) => {
|
256
|
+
const readable = new stream_1.Readable({ read: () => { } });
|
257
|
+
readable.push(buffer);
|
258
|
+
readable.push(null);
|
259
|
+
return readable;
|
260
|
+
};
|
261
|
+
exports.toReadable = toReadable;
|
262
|
+
const toBuffer = async (stream) => {
|
263
|
+
const chunks = [];
|
264
|
+
for await (const chunk of stream) {
|
265
|
+
chunks.push(chunk);
|
266
|
+
}
|
267
|
+
stream.destroy();
|
268
|
+
return Buffer.concat(chunks);
|
269
|
+
};
|
270
|
+
exports.toBuffer = toBuffer;
|
271
|
+
const getStream = async (item, opts) => {
|
272
|
+
if (Buffer.isBuffer(item)) {
|
273
|
+
return { stream: (0, exports.toReadable)(item), type: 'buffer' };
|
274
|
+
}
|
275
|
+
if ('stream' in item) {
|
276
|
+
return { stream: item.stream, type: 'readable' };
|
277
|
+
}
|
278
|
+
if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
|
279
|
+
return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
|
280
|
+
}
|
281
|
+
return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
|
282
|
+
};
|
283
|
+
exports.getStream = getStream;
|
284
|
+
/** generates a thumbnail for a given media, if required */
|
285
|
+
async function generateThumbnail(file, mediaType, options) {
|
286
|
+
var _a;
|
287
|
+
let thumbnail;
|
288
|
+
let originalImageDimensions;
|
289
|
+
if (mediaType === 'image') {
|
290
|
+
const { buffer, original } = await (0, exports.extractImageThumb)(file);
|
291
|
+
thumbnail = buffer.toString('base64');
|
292
|
+
if (original.width && original.height) {
|
293
|
+
originalImageDimensions = {
|
294
|
+
width: original.width,
|
295
|
+
height: original.height,
|
296
|
+
};
|
297
|
+
}
|
298
|
+
}
|
299
|
+
else if (mediaType === 'video') {
|
300
|
+
const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageID)() + '.jpg');
|
301
|
+
try {
|
302
|
+
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
|
303
|
+
const buff = await fs_1.promises.readFile(imgFilename);
|
304
|
+
thumbnail = buff.toString('base64');
|
305
|
+
await fs_1.promises.unlink(imgFilename);
|
306
|
+
}
|
307
|
+
catch (err) {
|
308
|
+
(_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug('could not generate video thumb: ' + err);
|
309
|
+
}
|
310
|
+
}
|
311
|
+
return {
|
312
|
+
thumbnail,
|
313
|
+
originalImageDimensions
|
314
|
+
};
|
315
|
+
}
|
316
|
+
exports.generateThumbnail = generateThumbnail;
|
317
|
+
const getHttpStream = async (url, options = {}) => {
|
318
|
+
const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' });
|
319
|
+
return fetched.data;
|
320
|
+
};
|
321
|
+
exports.getHttpStream = getHttpStream;
|
322
|
+
const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
323
|
+
const { stream, type } = await (0, exports.getStream)(media, opts);
|
324
|
+
logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
|
325
|
+
const mediaKey = Crypto.randomBytes(32);
|
326
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
|
327
|
+
const encWriteStream = new stream_1.Readable({ read: () => { } });
|
328
|
+
let bodyPath;
|
329
|
+
let writeStream;
|
330
|
+
let didSaveToTmpPath = false;
|
331
|
+
if (type === 'file') {
|
332
|
+
bodyPath = media.url.toString();
|
333
|
+
}
|
334
|
+
else if (saveOriginalFileIfRequired) {
|
335
|
+
bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageID)());
|
336
|
+
writeStream = (0, fs_1.createWriteStream)(bodyPath);
|
337
|
+
didSaveToTmpPath = true;
|
338
|
+
}
|
339
|
+
let fileLength = 0;
|
340
|
+
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
|
341
|
+
let hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
342
|
+
let sha256Plain = Crypto.createHash('sha256');
|
343
|
+
let sha256Enc = Crypto.createHash('sha256');
|
344
|
+
try {
|
345
|
+
for await (const data of stream) {
|
346
|
+
fileLength += data.length;
|
347
|
+
if (type === 'remote'
|
348
|
+
&& (opts === null || opts === void 0 ? void 0 : opts.maxContentLength)
|
349
|
+
&& fileLength + data.length > opts.maxContentLength) {
|
350
|
+
throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
|
351
|
+
data: { media, type }
|
352
|
+
});
|
353
|
+
}
|
354
|
+
sha256Plain = sha256Plain.update(data);
|
355
|
+
if (writeStream && !writeStream.write(data)) {
|
356
|
+
await (0, events_1.once)(writeStream, 'drain');
|
357
|
+
}
|
358
|
+
onChunk(aes.update(data));
|
359
|
+
}
|
360
|
+
onChunk(aes.final());
|
361
|
+
const mac = hmac.digest().slice(0, 10);
|
362
|
+
sha256Enc = sha256Enc.update(mac);
|
363
|
+
const fileSha256 = sha256Plain.digest();
|
364
|
+
const fileEncSha256 = sha256Enc.digest();
|
365
|
+
encWriteStream.push(mac);
|
366
|
+
encWriteStream.push(null);
|
367
|
+
writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
|
368
|
+
stream.destroy();
|
369
|
+
logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
|
370
|
+
return {
|
371
|
+
mediaKey,
|
372
|
+
encWriteStream,
|
373
|
+
bodyPath,
|
374
|
+
mac,
|
375
|
+
fileEncSha256,
|
376
|
+
fileSha256,
|
377
|
+
fileLength,
|
378
|
+
didSaveToTmpPath
|
379
|
+
};
|
380
|
+
}
|
381
|
+
catch (error) {
|
382
|
+
// destroy all streams with error
|
383
|
+
encWriteStream.destroy();
|
384
|
+
writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
|
385
|
+
aes.destroy();
|
386
|
+
hmac.destroy();
|
387
|
+
sha256Plain.destroy();
|
388
|
+
sha256Enc.destroy();
|
389
|
+
stream.destroy();
|
390
|
+
if (didSaveToTmpPath) {
|
391
|
+
try {
|
392
|
+
await fs_1.promises.unlink(bodyPath);
|
393
|
+
}
|
394
|
+
catch (err) {
|
395
|
+
logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
|
396
|
+
}
|
397
|
+
}
|
398
|
+
throw error;
|
399
|
+
}
|
400
|
+
function onChunk(buff) {
|
401
|
+
sha256Enc = sha256Enc.update(buff);
|
402
|
+
hmac = hmac.update(buff);
|
403
|
+
encWriteStream.push(buff);
|
404
|
+
}
|
405
|
+
};
|
406
|
+
exports.encryptedStream = encryptedStream;
|
407
|
+
const DEF_HOST = 'mmg.whatsapp.net';
|
408
|
+
const AES_CHUNK_SIZE = 16;
|
409
|
+
const toSmallestChunkSize = (num) => {
|
410
|
+
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
|
411
|
+
};
|
412
|
+
const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
|
413
|
+
exports.getUrlFromDirectPath = getUrlFromDirectPath;
|
414
|
+
const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
415
|
+
const downloadUrl = url || (0, exports.getUrlFromDirectPath)(directPath);
|
416
|
+
const keys = await getMediaKeys(mediaKey, type);
|
417
|
+
return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
|
418
|
+
};
|
419
|
+
exports.downloadContentFromMessage = downloadContentFromMessage;
|
420
|
+
/**
|
421
|
+
* Decrypts and downloads an AES256-CBC encrypted file given the keys.
|
422
|
+
* Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
|
423
|
+
* */
|
424
|
+
const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
425
|
+
let bytesFetched = 0;
|
426
|
+
let startChunk = 0;
|
427
|
+
let firstBlockIsIV = false;
|
428
|
+
// if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
|
429
|
+
if (startByte) {
|
430
|
+
const chunk = toSmallestChunkSize(startByte || 0);
|
431
|
+
if (chunk) {
|
432
|
+
startChunk = chunk - AES_CHUNK_SIZE;
|
433
|
+
bytesFetched = chunk;
|
434
|
+
firstBlockIsIV = true;
|
435
|
+
}
|
436
|
+
}
|
437
|
+
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
|
438
|
+
const headers = {
|
439
|
+
...(options === null || options === void 0 ? void 0 : options.headers) || {},
|
440
|
+
Origin: Defaults_1.DEFAULT_ORIGIN,
|
441
|
+
};
|
442
|
+
if (startChunk || endChunk) {
|
443
|
+
headers.Range = `bytes=${startChunk}-`;
|
444
|
+
if (endChunk) {
|
445
|
+
headers.Range += endChunk;
|
446
|
+
}
|
447
|
+
}
|
448
|
+
// download the message
|
449
|
+
const fetched = await (0, exports.getHttpStream)(downloadUrl, {
|
450
|
+
...options || {},
|
451
|
+
headers,
|
452
|
+
maxBodyLength: Infinity,
|
453
|
+
maxContentLength: Infinity,
|
454
|
+
});
|
455
|
+
let remainingBytes = Buffer.from([]);
|
456
|
+
let aes;
|
457
|
+
const pushBytes = (bytes, push) => {
|
458
|
+
if (startByte || endByte) {
|
459
|
+
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
|
460
|
+
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
|
461
|
+
push(bytes.slice(start, end));
|
462
|
+
bytesFetched += bytes.length;
|
463
|
+
}
|
464
|
+
else {
|
465
|
+
push(bytes);
|
466
|
+
}
|
467
|
+
};
|
468
|
+
const output = new stream_1.Transform({
|
469
|
+
transform(chunk, _, callback) {
|
470
|
+
let data = Buffer.concat([remainingBytes, chunk]);
|
471
|
+
const decryptLength = toSmallestChunkSize(data.length);
|
472
|
+
remainingBytes = data.slice(decryptLength);
|
473
|
+
data = data.slice(0, decryptLength);
|
474
|
+
if (!aes) {
|
475
|
+
let ivValue = iv;
|
476
|
+
if (firstBlockIsIV) {
|
477
|
+
ivValue = data.slice(0, AES_CHUNK_SIZE);
|
478
|
+
data = data.slice(AES_CHUNK_SIZE);
|
479
|
+
}
|
480
|
+
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
|
481
|
+
// if an end byte that is not EOF is specified
|
482
|
+
// stop auto padding (PKCS7) -- otherwise throws an error for decryption
|
483
|
+
if (endByte) {
|
484
|
+
aes.setAutoPadding(false);
|
485
|
+
}
|
486
|
+
}
|
487
|
+
try {
|
488
|
+
pushBytes(aes.update(data), b => this.push(b));
|
489
|
+
callback();
|
490
|
+
}
|
491
|
+
catch (error) {
|
492
|
+
callback(error);
|
493
|
+
}
|
494
|
+
},
|
495
|
+
final(callback) {
|
496
|
+
try {
|
497
|
+
pushBytes(aes.final(), b => this.push(b));
|
498
|
+
callback();
|
499
|
+
}
|
500
|
+
catch (error) {
|
501
|
+
callback(error);
|
502
|
+
}
|
503
|
+
},
|
504
|
+
});
|
505
|
+
return fetched.pipe(output, { end: true });
|
506
|
+
};
|
507
|
+
exports.downloadEncryptedContent = downloadEncryptedContent;
|
508
|
+
function extensionForMediaMessage(message) {
|
509
|
+
const getExtension = (mimetype) => mimetype.split(';')[0].split('/')[1];
|
510
|
+
const type = Object.keys(message)[0];
|
511
|
+
let extension;
|
512
|
+
if (type === 'locationMessage' ||
|
513
|
+
type === 'liveLocationMessage' ||
|
514
|
+
type === 'productMessage') {
|
515
|
+
extension = '.jpeg';
|
516
|
+
}
|
517
|
+
else {
|
518
|
+
const messageContent = message[type];
|
519
|
+
extension = getExtension(messageContent.mimetype);
|
520
|
+
}
|
521
|
+
return extension;
|
522
|
+
}
|
523
|
+
exports.extensionForMediaMessage = extensionForMediaMessage;
|
524
|
+
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
525
|
+
return async (stream, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
526
|
+
var _a, _b;
|
527
|
+
// send a query JSON to obtain the url & auth token to upload our media
|
528
|
+
let uploadInfo = await refreshMediaConn(false);
|
529
|
+
let urls;
|
530
|
+
const hosts = [...customUploadHosts, ...uploadInfo.hosts];
|
531
|
+
fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
|
532
|
+
for (const { hostname } of hosts) {
|
533
|
+
logger.debug(`uploading to "${hostname}"`);
|
534
|
+
const auth = encodeURIComponent(uploadInfo.auth); // the auth token
|
535
|
+
const url = `https://${hostname}${Defaults_1.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
|
536
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
537
|
+
let result;
|
538
|
+
try {
|
539
|
+
const body = await axios_1.default.post(url, stream, {
|
540
|
+
...options,
|
541
|
+
headers: {
|
542
|
+
...options.headers || {},
|
543
|
+
'Content-Type': 'application/octet-stream',
|
544
|
+
'Origin': Defaults_1.DEFAULT_ORIGIN
|
545
|
+
},
|
546
|
+
httpsAgent: fetchAgent,
|
547
|
+
timeout: timeoutMs,
|
548
|
+
responseType: 'json',
|
549
|
+
maxBodyLength: Infinity,
|
550
|
+
maxContentLength: Infinity,
|
551
|
+
});
|
552
|
+
result = body.data;
|
553
|
+
if ((result === null || result === void 0 ? void 0 : result.url) || (result === null || result === void 0 ? void 0 : result.directPath)) {
|
554
|
+
urls = {
|
555
|
+
mediaUrl: result.url,
|
556
|
+
directPath: result.direct_path
|
557
|
+
};
|
558
|
+
break;
|
559
|
+
}
|
560
|
+
else {
|
561
|
+
uploadInfo = await refreshMediaConn(true);
|
562
|
+
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
|
563
|
+
}
|
564
|
+
}
|
565
|
+
catch (error) {
|
566
|
+
if (axios_1.default.isAxiosError(error)) {
|
567
|
+
result = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
|
568
|
+
}
|
569
|
+
const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
|
570
|
+
logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
|
571
|
+
}
|
572
|
+
}
|
573
|
+
if (!urls) {
|
574
|
+
throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
|
575
|
+
}
|
576
|
+
return urls;
|
577
|
+
};
|
578
|
+
};
|
579
|
+
exports.getWAUploadToServer = getWAUploadToServer;
|
580
|
+
const getMediaRetryKey = (mediaKey) => {
|
581
|
+
return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
|
582
|
+
};
|
583
|
+
/**
|
584
|
+
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
585
|
+
*/
|
586
|
+
const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
|
587
|
+
const recp = { stanzaId: key.id };
|
588
|
+
const recpBuffer = WAProto_1.proto.ServerErrorReceipt.encode(recp).finish();
|
589
|
+
const iv = Crypto.randomBytes(12);
|
590
|
+
const retryKey = await getMediaRetryKey(mediaKey);
|
591
|
+
const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
|
592
|
+
const req = {
|
593
|
+
tag: 'receipt',
|
594
|
+
attrs: {
|
595
|
+
id: key.id,
|
596
|
+
to: (0, WABinary_1.jidNormalizedUser)(meId),
|
597
|
+
type: 'server-error'
|
598
|
+
},
|
599
|
+
content: [
|
600
|
+
// this encrypt node is actually pretty useless
|
601
|
+
// the media is returned even without this node
|
602
|
+
// keeping it here to maintain parity with WA Web
|
603
|
+
{
|
604
|
+
tag: 'encrypt',
|
605
|
+
attrs: {},
|
606
|
+
content: [
|
607
|
+
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
608
|
+
{ tag: 'enc_iv', attrs: {}, content: iv }
|
609
|
+
]
|
610
|
+
},
|
611
|
+
{
|
612
|
+
tag: 'rmr',
|
613
|
+
attrs: {
|
614
|
+
jid: key.remoteJid,
|
615
|
+
'from_me': (!!key.fromMe).toString(),
|
616
|
+
// @ts-ignore
|
617
|
+
participant: key.participant || undefined
|
618
|
+
}
|
619
|
+
}
|
620
|
+
]
|
621
|
+
};
|
622
|
+
return req;
|
623
|
+
};
|
624
|
+
exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
|
625
|
+
const decodeMediaRetryNode = (node) => {
|
626
|
+
const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
|
627
|
+
const event = {
|
628
|
+
key: {
|
629
|
+
id: node.attrs.id,
|
630
|
+
remoteJid: rmrNode.attrs.jid,
|
631
|
+
fromMe: rmrNode.attrs.from_me === 'true',
|
632
|
+
participant: rmrNode.attrs.participant
|
633
|
+
}
|
634
|
+
};
|
635
|
+
const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
|
636
|
+
if (errorNode) {
|
637
|
+
const errorCode = +errorNode.attrs.code;
|
638
|
+
event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode) });
|
639
|
+
}
|
640
|
+
else {
|
641
|
+
const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
|
642
|
+
const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
|
643
|
+
const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
|
644
|
+
if (ciphertext && iv) {
|
645
|
+
event.media = { ciphertext, iv };
|
646
|
+
}
|
647
|
+
else {
|
648
|
+
event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
|
649
|
+
}
|
650
|
+
}
|
651
|
+
return event;
|
652
|
+
};
|
653
|
+
exports.decodeMediaRetryNode = decodeMediaRetryNode;
|
654
|
+
const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
|
655
|
+
const retryKey = await getMediaRetryKey(mediaKey);
|
656
|
+
const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
|
657
|
+
return WAProto_1.proto.MediaRetryNotification.decode(plaintext);
|
658
|
+
};
|
659
|
+
exports.decryptMediaRetryData = decryptMediaRetryData;
|
660
|
+
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
|
661
|
+
exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
|
662
|
+
const MEDIA_RETRY_STATUS_MAP = {
|
663
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
664
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
665
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
666
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
|
667
|
+
};
|