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