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