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