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