@badzz88/baileys 8.5.5 → 8.5.6
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.md +2 -2
- package/WAProto/WAProto.proto +1256 -75
- package/WAProto/fix-imports.js +69 -79
- package/WAProto/index.d.ts +15254 -71491
- package/WAProto/index.js +19816 -126438
- package/engine-requirements.js +3 -4
- package/package.json +4 -4
- package/src/Defaults/index.js +186 -0
- package/src/Signal/Group/ciphertext-message.js +15 -0
- package/src/Signal/Group/group-session-builder.js +86 -0
- package/src/Signal/Group/group_cipher.js +82 -0
- package/src/Signal/Group/index.js +140 -0
- package/src/Signal/Group/keyhelper.js +77 -0
- package/src/Signal/Group/sender-chain-key.js +29 -0
- package/src/Signal/Group/sender-key-distribution-message.js +66 -0
- package/src/Signal/Group/sender-key-message.js +69 -0
- package/src/Signal/Group/sender-key-name.js +51 -0
- package/src/Signal/Group/sender-key-record.js +44 -0
- package/src/Signal/Group/sender-key-state.js +87 -0
- package/src/Signal/Group/sender-message-key.js +29 -0
- package/src/Signal/libsignal.js +455 -0
- package/src/Signal/lid-mapping.js +273 -0
- package/src/Socket/Client/index.js +31 -0
- package/src/Socket/Client/types.js +13 -0
- package/src/Socket/Client/websocket.js +61 -0
- package/src/Socket/aigroups.js +221 -0
- package/src/Socket/business.js +411 -0
- package/src/Socket/chats.js +1449 -0
- package/src/Socket/communities.js +463 -0
- package/src/Socket/graphql.js +523 -0
- package/src/Socket/groups.js +516 -0
- package/src/Socket/index.js +31 -0
- package/src/Socket/interactive-handler.js +527 -0
- package/src/Socket/interop.js +339 -0
- package/{lib → src}/Socket/luxu.js +82 -120
- package/src/Socket/managed-account.js +98 -0
- package/src/Socket/messages-recv.js +2685 -0
- package/src/Socket/messages-send.js +2047 -0
- package/src/Socket/mex.js +57 -0
- package/src/Socket/newsletter.js +455 -0
- package/src/Socket/privacy.js +125 -0
- package/src/Socket/registration.js +236 -0
- package/src/Socket/socket.js +983 -0
- package/src/Socket/text-router.js +65 -0
- package/src/Socket/username.js +130 -0
- package/src/Store/index.js +33 -0
- package/{lib → src}/Store/keyed-db.js +21 -11
- package/src/Store/make-cache-manager-store.js +84 -0
- package/src/Store/make-in-memory-store.js +551 -0
- package/src/Store/make-ordered-dictionary.js +81 -0
- package/src/Store/object-repository.js +26 -0
- package/src/Types/Auth.js +31 -0
- package/src/Types/Bussines.js +2 -0
- package/src/Types/Call.js +2 -0
- package/src/Types/Chat.js +4 -0
- package/src/Types/Contact.js +2 -0
- package/src/Types/Events.js +2 -0
- package/src/Types/GroupMetadata.js +2 -0
- package/src/Types/Label.js +26 -0
- package/src/Types/LabelAssociation.js +8 -0
- package/src/Types/Message.js +93 -0
- package/src/Types/Mex.js +112 -0
- package/src/Types/Newsletter.js +109 -0
- package/src/Types/Product.js +2 -0
- package/src/Types/Signal.js +2 -0
- package/src/Types/Socket.js +2 -0
- package/src/Types/State.js +62 -0
- package/src/Types/USync.js +2 -0
- package/src/Types/index.js +56 -0
- package/src/Utils/auth-utils.js +254 -0
- package/src/Utils/browser-utils.js +112 -0
- package/src/Utils/business.js +240 -0
- package/src/Utils/chat-utils.js +1230 -0
- package/src/Utils/command-loader.d.ts +27 -0
- package/src/Utils/command-loader.js +89 -0
- package/src/Utils/companion-reg-client-utils.js +40 -0
- package/src/Utils/consumer-application.js +105 -0
- package/src/Utils/crypto.js +118 -0
- package/src/Utils/curve25519-js.js +242 -0
- package/src/Utils/decode-wa-message.js +529 -0
- package/src/Utils/event-buffer.js +580 -0
- package/src/Utils/generics.js +483 -0
- package/src/Utils/group-history.js +44 -0
- package/src/Utils/history.js +232 -0
- package/src/Utils/identity-change-handler.js +52 -0
- package/src/Utils/index.js +58 -0
- package/src/Utils/jid-display-normalization.js +195 -0
- package/src/Utils/link-preview.js +135 -0
- package/src/Utils/logger.js +8 -0
- package/src/Utils/lt-hash.js +25 -0
- package/src/Utils/make-mutex.js +36 -0
- package/src/Utils/message-composer.js +471 -0
- package/src/Utils/message-retry-manager.js +217 -0
- package/src/Utils/messages-media.js +843 -0
- package/src/Utils/messages.js +2817 -0
- package/src/Utils/meta-ai-msmsg.js +222 -0
- package/src/Utils/native-bridge.js +68 -0
- package/src/Utils/noise-handler.js +169 -0
- package/src/Utils/offline-node-processor.js +34 -0
- package/src/Utils/pre-key-manager.js +90 -0
- package/src/Utils/process-message.js +950 -0
- package/src/Utils/reporting-utils.js +261 -0
- package/src/Utils/session-pool.d.ts +14 -0
- package/src/Utils/session-pool.js +70 -0
- package/src/Utils/signal.js +217 -0
- package/src/Utils/stanza-ack.js +30 -0
- package/src/Utils/sticker.d.ts +13 -0
- package/src/Utils/sticker.js +123 -0
- package/src/Utils/sync-action-utils.js +45 -0
- package/src/Utils/tc-token-utils.js +158 -0
- package/src/Utils/use-multi-file-auth-state.js +111 -0
- package/src/Utils/validate-connection.js +209 -0
- package/src/Utils/view-once-cache.d.ts +12 -0
- package/src/Utils/view-once-cache.js +63 -0
- package/src/Utils/voip-rekey.js +22 -0
- package/src/WABinary/constants.js +1304 -0
- package/src/WABinary/decode.js +342 -0
- package/{lib → src}/WABinary/encode.js +9 -12
- package/src/WABinary/generic-utils.js +238 -0
- package/src/WABinary/index.js +34 -0
- package/src/WABinary/jid-utils.js +351 -0
- package/src/WABinary/types.js +2 -0
- package/src/WAM/BinaryInfo.js +13 -0
- package/src/WAM/constants.js +39484 -0
- package/src/WAM/encode.js +149 -0
- package/src/WAM/index.js +32 -0
- package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
- package/src/WAUSync/Protocols/USyncBusinessProtocol.js +44 -0
- package/src/WAUSync/Protocols/USyncContactProtocol.js +55 -0
- package/src/WAUSync/Protocols/USyncDeviceProtocol.js +55 -0
- package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
- package/src/WAUSync/Protocols/USyncFeatureProtocol.js +54 -0
- package/src/WAUSync/Protocols/USyncLIDProtocol.js +32 -0
- package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +473 -0
- package/src/WAUSync/Protocols/USyncPictureProtocol.js +34 -0
- package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
- package/src/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
- package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
- package/src/WAUSync/Protocols/index.js +40 -0
- package/src/WAUSync/USyncQuery.js +126 -0
- package/src/WAUSync/USyncUser.js +50 -0
- package/src/WAUSync/index.js +32 -0
- package/src/antiban.js +4152 -0
- package/{lib → src}/index.js +51 -49
- package/lib/Defaults/index.js +0 -187
- package/lib/Signal/Group/ciphertext-message.js +0 -15
- package/lib/Signal/Group/group-session-builder.js +0 -92
- package/lib/Signal/Group/group_cipher.js +0 -89
- package/lib/Signal/Group/index.js +0 -136
- package/lib/Signal/Group/keyhelper.js +0 -73
- package/lib/Signal/Group/sender-chain-key.js +0 -32
- package/lib/Signal/Group/sender-key-distribution-message.js +0 -66
- package/lib/Signal/Group/sender-key-message.js +0 -69
- package/lib/Signal/Group/sender-key-name.js +0 -50
- package/lib/Signal/Group/sender-key-record.js +0 -44
- package/lib/Signal/Group/sender-key-state.js +0 -97
- package/lib/Signal/Group/sender-message-key.js +0 -30
- package/lib/Signal/libsignal.js +0 -459
- package/lib/Signal/lid-mapping.js +0 -260
- package/lib/Socket/Client/index.js +0 -30
- package/lib/Socket/Client/types.js +0 -13
- package/lib/Socket/Client/websocket.js +0 -62
- package/lib/Socket/aigroups.js +0 -240
- package/lib/Socket/business.js +0 -422
- package/lib/Socket/chats.js +0 -1816
- package/lib/Socket/communities.js +0 -549
- package/lib/Socket/graphql.js +0 -656
- package/lib/Socket/groups.js +0 -764
- package/lib/Socket/index.js +0 -39
- package/lib/Socket/interactive-handler.js +0 -522
- package/lib/Socket/interop.js +0 -549
- package/lib/Socket/managed-account.js +0 -183
- package/lib/Socket/messages-recv.js +0 -2442
- package/lib/Socket/messages-send.js +0 -1853
- package/lib/Socket/mex.js +0 -60
- package/lib/Socket/newsletter.js +0 -818
- package/lib/Socket/privacy.js +0 -449
- package/lib/Socket/registration.js +0 -427
- package/lib/Socket/socket.js +0 -1092
- package/lib/Socket/text-router.js +0 -83
- package/lib/Socket/username.js +0 -243
- package/lib/Store/index.js +0 -36
- package/lib/Store/make-cache-manager-store.js +0 -90
- package/lib/Store/make-in-memory-store.js +0 -604
- package/lib/Store/make-ordered-dictionary.js +0 -81
- package/lib/Store/object-repository.js +0 -29
- package/lib/Types/Auth.js +0 -38
- package/lib/Types/Bussines.js +0 -2
- package/lib/Types/Call.js +0 -2
- package/lib/Types/Chat.js +0 -4
- package/lib/Types/Contact.js +0 -2
- package/lib/Types/Events.js +0 -2
- package/lib/Types/GroupMetadata.js +0 -2
- package/lib/Types/Label.js +0 -27
- package/lib/Types/LabelAssociation.js +0 -9
- package/lib/Types/Message.js +0 -95
- package/lib/Types/Mex.js +0 -112
- package/lib/Types/Newsletter.js +0 -121
- package/lib/Types/Product.js +0 -2
- package/lib/Types/Signal.js +0 -2
- package/lib/Types/Socket.js +0 -2
- package/lib/Types/State.js +0 -70
- package/lib/Types/USync.js +0 -2
- package/lib/Types/index.js +0 -55
- package/lib/Utils/auth-utils.js +0 -306
- package/lib/Utils/browser-utils.js +0 -114
- package/lib/Utils/business.js +0 -247
- package/lib/Utils/chat-utils.js +0 -1208
- package/lib/Utils/command-loader.d.ts +0 -31
- package/lib/Utils/command-loader.js +0 -100
- package/lib/Utils/companion-reg-client-utils.js +0 -42
- package/lib/Utils/consumer-application.js +0 -107
- package/lib/Utils/crypto.js +0 -155
- package/lib/Utils/curve25519-js.js +0 -275
- package/lib/Utils/decode-wa-message.js +0 -560
- package/lib/Utils/event-buffer.js +0 -607
- package/lib/Utils/generics.js +0 -563
- package/lib/Utils/group-history.js +0 -60
- package/lib/Utils/history.js +0 -244
- package/lib/Utils/identity-change-handler.js +0 -52
- package/lib/Utils/index.js +0 -57
- package/lib/Utils/jid-display-normalization.js +0 -218
- package/lib/Utils/link-preview.js +0 -143
- package/lib/Utils/logger.js +0 -9
- package/lib/Utils/lt-hash.js +0 -39
- package/lib/Utils/make-mutex.js +0 -36
- package/lib/Utils/message-composer.js +0 -479
- package/lib/Utils/message-inspect.js +0 -393
- package/lib/Utils/message-retry-manager.js +0 -270
- package/lib/Utils/messages-media.js +0 -896
- package/lib/Utils/messages.js +0 -2904
- package/lib/Utils/meta-ai-msmsg.js +0 -262
- package/lib/Utils/native-bridge.js +0 -82
- package/lib/Utils/noise-handler.js +0 -196
- package/lib/Utils/offline-node-processor.js +0 -42
- package/lib/Utils/pre-key-manager.js +0 -107
- package/lib/Utils/process-message.js +0 -1048
- package/lib/Utils/reporting-utils.js +0 -262
- package/lib/Utils/session-pool.d.ts +0 -16
- package/lib/Utils/session-pool.js +0 -94
- package/lib/Utils/signal.js +0 -224
- package/lib/Utils/stanza-ack.js +0 -40
- package/lib/Utils/sticker.d.ts +0 -17
- package/lib/Utils/sticker.js +0 -145
- package/lib/Utils/sync-action-utils.js +0 -54
- package/lib/Utils/tc-token-utils.js +0 -161
- package/lib/Utils/use-multi-file-auth-state.js +0 -121
- package/lib/Utils/validate-connection.js +0 -219
- package/lib/Utils/view-once-cache.d.ts +0 -9
- package/lib/Utils/view-once-cache.js +0 -79
- package/lib/Utils/voip-rekey.js +0 -22
- package/lib/WABinary/constants.js +0 -1304
- package/lib/WABinary/decode.js +0 -343
- package/lib/WABinary/generic-utils.js +0 -240
- package/lib/WABinary/index.js +0 -33
- package/lib/WABinary/jid-utils.js +0 -361
- package/lib/WABinary/types.js +0 -2
- package/lib/WAM/BinaryInfo.js +0 -13
- package/lib/WAM/constants.js +0 -39486
- package/lib/WAM/encode.js +0 -142
- package/lib/WAM/index.js +0 -31
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -55
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +0 -43
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -54
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +0 -59
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -31
- package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -865
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +0 -32
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -39
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -27
- package/lib/WAUSync/Protocols/index.js +0 -39
- package/lib/WAUSync/USyncBackoff.js +0 -26
- package/lib/WAUSync/USyncQuery.js +0 -133
- package/lib/WAUSync/USyncUser.js +0 -50
- package/lib/WAUSync/index.js +0 -31
- package/lib/antiban.js +0 -4637
- /package/{lib → src}/Defaults/phonenumber-mcc.json +0 -0
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
var __createBinding = (this && this.__createBinding) ||
|
|
3
|
+
(Object.create
|
|
4
|
+
? function (o, m, k, k2) {
|
|
5
|
+
if (k2 === undefined)
|
|
6
|
+
k2 = k;
|
|
7
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
8
|
+
if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
9
|
+
desc = {
|
|
10
|
+
enumerable: true,
|
|
11
|
+
get: function () {
|
|
12
|
+
return m[k];
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
Object.defineProperty(o, k2, desc);
|
|
17
|
+
}
|
|
18
|
+
: function (o, m, k, k2) {
|
|
19
|
+
if (k2 === undefined)
|
|
20
|
+
k2 = k;
|
|
21
|
+
o[k2] = m[k];
|
|
22
|
+
});
|
|
23
|
+
var __setModuleDefault = (this && this.__setModuleDefault) ||
|
|
24
|
+
(Object.create
|
|
25
|
+
? function (o, v) {
|
|
26
|
+
Object.defineProperty(o, 'default', { enumerable: true, value: v });
|
|
27
|
+
}
|
|
28
|
+
: function (o, v) {
|
|
29
|
+
o['default'] = v;
|
|
30
|
+
});
|
|
31
|
+
var __importStar = (this && this.__importStar) ||
|
|
32
|
+
(function () {
|
|
33
|
+
var ownKeys = function (o) {
|
|
34
|
+
ownKeys =
|
|
35
|
+
Object.getOwnPropertyNames ||
|
|
36
|
+
function (o) {
|
|
37
|
+
var ar = [];
|
|
38
|
+
for (var k in o)
|
|
39
|
+
if (Object.prototype.hasOwnProperty.call(o, k))
|
|
40
|
+
ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule)
|
|
47
|
+
return mod;
|
|
48
|
+
var result = {};
|
|
49
|
+
if (mod != null)
|
|
50
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++)
|
|
51
|
+
if (k[i] !== 'default')
|
|
52
|
+
__createBinding(result, mod, k[i]);
|
|
53
|
+
__setModuleDefault(result, mod);
|
|
54
|
+
return result;
|
|
55
|
+
};
|
|
56
|
+
})();
|
|
57
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
58
|
+
exports.getStatusCodeForMediaRetry =
|
|
59
|
+
exports.decryptMediaRetryData =
|
|
60
|
+
exports.decodeMediaRetryNode =
|
|
61
|
+
exports.encryptMediaRetryRequest =
|
|
62
|
+
exports.getWAUploadToServer =
|
|
63
|
+
exports.uploadWithNodeHttp =
|
|
64
|
+
exports.downloadEncryptedContent =
|
|
65
|
+
exports.downloadContentFromMessage =
|
|
66
|
+
exports.getUrlFromDirectPath =
|
|
67
|
+
exports.encryptedStream =
|
|
68
|
+
exports.getHttpStream =
|
|
69
|
+
exports.getStream =
|
|
70
|
+
exports.toBuffer =
|
|
71
|
+
exports.toReadable =
|
|
72
|
+
exports.mediaMessageSHA256B64 =
|
|
73
|
+
exports.generateProfilePicture =
|
|
74
|
+
exports.encodeBase64EncodedStringForUpload =
|
|
75
|
+
exports.extractImageThumb =
|
|
76
|
+
exports.getRawMediaUploadData =
|
|
77
|
+
exports.hkdfInfoKey =
|
|
78
|
+
void 0;
|
|
79
|
+
exports.getMediaKeys = getMediaKeys;
|
|
80
|
+
exports.getAudioDuration = getAudioDuration;
|
|
81
|
+
exports.getAudioWaveform = getAudioWaveform;
|
|
82
|
+
exports.generateThumbnail = generateThumbnail;
|
|
83
|
+
exports.extensionForMediaMessage = extensionForMediaMessage;
|
|
84
|
+
const boom_1 = require('@hapi/boom');
|
|
85
|
+
const child_process_1 = require('child_process');
|
|
86
|
+
const Crypto = __importStar(require('crypto'));
|
|
87
|
+
const events_1 = require('events');
|
|
88
|
+
const fs_1 = require('fs');
|
|
89
|
+
const os_1 = require('os');
|
|
90
|
+
const path_1 = require('path');
|
|
91
|
+
const stream_1 = require('stream');
|
|
92
|
+
const url_1 = require('url');
|
|
93
|
+
const index_js_1 = require('../../WAProto/index.js');
|
|
94
|
+
const Defaults_1 = require('../Defaults');
|
|
95
|
+
const WABinary_1 = require('../WABinary');
|
|
96
|
+
const crypto_1 = require('./crypto');
|
|
97
|
+
const generics_1 = require('./generics');
|
|
98
|
+
const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
|
|
99
|
+
const getImageProcessingLibrary = async () => {
|
|
100
|
+
const [jimp, sharp] = await Promise.all([
|
|
101
|
+
Promise.resolve()
|
|
102
|
+
.then(() => __importStar(require('jimp')))
|
|
103
|
+
.catch(() => { }),
|
|
104
|
+
Promise.resolve()
|
|
105
|
+
.then(() => __importStar(require('sharp')))
|
|
106
|
+
.catch(() => { })
|
|
107
|
+
]);
|
|
108
|
+
if (sharp) {
|
|
109
|
+
return { sharp };
|
|
110
|
+
}
|
|
111
|
+
if (jimp) {
|
|
112
|
+
return { jimp };
|
|
113
|
+
}
|
|
114
|
+
throw new boom_1.Boom('No image processing library available');
|
|
115
|
+
};
|
|
116
|
+
const hkdfInfoKey = type => {
|
|
117
|
+
const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
|
|
118
|
+
return `WhatsApp ${hkdfInfo} Keys`;
|
|
119
|
+
};
|
|
120
|
+
exports.hkdfInfoKey = hkdfInfoKey;
|
|
121
|
+
const getRawMediaUploadData = async (media, mediaType, logger) => {
|
|
122
|
+
const { stream } = await (0, exports.getStream)(media);
|
|
123
|
+
logger?.debug('got stream for raw upload');
|
|
124
|
+
const hasher = Crypto.createHash('sha256');
|
|
125
|
+
const filePath = (0, path_1.join)((0, os_1.tmpdir)(), mediaType + (0, generics_1.generateMessageIDV2)());
|
|
126
|
+
const fileWriteStream = (0, fs_1.createWriteStream)(filePath);
|
|
127
|
+
let fileLength = 0;
|
|
128
|
+
try {
|
|
129
|
+
for await (const data of stream) {
|
|
130
|
+
fileLength += data.length;
|
|
131
|
+
hasher.update(data);
|
|
132
|
+
if (!fileWriteStream.write(data)) {
|
|
133
|
+
await (0, events_1.once)(fileWriteStream, 'drain');
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
fileWriteStream.end();
|
|
137
|
+
await (0, events_1.once)(fileWriteStream, 'finish');
|
|
138
|
+
stream.destroy();
|
|
139
|
+
const fileSha256 = hasher.digest();
|
|
140
|
+
logger?.debug('hashed data for raw upload');
|
|
141
|
+
return {
|
|
142
|
+
filePath: filePath,
|
|
143
|
+
fileSha256,
|
|
144
|
+
fileLength
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
fileWriteStream.destroy();
|
|
149
|
+
stream.destroy();
|
|
150
|
+
try {
|
|
151
|
+
await fs_1.promises.unlink(filePath);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
}
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
exports.getRawMediaUploadData = getRawMediaUploadData;
|
|
159
|
+
async function getMediaKeys(buffer, mediaType) {
|
|
160
|
+
if (!buffer) {
|
|
161
|
+
throw new boom_1.Boom('Cannot derive from empty media key');
|
|
162
|
+
}
|
|
163
|
+
if (typeof buffer === 'string') {
|
|
164
|
+
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
|
|
165
|
+
}
|
|
166
|
+
const expandedMediaKey = (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
|
|
167
|
+
return {
|
|
168
|
+
iv: expandedMediaKey.slice(0, 16),
|
|
169
|
+
cipherKey: expandedMediaKey.slice(16, 48),
|
|
170
|
+
macKey: expandedMediaKey.slice(48, 80)
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
|
|
174
|
+
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
|
|
175
|
+
(0, child_process_1.exec)(cmd, err => {
|
|
176
|
+
if (err) {
|
|
177
|
+
reject(err);
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
resolve();
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
const extractImageThumb = async (bufferOrFilePath, width = 32) => {
|
|
185
|
+
if (bufferOrFilePath instanceof stream_1.Readable) {
|
|
186
|
+
bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
|
|
187
|
+
}
|
|
188
|
+
const lib = await getImageProcessingLibrary();
|
|
189
|
+
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
190
|
+
const img = lib.sharp.default(bufferOrFilePath);
|
|
191
|
+
const dimensions = await img.metadata();
|
|
192
|
+
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
|
|
193
|
+
return {
|
|
194
|
+
buffer,
|
|
195
|
+
original: {
|
|
196
|
+
width: dimensions.width,
|
|
197
|
+
height: dimensions.height
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
|
|
202
|
+
const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
|
|
203
|
+
const dimensions = {
|
|
204
|
+
width: jimp.width,
|
|
205
|
+
height: jimp.height
|
|
206
|
+
};
|
|
207
|
+
const buffer = await jimp
|
|
208
|
+
.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
|
|
209
|
+
.getBuffer('image/jpeg', { quality: 50 });
|
|
210
|
+
return {
|
|
211
|
+
buffer,
|
|
212
|
+
original: dimensions
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
throw new boom_1.Boom('No image processing library available');
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
exports.extractImageThumb = extractImageThumb;
|
|
220
|
+
const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
|
|
221
|
+
exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
|
|
222
|
+
const generateProfilePicture = async (mediaUpload, dimensions) => {
|
|
223
|
+
let buffer;
|
|
224
|
+
const { width: w = 640, height: h = 640 } = dimensions || {};
|
|
225
|
+
if (Buffer.isBuffer(mediaUpload)) {
|
|
226
|
+
buffer = mediaUpload;
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
const { stream } = await (0, exports.getStream)(mediaUpload);
|
|
230
|
+
buffer = await (0, exports.toBuffer)(stream);
|
|
231
|
+
}
|
|
232
|
+
const lib = await getImageProcessingLibrary();
|
|
233
|
+
let img;
|
|
234
|
+
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
235
|
+
img = lib.sharp
|
|
236
|
+
.default(buffer)
|
|
237
|
+
.resize(w, h)
|
|
238
|
+
.jpeg({
|
|
239
|
+
quality: 50
|
|
240
|
+
})
|
|
241
|
+
.toBuffer();
|
|
242
|
+
}
|
|
243
|
+
else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
|
|
244
|
+
const jimp = await lib.jimp.Jimp.read(buffer);
|
|
245
|
+
const min = Math.min(jimp.width, jimp.height);
|
|
246
|
+
const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
|
|
247
|
+
img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
throw new boom_1.Boom('No image processing library available');
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
img: await img
|
|
254
|
+
};
|
|
255
|
+
};
|
|
256
|
+
exports.generateProfilePicture = generateProfilePicture;
|
|
257
|
+
const mediaMessageSHA256B64 = message => {
|
|
258
|
+
const media = Object.values(message)[0];
|
|
259
|
+
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
|
|
260
|
+
};
|
|
261
|
+
exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
|
|
262
|
+
async function getAudioDuration(buffer) {
|
|
263
|
+
const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
|
|
264
|
+
let metadata;
|
|
265
|
+
const options = {
|
|
266
|
+
duration: true
|
|
267
|
+
};
|
|
268
|
+
if (Buffer.isBuffer(buffer)) {
|
|
269
|
+
metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
|
|
270
|
+
}
|
|
271
|
+
else if (typeof buffer === 'string') {
|
|
272
|
+
metadata = await musicMetadata.parseFile(buffer, options);
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
metadata = await musicMetadata.parseStream(buffer, undefined, options);
|
|
276
|
+
}
|
|
277
|
+
return metadata.format.duration;
|
|
278
|
+
}
|
|
279
|
+
async function getAudioWaveform(buffer, logger) {
|
|
280
|
+
try {
|
|
281
|
+
const { default: decoder } = await Promise.resolve().then(() => __importStar(require('audio-decode')));
|
|
282
|
+
let audioData;
|
|
283
|
+
if (Buffer.isBuffer(buffer)) {
|
|
284
|
+
audioData = buffer;
|
|
285
|
+
}
|
|
286
|
+
else if (typeof buffer === 'string') {
|
|
287
|
+
const rStream = (0, fs_1.createReadStream)(buffer);
|
|
288
|
+
audioData = await (0, exports.toBuffer)(rStream);
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
audioData = await (0, exports.toBuffer)(buffer);
|
|
292
|
+
}
|
|
293
|
+
const audioBuffer = await decoder(audioData);
|
|
294
|
+
const rawData = audioBuffer.getChannelData(0);
|
|
295
|
+
const samples = 64;
|
|
296
|
+
const blockSize = Math.floor(rawData.length / samples);
|
|
297
|
+
const filteredData = [];
|
|
298
|
+
for (let i = 0; i < samples; i++) {
|
|
299
|
+
const blockStart = blockSize * i;
|
|
300
|
+
let sum = 0;
|
|
301
|
+
for (let j = 0; j < blockSize; j++) {
|
|
302
|
+
sum = sum + Math.abs(rawData[blockStart + j]);
|
|
303
|
+
}
|
|
304
|
+
filteredData.push(sum / blockSize);
|
|
305
|
+
}
|
|
306
|
+
const multiplier = Math.pow(Math.max(...filteredData), -1);
|
|
307
|
+
const normalizedData = filteredData.map(n => n * multiplier);
|
|
308
|
+
const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
|
|
309
|
+
return waveform;
|
|
310
|
+
}
|
|
311
|
+
catch (e) {
|
|
312
|
+
logger?.debug('Failed to generate waveform: ' + e);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const toReadable = buffer => {
|
|
316
|
+
const readable = new stream_1.Readable({ read: () => { } });
|
|
317
|
+
readable.push(buffer);
|
|
318
|
+
readable.push(null);
|
|
319
|
+
return readable;
|
|
320
|
+
};
|
|
321
|
+
exports.toReadable = toReadable;
|
|
322
|
+
const toBuffer = async (stream) => {
|
|
323
|
+
const chunks = [];
|
|
324
|
+
for await (const chunk of stream) {
|
|
325
|
+
chunks.push(chunk);
|
|
326
|
+
}
|
|
327
|
+
stream.destroy();
|
|
328
|
+
return Buffer.concat(chunks);
|
|
329
|
+
};
|
|
330
|
+
exports.toBuffer = toBuffer;
|
|
331
|
+
const getStream = async (item, opts) => {
|
|
332
|
+
if (Buffer.isBuffer(item)) {
|
|
333
|
+
return { stream: (0, exports.toReadable)(item), type: 'buffer' };
|
|
334
|
+
}
|
|
335
|
+
if ('stream' in item) {
|
|
336
|
+
return { stream: item.stream, type: 'readable' };
|
|
337
|
+
}
|
|
338
|
+
const urlStr = item.url.toString();
|
|
339
|
+
if (urlStr.startsWith('data:')) {
|
|
340
|
+
const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
|
|
341
|
+
return { stream: (0, exports.toReadable)(buffer), type: 'buffer' };
|
|
342
|
+
}
|
|
343
|
+
if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
|
|
344
|
+
return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
|
|
345
|
+
}
|
|
346
|
+
return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
|
|
347
|
+
};
|
|
348
|
+
exports.getStream = getStream;
|
|
349
|
+
async function generateThumbnail(file, mediaType, options) {
|
|
350
|
+
let thumbnail;
|
|
351
|
+
let originalImageDimensions;
|
|
352
|
+
if (mediaType === 'image') {
|
|
353
|
+
const { buffer, original } = await (0, exports.extractImageThumb)(file);
|
|
354
|
+
thumbnail = buffer.toString('base64');
|
|
355
|
+
if (original.width && original.height) {
|
|
356
|
+
originalImageDimensions = {
|
|
357
|
+
width: original.width,
|
|
358
|
+
height: original.height
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
else if (mediaType === 'video') {
|
|
363
|
+
const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageIDV2)() + '.jpg');
|
|
364
|
+
try {
|
|
365
|
+
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
|
|
366
|
+
const buff = await fs_1.promises.readFile(imgFilename);
|
|
367
|
+
thumbnail = buff.toString('base64');
|
|
368
|
+
await fs_1.promises.unlink(imgFilename);
|
|
369
|
+
}
|
|
370
|
+
catch (err) {
|
|
371
|
+
options.logger?.debug('could not generate video thumb: ' + err);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return {
|
|
375
|
+
thumbnail,
|
|
376
|
+
originalImageDimensions
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
const getHttpStream = async (url, options = {}) => {
|
|
380
|
+
const response = await fetch(url.toString(), {
|
|
381
|
+
dispatcher: options.dispatcher,
|
|
382
|
+
method: 'GET',
|
|
383
|
+
headers: options.headers
|
|
384
|
+
});
|
|
385
|
+
if (!response.ok) {
|
|
386
|
+
throw new boom_1.Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
|
|
387
|
+
}
|
|
388
|
+
return response.body instanceof stream_1.Readable ? response.body : stream_1.Readable.fromWeb(response.body);
|
|
389
|
+
};
|
|
390
|
+
exports.getHttpStream = getHttpStream;
|
|
391
|
+
const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
392
|
+
const { stream, type } = await (0, exports.getStream)(media, opts);
|
|
393
|
+
logger?.debug('fetched media stream');
|
|
394
|
+
const mediaKey = Crypto.randomBytes(32);
|
|
395
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
|
|
396
|
+
const encFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-enc');
|
|
397
|
+
const encFileWriteStream = (0, fs_1.createWriteStream)(encFilePath);
|
|
398
|
+
let originalFileStream;
|
|
399
|
+
let originalFilePath;
|
|
400
|
+
if (saveOriginalFileIfRequired) {
|
|
401
|
+
originalFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-original');
|
|
402
|
+
originalFileStream = (0, fs_1.createWriteStream)(originalFilePath);
|
|
403
|
+
}
|
|
404
|
+
let fileLength = 0;
|
|
405
|
+
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
|
|
406
|
+
const hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
|
407
|
+
const sha256Plain = Crypto.createHash('sha256');
|
|
408
|
+
const sha256Enc = Crypto.createHash('sha256');
|
|
409
|
+
const onChunk = async (buff) => {
|
|
410
|
+
sha256Enc.update(buff);
|
|
411
|
+
hmac.update(buff);
|
|
412
|
+
if (!encFileWriteStream.write(buff)) {
|
|
413
|
+
await (0, events_1.once)(encFileWriteStream, 'drain');
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
try {
|
|
417
|
+
for await (const data of stream) {
|
|
418
|
+
fileLength += data.length;
|
|
419
|
+
if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
|
|
420
|
+
throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
|
|
421
|
+
data: { media, type }
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
if (originalFileStream) {
|
|
425
|
+
if (!originalFileStream.write(data)) {
|
|
426
|
+
await (0, events_1.once)(originalFileStream, 'drain');
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
sha256Plain.update(data);
|
|
430
|
+
await onChunk(aes.update(data));
|
|
431
|
+
}
|
|
432
|
+
await onChunk(aes.final());
|
|
433
|
+
const mac = hmac.digest().slice(0, 10);
|
|
434
|
+
sha256Enc.update(mac);
|
|
435
|
+
const fileSha256 = sha256Plain.digest();
|
|
436
|
+
const fileEncSha256 = sha256Enc.digest();
|
|
437
|
+
encFileWriteStream.write(mac);
|
|
438
|
+
const encFinishPromise = (0, events_1.once)(encFileWriteStream, 'finish');
|
|
439
|
+
const originalFinishPromise = originalFileStream
|
|
440
|
+
? (0, events_1.once)(originalFileStream, 'finish')
|
|
441
|
+
: Promise.resolve();
|
|
442
|
+
encFileWriteStream.end();
|
|
443
|
+
originalFileStream?.end?.();
|
|
444
|
+
stream.destroy();
|
|
445
|
+
await encFinishPromise;
|
|
446
|
+
await originalFinishPromise;
|
|
447
|
+
logger?.debug('encrypted data successfully');
|
|
448
|
+
return {
|
|
449
|
+
mediaKey,
|
|
450
|
+
originalFilePath,
|
|
451
|
+
encFilePath,
|
|
452
|
+
mac,
|
|
453
|
+
fileEncSha256,
|
|
454
|
+
fileSha256,
|
|
455
|
+
fileLength
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
encFileWriteStream.destroy();
|
|
460
|
+
originalFileStream?.destroy?.();
|
|
461
|
+
aes.destroy();
|
|
462
|
+
hmac.destroy();
|
|
463
|
+
sha256Plain.destroy();
|
|
464
|
+
sha256Enc.destroy();
|
|
465
|
+
stream.destroy();
|
|
466
|
+
try {
|
|
467
|
+
await fs_1.promises.unlink(encFilePath);
|
|
468
|
+
if (originalFilePath) {
|
|
469
|
+
await fs_1.promises.unlink(originalFilePath);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
catch (err) {
|
|
473
|
+
logger?.error({ err }, 'failed deleting tmp files');
|
|
474
|
+
}
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
exports.encryptedStream = encryptedStream;
|
|
479
|
+
const DEF_HOST = 'mmg.whatsapp.net';
|
|
480
|
+
const AES_CHUNK_SIZE = 16;
|
|
481
|
+
const toSmallestChunkSize = num => {
|
|
482
|
+
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
|
|
483
|
+
};
|
|
484
|
+
const getUrlFromDirectPath = directPath => `https://${DEF_HOST}${directPath}`;
|
|
485
|
+
exports.getUrlFromDirectPath = getUrlFromDirectPath;
|
|
486
|
+
const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
487
|
+
const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
|
|
488
|
+
const downloadUrl = isValidMediaUrl ? url : (0, exports.getUrlFromDirectPath)(directPath);
|
|
489
|
+
if (!downloadUrl) {
|
|
490
|
+
throw new boom_1.Boom('No valid media URL or directPath present in message', { statusCode: 400 });
|
|
491
|
+
}
|
|
492
|
+
const keys = await getMediaKeys(mediaKey, type);
|
|
493
|
+
return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
|
|
494
|
+
};
|
|
495
|
+
exports.downloadContentFromMessage = downloadContentFromMessage;
|
|
496
|
+
const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
497
|
+
let bytesFetched = 0;
|
|
498
|
+
let startChunk = 0;
|
|
499
|
+
let firstBlockIsIV = false;
|
|
500
|
+
if (startByte) {
|
|
501
|
+
const chunk = toSmallestChunkSize(startByte || 0);
|
|
502
|
+
if (chunk) {
|
|
503
|
+
startChunk = chunk - AES_CHUNK_SIZE;
|
|
504
|
+
bytesFetched = chunk;
|
|
505
|
+
firstBlockIsIV = true;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
|
|
509
|
+
const headersInit = options?.headers ? options.headers : undefined;
|
|
510
|
+
const headers = {
|
|
511
|
+
...(headersInit ? (Array.isArray(headersInit) ? Object.fromEntries(headersInit) : headersInit) : {}),
|
|
512
|
+
Origin: Defaults_1.DEFAULT_ORIGIN
|
|
513
|
+
};
|
|
514
|
+
if (startChunk || endChunk) {
|
|
515
|
+
headers.Range = `bytes=${startChunk}-`;
|
|
516
|
+
if (endChunk) {
|
|
517
|
+
headers.Range += endChunk;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const fetched = await (0, exports.getHttpStream)(downloadUrl, {
|
|
521
|
+
...(options || {}),
|
|
522
|
+
headers
|
|
523
|
+
});
|
|
524
|
+
let remainingBytes = Buffer.from([]);
|
|
525
|
+
let aes;
|
|
526
|
+
const pushBytes = (bytes, push) => {
|
|
527
|
+
if (startByte || endByte) {
|
|
528
|
+
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
|
|
529
|
+
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
|
|
530
|
+
push(bytes.slice(start, end));
|
|
531
|
+
bytesFetched += bytes.length;
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
push(bytes);
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
const output = new stream_1.Transform({
|
|
538
|
+
transform(chunk, _, callback) {
|
|
539
|
+
let data = Buffer.concat([remainingBytes, chunk]);
|
|
540
|
+
const decryptLength = toSmallestChunkSize(data.length);
|
|
541
|
+
remainingBytes = data.slice(decryptLength);
|
|
542
|
+
data = data.slice(0, decryptLength);
|
|
543
|
+
if (!aes) {
|
|
544
|
+
let ivValue = iv;
|
|
545
|
+
if (firstBlockIsIV) {
|
|
546
|
+
ivValue = data.slice(0, AES_CHUNK_SIZE);
|
|
547
|
+
data = data.slice(AES_CHUNK_SIZE);
|
|
548
|
+
}
|
|
549
|
+
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
|
|
550
|
+
if (endByte) {
|
|
551
|
+
aes.setAutoPadding(false);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
try {
|
|
555
|
+
pushBytes(aes.update(data), b => this.push(b));
|
|
556
|
+
callback();
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
callback(error);
|
|
560
|
+
}
|
|
561
|
+
},
|
|
562
|
+
final(callback) {
|
|
563
|
+
try {
|
|
564
|
+
pushBytes(aes.final(), b => this.push(b));
|
|
565
|
+
callback();
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
callback(error);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
});
|
|
572
|
+
return fetched.pipe(output, { end: true });
|
|
573
|
+
};
|
|
574
|
+
exports.downloadEncryptedContent = downloadEncryptedContent;
|
|
575
|
+
function extensionForMediaMessage(message) {
|
|
576
|
+
const getExtension = mimetype => mimetype.split(';')[0]?.split('/')[1];
|
|
577
|
+
const type = Object.keys(message)[0];
|
|
578
|
+
let extension;
|
|
579
|
+
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
|
|
580
|
+
extension = '.jpeg';
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
const messageContent = message[type];
|
|
584
|
+
extension = getExtension(messageContent.mimetype);
|
|
585
|
+
}
|
|
586
|
+
return extension;
|
|
587
|
+
}
|
|
588
|
+
const isNodeRuntime = () => {
|
|
589
|
+
return (typeof process !== 'undefined' &&
|
|
590
|
+
process.versions?.node !== null &&
|
|
591
|
+
typeof process.versions.bun === 'undefined' &&
|
|
592
|
+
typeof globalThis.Deno === 'undefined');
|
|
593
|
+
};
|
|
594
|
+
const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
|
|
595
|
+
if (redirectCount > 5) {
|
|
596
|
+
throw new Error('Too many redirects');
|
|
597
|
+
}
|
|
598
|
+
const parsedUrl = new url_1.URL(url);
|
|
599
|
+
const httpModule = parsedUrl.protocol === 'https:'
|
|
600
|
+
? await Promise.resolve().then(() => __importStar(require('https')))
|
|
601
|
+
: await Promise.resolve().then(() => __importStar(require('http')));
|
|
602
|
+
const fileStats = await fs_1.promises.stat(filePath);
|
|
603
|
+
const fileSize = fileStats.size;
|
|
604
|
+
return new Promise((resolve, reject) => {
|
|
605
|
+
const req = httpModule.request({
|
|
606
|
+
hostname: parsedUrl.hostname,
|
|
607
|
+
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
|
608
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
609
|
+
method: 'POST',
|
|
610
|
+
headers: {
|
|
611
|
+
...headers,
|
|
612
|
+
'Content-Length': fileSize
|
|
613
|
+
},
|
|
614
|
+
agent,
|
|
615
|
+
timeout: timeoutMs
|
|
616
|
+
}, res => {
|
|
617
|
+
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
618
|
+
res.resume();
|
|
619
|
+
const newUrl = new url_1.URL(res.headers.location, url).toString();
|
|
620
|
+
resolve((0, exports.uploadWithNodeHttp)({
|
|
621
|
+
url: newUrl,
|
|
622
|
+
filePath,
|
|
623
|
+
headers,
|
|
624
|
+
timeoutMs,
|
|
625
|
+
agent
|
|
626
|
+
}, redirectCount + 1));
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
let body = '';
|
|
630
|
+
res.on('data', chunk => (body += chunk));
|
|
631
|
+
res.on('end', () => {
|
|
632
|
+
try {
|
|
633
|
+
const parsed = JSON.parse(body);
|
|
634
|
+
if (parsed && typeof parsed === 'object') {
|
|
635
|
+
Object.defineProperty(parsed, '__statusCode', { value: res.statusCode, enumerable: false });
|
|
636
|
+
}
|
|
637
|
+
resolve(parsed);
|
|
638
|
+
}
|
|
639
|
+
catch {
|
|
640
|
+
resolve({ __statusCode: res.statusCode });
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
});
|
|
644
|
+
req.on('error', reject);
|
|
645
|
+
req.on('timeout', () => {
|
|
646
|
+
req.destroy();
|
|
647
|
+
reject(new Error('Upload timeout'));
|
|
648
|
+
});
|
|
649
|
+
const stream = (0, fs_1.createReadStream)(filePath);
|
|
650
|
+
stream.pipe(req);
|
|
651
|
+
stream.on('error', err => {
|
|
652
|
+
req.destroy();
|
|
653
|
+
reject(err);
|
|
654
|
+
});
|
|
655
|
+
});
|
|
656
|
+
};
|
|
657
|
+
exports.uploadWithNodeHttp = uploadWithNodeHttp;
|
|
658
|
+
const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
|
|
659
|
+
const nodeStream = (0, fs_1.createReadStream)(filePath);
|
|
660
|
+
const webStream = stream_1.Readable.toWeb(nodeStream);
|
|
661
|
+
const response = await fetch(url, {
|
|
662
|
+
dispatcher: agent,
|
|
663
|
+
method: 'POST',
|
|
664
|
+
body: webStream,
|
|
665
|
+
headers,
|
|
666
|
+
duplex: 'half',
|
|
667
|
+
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
668
|
+
});
|
|
669
|
+
try {
|
|
670
|
+
const parsed = await response.json();
|
|
671
|
+
if (parsed && typeof parsed === 'object') {
|
|
672
|
+
Object.defineProperty(parsed, '__statusCode', { value: response.status, enumerable: false });
|
|
673
|
+
}
|
|
674
|
+
return parsed;
|
|
675
|
+
}
|
|
676
|
+
catch {
|
|
677
|
+
return { __statusCode: response.status };
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
const uploadMedia = async (params, logger) => {
|
|
681
|
+
if (isNodeRuntime()) {
|
|
682
|
+
logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
|
|
683
|
+
return (0, exports.uploadWithNodeHttp)(params);
|
|
684
|
+
}
|
|
685
|
+
else {
|
|
686
|
+
logger?.debug('Using web-standard Fetch API for upload');
|
|
687
|
+
return uploadWithFetch(params);
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
691
|
+
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
|
692
|
+
let uploadInfo = await refreshMediaConn(false);
|
|
693
|
+
let urls;
|
|
694
|
+
const hosts = [...customUploadHosts, ...uploadInfo.hosts];
|
|
695
|
+
fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
|
|
696
|
+
const customHeaders = (() => {
|
|
697
|
+
const hdrs = options?.headers;
|
|
698
|
+
if (!hdrs)
|
|
699
|
+
return {};
|
|
700
|
+
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
|
|
701
|
+
})();
|
|
702
|
+
const headers = {
|
|
703
|
+
...customHeaders,
|
|
704
|
+
'Content-Type': 'application/octet-stream',
|
|
705
|
+
Origin: Defaults_1.DEFAULT_ORIGIN
|
|
706
|
+
};
|
|
707
|
+
for (const { hostname } of hosts) {
|
|
708
|
+
logger.debug(`uploading to "${hostname}"`);
|
|
709
|
+
const auth = encodeURIComponent(uploadInfo.auth);
|
|
710
|
+
const url = `https://${hostname}${Defaults_1.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
|
|
711
|
+
let result;
|
|
712
|
+
const maxRateLimitRetries = 3;
|
|
713
|
+
for (let attempt = 0; attempt <= maxRateLimitRetries; attempt++) {
|
|
714
|
+
try {
|
|
715
|
+
result = await uploadMedia({
|
|
716
|
+
url,
|
|
717
|
+
filePath,
|
|
718
|
+
headers,
|
|
719
|
+
timeoutMs,
|
|
720
|
+
agent: fetchAgent
|
|
721
|
+
}, logger);
|
|
722
|
+
const isRateLimited = result?.__statusCode === 429 || result?.__statusCode === 503;
|
|
723
|
+
if (isRateLimited && attempt < maxRateLimitRetries) {
|
|
724
|
+
const backoffMs = Math.min(500 * 2 ** attempt, 8000) + Math.floor(Math.random() * 250);
|
|
725
|
+
logger.warn({ hostname, attempt, backoffMs, statusCode: result.__statusCode }, 'media upload rate-limited, backing off before retry');
|
|
726
|
+
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
if (result?.url || result?.direct_path) {
|
|
730
|
+
urls = {
|
|
731
|
+
mediaUrl: result.url,
|
|
732
|
+
directPath: result.direct_path,
|
|
733
|
+
meta_hmac: result.meta_hmac,
|
|
734
|
+
fbid: result.fbid,
|
|
735
|
+
ts: result.ts
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
else {
|
|
739
|
+
uploadInfo = await refreshMediaConn(true);
|
|
740
|
+
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
|
|
741
|
+
}
|
|
742
|
+
break;
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
|
|
746
|
+
logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
|
|
747
|
+
break;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (urls)
|
|
751
|
+
break;
|
|
752
|
+
}
|
|
753
|
+
if (!urls) {
|
|
754
|
+
throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
|
|
755
|
+
}
|
|
756
|
+
return urls;
|
|
757
|
+
};
|
|
758
|
+
};
|
|
759
|
+
exports.getWAUploadToServer = getWAUploadToServer;
|
|
760
|
+
const getMediaRetryKey = mediaKey => {
|
|
761
|
+
return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
|
|
762
|
+
};
|
|
763
|
+
const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
764
|
+
const recp = { stanzaId: key.id };
|
|
765
|
+
const recpBuffer = index_js_1.proto.ServerErrorReceipt.encode(recp).finish();
|
|
766
|
+
const iv = Crypto.randomBytes(12);
|
|
767
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
768
|
+
const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
|
|
769
|
+
const req = {
|
|
770
|
+
tag: 'receipt',
|
|
771
|
+
attrs: {
|
|
772
|
+
id: key.id,
|
|
773
|
+
to: (0, WABinary_1.jidNormalizedUser)(meId),
|
|
774
|
+
type: 'server-error'
|
|
775
|
+
},
|
|
776
|
+
content: [
|
|
777
|
+
{
|
|
778
|
+
tag: 'encrypt',
|
|
779
|
+
attrs: {},
|
|
780
|
+
content: [
|
|
781
|
+
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
782
|
+
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
783
|
+
]
|
|
784
|
+
},
|
|
785
|
+
{
|
|
786
|
+
tag: 'rmr',
|
|
787
|
+
attrs: {
|
|
788
|
+
jid: key.remoteJid,
|
|
789
|
+
from_me: (!!key.fromMe).toString(),
|
|
790
|
+
participant: key.participant || undefined
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
]
|
|
794
|
+
};
|
|
795
|
+
return req;
|
|
796
|
+
};
|
|
797
|
+
exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
|
|
798
|
+
const decodeMediaRetryNode = node => {
|
|
799
|
+
const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
|
|
800
|
+
const event = {
|
|
801
|
+
key: {
|
|
802
|
+
id: node.attrs.id,
|
|
803
|
+
remoteJid: rmrNode.attrs.jid,
|
|
804
|
+
fromMe: rmrNode.attrs.from_me === 'true',
|
|
805
|
+
participant: rmrNode.attrs.participant
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
|
|
809
|
+
if (errorNode) {
|
|
810
|
+
const errorCode = +errorNode.attrs.code;
|
|
811
|
+
event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, {
|
|
812
|
+
data: errorNode.attrs,
|
|
813
|
+
statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode)
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
else {
|
|
817
|
+
const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
|
|
818
|
+
const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
|
|
819
|
+
const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
|
|
820
|
+
if (ciphertext && iv) {
|
|
821
|
+
event.media = { ciphertext, iv };
|
|
822
|
+
}
|
|
823
|
+
else {
|
|
824
|
+
event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
return event;
|
|
828
|
+
};
|
|
829
|
+
exports.decodeMediaRetryNode = decodeMediaRetryNode;
|
|
830
|
+
const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
831
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
832
|
+
const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
|
|
833
|
+
return index_js_1.proto.MediaRetryNotification.decode(plaintext);
|
|
834
|
+
};
|
|
835
|
+
exports.decryptMediaRetryData = decryptMediaRetryData;
|
|
836
|
+
const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code];
|
|
837
|
+
exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
|
|
838
|
+
const MEDIA_RETRY_STATUS_MAP = {
|
|
839
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
840
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
841
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
842
|
+
[index_js_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
843
|
+
};
|