kage-baileys 25.3.12 → 25.3.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/Defaults/connection.js +49 -108
- package/lib/Defaults/constants.js +71 -153
- package/lib/Defaults/index.js +0 -199
- package/lib/Defaults/media.js +0 -60
- package/lib/Defaults/prefix.js +17 -43
- package/lib/Modded/message_builder.js +0 -2355
- package/lib/Signal/Group/ciphertext-message.js +0 -54
- package/lib/Signal/Group/group-session-builder.js +0 -124
- package/lib/Signal/Group/group_cipher.js +0 -230
- package/lib/Signal/Group/index.js +0 -124
- package/lib/Signal/Group/keyhelper.js +0 -108
- package/lib/Signal/Group/sender-chain-key.js +0 -88
- package/lib/Signal/Group/sender-key-distribution-message.js +0 -157
- package/lib/Signal/Group/sender-key-message.js +0 -166
- package/lib/Signal/Group/sender-key-name.js +0 -130
- package/lib/Signal/Group/sender-key-record.js +0 -122
- package/lib/Signal/Group/sender-key-state.js +0 -220
- package/lib/Signal/Group/sender-message-key.js +0 -82
- package/lib/Signal/libsignal.js +0 -646
- package/lib/Signal/lid-mapping.js +0 -537
- package/lib/Socket/Client/index.js +0 -60
- package/lib/Socket/Client/types.js +0 -51
- package/lib/Socket/Client/websocket.js +0 -164
- package/lib/Socket/business.js +0 -708
- package/lib/Socket/chats.js +0 -2253
- package/lib/Socket/communities.js +0 -441
- package/lib/Socket/community.js +504 -1019
- package/lib/Socket/groups.js +0 -727
- package/lib/Socket/messages-recv.js +0 -2780
- package/lib/Socket/messages-send.js +0 -2640
- package/lib/Socket/mex.js +0 -128
- package/lib/Socket/newsletter.js +0 -486
- package/lib/Socket/socket.js +0 -1899
- package/lib/Store/index.js +0 -68
- package/lib/Store/make-cache-manager-store.js +0 -97
- package/lib/Store/make-in-memory-store.js +0 -908
- package/lib/Store/make-ordered-dictionary.js +0 -187
- package/lib/Store/object-repository.js +0 -78
- package/lib/Types/Bussines.js +2 -2
- package/lib/Types/Chat.js +0 -33
- package/lib/Types/Label.js +0 -78
- package/lib/Types/LabelAssociation.js +0 -42
- package/lib/Types/Message.js +0 -46
- package/lib/Types/Mex.js +0 -53
- package/lib/Types/MexUpdates.js +16 -43
- package/lib/Types/Newsletter.js +0 -27
- package/lib/Types/State.js +0 -42
- package/lib/Types/index.js +0 -134
- package/lib/Utils/auth-utils.js +0 -579
- package/lib/Utils/baileys-event-stream.js +65 -142
- package/lib/Utils/browser-utils.js +0 -104
- package/lib/Utils/business.js +0 -519
- package/lib/Utils/chat-utils.js +0 -1702
- package/lib/Utils/companion-reg-client-utils.js +0 -45
- package/lib/Utils/crypto.js +0 -382
- package/lib/Utils/decode-wa-message.js +0 -605
- package/lib/Utils/event-buffer.js +0 -1207
- package/lib/Utils/generics.js +0 -1020
- package/lib/Utils/history.js +0 -231
- package/lib/Utils/identity-change-handler.js +0 -59
- package/lib/Utils/index.js +0 -133
- package/lib/Utils/link-preview.js +0 -228
- package/lib/Utils/logger.js +0 -35
- package/lib/Utils/lt-hash.js +0 -60
- package/lib/Utils/make-mutex.js +0 -110
- package/lib/Utils/message-retry-manager.js +0 -429
- package/lib/Utils/messages-media.js +0 -1899
- package/lib/Utils/messages.js +0 -2950
- package/lib/Utils/noise-handler.js +0 -369
- package/lib/Utils/offline-node-processor.js +0 -50
- package/lib/Utils/pre-key-manager.js +0 -251
- package/lib/Utils/process-message.js +0 -1239
- package/lib/Utils/reporting-utils.js +0 -268
- package/lib/Utils/signal.js +0 -377
- package/lib/Utils/stanza-ack.js +0 -48
- package/lib/Utils/sync-action-utils.js +0 -58
- package/lib/Utils/tc-token-utils.js +0 -28
- package/lib/Utils/validate-connection.js +0 -508
- package/lib/VoIP/audio-feeder.js +0 -146
- package/lib/VoIP/index.js +0 -292
- package/lib/VoIP/relay-transport.js +0 -569
- package/lib/VoIP/signaling.js +0 -613
- package/lib/VoIP/types.js +0 -27
- package/lib/VoIP/wasm-engine.js +0 -1222
- package/lib/VoIP/worker-bootstrap.js +0 -1785
- package/lib/WABinary/constants.js +0 -2639
- package/lib/WABinary/decode.js +0 -612
- package/lib/WABinary/encode.js +0 -556
- package/lib/WABinary/generic-utils.js +0 -272
- package/lib/WABinary/index.js +0 -82
- package/lib/WABinary/jid-utils.js +0 -262
- package/lib/WAM/BinaryInfo.js +0 -50
- package/lib/WAM/constants.js +0 -38242
- package/lib/WAM/encode.js +0 -396
- package/lib/WAM/index.js +0 -78
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +47 -109
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -88
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -142
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -85
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -63
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -114
- package/lib/WAUSync/Protocols/index.js +0 -82
- package/lib/WAUSync/index.js +0 -78
- package/lib/assets/wasm/loader.js +0 -13
- package/lib/assets/wasm/worker-modules.js +0 -283
- package/lib/index.js +0 -93
- package/package.json +2 -3
- package/WAProto/index.d.ts +0 -46
- package/lib/Defaults/index.d.ts.map +0 -1
- package/lib/Defaults/index.js.map +0 -1
- package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
- package/lib/Signal/Group/ciphertext-message.js.map +0 -1
- package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
- package/lib/Signal/Group/group-session-builder.js.map +0 -1
- package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
- package/lib/Signal/Group/group_cipher.js.map +0 -1
- package/lib/Signal/Group/index.d.ts.map +0 -1
- package/lib/Signal/Group/index.js.map +0 -1
- package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
- package/lib/Signal/Group/keyhelper.js.map +0 -1
- package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
- package/lib/Signal/Group/sender-chain-key.js.map +0 -1
- package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
- package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
- package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
- package/lib/Signal/Group/sender-key-message.js.map +0 -1
- package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
- package/lib/Signal/Group/sender-key-name.js.map +0 -1
- package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
- package/lib/Signal/Group/sender-key-record.js.map +0 -1
- package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
- package/lib/Signal/Group/sender-key-state.js.map +0 -1
- package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
- package/lib/Signal/Group/sender-message-key.js.map +0 -1
- package/lib/Signal/libsignal.d.ts.map +0 -1
- package/lib/Signal/libsignal.js.map +0 -1
- package/lib/Signal/lid-mapping.d.ts.map +0 -1
- package/lib/Signal/lid-mapping.js.map +0 -1
- package/lib/Socket/Client/index.d.ts.map +0 -1
- package/lib/Socket/Client/index.js.map +0 -1
- package/lib/Socket/Client/types.d.ts.map +0 -1
- package/lib/Socket/Client/types.js.map +0 -1
- package/lib/Socket/Client/websocket.d.ts.map +0 -1
- package/lib/Socket/Client/websocket.js.map +0 -1
- package/lib/Socket/business.d.ts.map +0 -1
- package/lib/Socket/business.js.map +0 -1
- package/lib/Socket/chats.d.ts.map +0 -1
- package/lib/Socket/chats.js.map +0 -1
- package/lib/Socket/communities.d.ts.map +0 -1
- package/lib/Socket/communities.js.map +0 -1
- package/lib/Socket/groups.d.ts.map +0 -1
- package/lib/Socket/groups.js.map +0 -1
- package/lib/Socket/index.d.ts.map +0 -1
- package/lib/Socket/index.js.map +0 -1
- package/lib/Socket/messages-recv.d.ts.map +0 -1
- package/lib/Socket/messages-recv.js.map +0 -1
- package/lib/Socket/messages-send.d.ts.map +0 -1
- package/lib/Socket/messages-send.js.map +0 -1
- package/lib/Socket/mex.d.ts.map +0 -1
- package/lib/Socket/mex.js.map +0 -1
- package/lib/Socket/newsletter.d.ts.map +0 -1
- package/lib/Socket/newsletter.js.map +0 -1
- package/lib/Socket/socket.d.ts.map +0 -1
- package/lib/Socket/socket.js.map +0 -1
- package/lib/Store/index.d.ts.map +0 -1
- package/lib/Store/index.js.map +0 -1
- package/lib/Store/make-in-memory-store.d.ts.map +0 -1
- package/lib/Store/make-in-memory-store.js.map +0 -1
- package/lib/Store/make-ordered-dictionary.d.ts.map +0 -1
- package/lib/Store/make-ordered-dictionary.js.map +0 -1
- package/lib/Store/object-repository.d.ts.map +0 -1
- package/lib/Store/object-repository.js.map +0 -1
- package/lib/Types/Auth.d.ts.map +0 -1
- package/lib/Types/Auth.js.map +0 -1
- package/lib/Types/Bussines.d.ts.map +0 -1
- package/lib/Types/Call.d.ts.map +0 -1
- package/lib/Types/Chat.d.ts.map +0 -1
- package/lib/Types/Contact.d.ts.map +0 -1
- package/lib/Types/Events.d.ts.map +0 -1
- package/lib/Types/GroupMetadata.d.ts.map +0 -1
- package/lib/Types/Label.d.ts.map +0 -1
- package/lib/Types/LabelAssociation.d.ts.map +0 -1
- package/lib/Types/Message.d.ts.map +0 -1
- package/lib/Types/Mex.d.ts.map +0 -1
- package/lib/Types/Product.d.ts.map +0 -1
- package/lib/Types/RichType.d.ts.map +0 -1
- package/lib/Types/Signal.d.ts.map +0 -1
- package/lib/Types/Socket.d.ts.map +0 -1
- package/lib/Types/State.d.ts.map +0 -1
- package/lib/Types/USync.d.ts.map +0 -1
- package/lib/Types/index.d.ts.map +0 -1
- package/lib/Utils/auth-utils.d.ts.map +0 -1
- package/lib/Utils/auth-utils.js.map +0 -1
- package/lib/Utils/browser-utils.d.ts.map +0 -1
- package/lib/Utils/browser-utils.js.map +0 -1
- package/lib/Utils/business.d.ts.map +0 -1
- package/lib/Utils/business.js.map +0 -1
- package/lib/Utils/chat-utils.d.ts.map +0 -1
- package/lib/Utils/chat-utils.js.map +0 -1
- package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
- package/lib/Utils/companion-reg-client-utils.js.map +0 -1
- package/lib/Utils/crypto.d.ts.map +0 -1
- package/lib/Utils/crypto.js.map +0 -1
- package/lib/Utils/decode-wa-message.d.ts.map +0 -1
- package/lib/Utils/decode-wa-message.js.map +0 -1
- package/lib/Utils/event-buffer.d.ts.map +0 -1
- package/lib/Utils/event-buffer.js.map +0 -1
- package/lib/Utils/generics.d.ts.map +0 -1
- package/lib/Utils/generics.js.map +0 -1
- package/lib/Utils/history.d.ts.map +0 -1
- package/lib/Utils/history.js.map +0 -1
- package/lib/Utils/identity-change-handler.d.ts.map +0 -1
- package/lib/Utils/identity-change-handler.js.map +0 -1
- package/lib/Utils/index.d.ts.map +0 -1
- package/lib/Utils/index.js.map +0 -1
- package/lib/Utils/link-preview.d.ts.map +0 -1
- package/lib/Utils/link-preview.js.map +0 -1
- package/lib/Utils/logger.d.ts.map +0 -1
- package/lib/Utils/logger.js.map +0 -1
- package/lib/Utils/lt-hash.d.ts.map +0 -1
- package/lib/Utils/lt-hash.js.map +0 -1
- package/lib/Utils/make-mutex.d.ts.map +0 -1
- package/lib/Utils/make-mutex.js.map +0 -1
- package/lib/Utils/message-retry-manager.d.ts.map +0 -1
- package/lib/Utils/message-retry-manager.js.map +0 -1
- package/lib/Utils/messages-media.d.ts.map +0 -1
- package/lib/Utils/messages-media.js.map +0 -1
- package/lib/Utils/messages.d.ts.map +0 -1
- package/lib/Utils/messages.js.map +0 -1
- package/lib/Utils/noise-handler.d.ts.map +0 -1
- package/lib/Utils/noise-handler.js.map +0 -1
- package/lib/Utils/offline-node-processor.d.ts.map +0 -1
- package/lib/Utils/offline-node-processor.js.map +0 -1
- package/lib/Utils/pre-key-manager.d.ts.map +0 -1
- package/lib/Utils/pre-key-manager.js.map +0 -1
- package/lib/Utils/process-message.d.ts.map +0 -1
- package/lib/Utils/process-message.js.map +0 -1
- package/lib/Utils/reporting-utils.d.ts.map +0 -1
- package/lib/Utils/reporting-utils.js.map +0 -1
- package/lib/Utils/rich-message-utils.d.ts.map +0 -1
- package/lib/Utils/rich-message-utils.js.map +0 -1
- package/lib/Utils/signal.d.ts.map +0 -1
- package/lib/Utils/signal.js.map +0 -1
- package/lib/Utils/stanza-ack.d.ts.map +0 -1
- package/lib/Utils/stanza-ack.js.map +0 -1
- package/lib/Utils/sync-action-utils.d.ts.map +0 -1
- package/lib/Utils/sync-action-utils.js.map +0 -1
- package/lib/Utils/tc-token-utils.d.ts.map +0 -1
- package/lib/Utils/tc-token-utils.js.map +0 -1
- package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
- package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
- package/lib/Utils/use-single-file-auth-state.d.ts.map +0 -1
- package/lib/Utils/use-single-file-auth-state.js.map +0 -1
- package/lib/Utils/use-sqlite-auth-state.d.ts.map +0 -1
- package/lib/Utils/use-sqlite-auth-state.js.map +0 -1
- package/lib/Utils/validate-connection.d.ts.map +0 -1
- package/lib/Utils/validate-connection.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
|
@@ -32,1898 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
32
32
|
return result;
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
-
};
|
|
38
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.prepareStream = exports.getHttpStream = exports.getStream = exports.toBuffer = exports.toReadable = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.extractVideoThumb = exports.hkdfInfoKey = void 0;
|
|
40
|
-
exports.getMediaKeys = getMediaKeys;
|
|
41
|
-
exports.uploadFile = uploadFile;
|
|
42
|
-
exports.vid2jpg = vid2jpg;
|
|
43
|
-
exports.getAudioDuration = getAudioDuration;
|
|
44
|
-
exports.getAudioWaveform = getAudioWaveform;
|
|
45
|
-
exports.generateThumbnail = generateThumbnail;
|
|
46
|
-
exports.extensionForMediaMessage = extensionForMediaMessage;
|
|
47
|
-
const boom_1 = require("@hapi/boom");
|
|
48
|
-
const axios_1 = __importDefault(require("axios"));
|
|
49
|
-
const form_data_1 = __importDefault(require("form-data"));
|
|
50
|
-
const cheerio = __importStar(require("cheerio"));
|
|
51
|
-
const Crypto = __importStar(require("crypto"));
|
|
52
|
-
const events_1 = require("events");
|
|
53
|
-
const fs_1 = require("fs");
|
|
54
|
-
const os_1 = require("os");
|
|
55
|
-
const path_1 = require("path");
|
|
56
|
-
let jimp_1; try { jimp_1 = __importDefault(require("jimp")); } catch (e) { jimp_1 = { default: undefined }; }
|
|
57
|
-
const stream_1 = require("stream");
|
|
58
|
-
const child_process_1 = require("child_process");
|
|
59
|
-
const WAProto_1 = require("../../WAProto");
|
|
60
|
-
const Defaults_1 = require("../Defaults");
|
|
61
|
-
const WABinary_1 = require("../WABinary");
|
|
62
|
-
const crypto_1 = require("./crypto");
|
|
63
|
-
const generics_1 = require("./generics");
|
|
64
|
-
const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
|
|
65
|
-
const getImageProcessingLibrary = async () => {
|
|
66
|
-
const [_jimp, sharp] = await Promise.all([
|
|
67
|
-
(async () => {
|
|
68
|
-
const jimp = await (Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }));
|
|
69
|
-
return jimp;
|
|
70
|
-
})(),
|
|
71
|
-
(async () => {
|
|
72
|
-
const sharp = await (Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }));
|
|
73
|
-
return sharp;
|
|
74
|
-
})()
|
|
75
|
-
]);
|
|
76
|
-
if (sharp) {
|
|
77
|
-
return { sharp };
|
|
78
|
-
}
|
|
79
|
-
const jimp = _jimp?.Jimp || _jimp?.default?.Jimp || _jimp?.default || _jimp;
|
|
80
|
-
if (jimp) {
|
|
81
|
-
return { jimp };
|
|
82
|
-
}
|
|
83
|
-
throw new boom_1.Boom('No image processing library available');
|
|
84
|
-
};
|
|
85
|
-
const hkdfInfoKey = (type) => {
|
|
86
|
-
const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
|
|
87
|
-
return `WhatsApp ${hkdfInfo} Keys`;
|
|
88
|
-
};
|
|
89
|
-
exports.hkdfInfoKey = hkdfInfoKey;
|
|
90
|
-
|
|
91
|
-
async function getMediaKeys(buffer, mediaType) {
|
|
92
|
-
if (!buffer) {
|
|
93
|
-
throw new boom_1.Boom('Cannot derive from empty media key');
|
|
94
|
-
}
|
|
95
|
-
if (typeof buffer === 'string') {
|
|
96
|
-
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const expandedMediaKey = await (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
|
|
100
|
-
return {
|
|
101
|
-
iv: expandedMediaKey.slice(0, 16),
|
|
102
|
-
cipherKey: expandedMediaKey.slice(16, 48),
|
|
103
|
-
macKey: expandedMediaKey.slice(48, 80),
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
async function uploadFile(buffer, logger) {
|
|
107
|
-
const { fileTypeFromBuffer: fromBuffer } = await import('file-type');
|
|
108
|
-
const fileType = await fromBuffer(buffer);
|
|
109
|
-
if (!fileType)
|
|
110
|
-
throw new Error("Failed to detect file type.");
|
|
111
|
-
const { ext, mime } = fileType;
|
|
112
|
-
const services = [
|
|
113
|
-
{
|
|
114
|
-
name: "catbox",
|
|
115
|
-
url: "https://catbox.moe/user/api.php",
|
|
116
|
-
buildForm: () => {
|
|
117
|
-
const form = new form_data_1.default();
|
|
118
|
-
form.append("fileToUpload", buffer, {
|
|
119
|
-
filename: `file.${ext}`,
|
|
120
|
-
contentType: mime || "application/octet-stream"
|
|
121
|
-
});
|
|
122
|
-
form.append("reqtype", "fileupload");
|
|
123
|
-
return form;
|
|
124
|
-
},
|
|
125
|
-
parseResponse: res => res.data
|
|
126
|
-
},
|
|
127
|
-
{
|
|
128
|
-
name: "pdi.moe",
|
|
129
|
-
url: "https://scdn.pdi.moe/upload",
|
|
130
|
-
buildForm: () => {
|
|
131
|
-
const form = new form_data_1.default();
|
|
132
|
-
form.append("file", buffer, {
|
|
133
|
-
filename: `file.${ext}`,
|
|
134
|
-
contentType: mime
|
|
135
|
-
});
|
|
136
|
-
return form;
|
|
137
|
-
},
|
|
138
|
-
parseResponse: res => res.data.result.url
|
|
139
|
-
},
|
|
140
|
-
{
|
|
141
|
-
name: "qu.ax",
|
|
142
|
-
url: "https://qu.ax/upload.php",
|
|
143
|
-
buildForm: () => {
|
|
144
|
-
const form = new form_data_1.default();
|
|
145
|
-
form.append("files[]", buffer, {
|
|
146
|
-
filename: `file.${ext}`,
|
|
147
|
-
contentType: mime || "application/octet-stream"
|
|
148
|
-
});
|
|
149
|
-
return form;
|
|
150
|
-
},
|
|
151
|
-
parseResponse: res => {
|
|
152
|
-
var _a, _b, _c;
|
|
153
|
-
if (!((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.url))
|
|
154
|
-
throw new Error("Failed to get URL from qu.ax");
|
|
155
|
-
return res.data.files[0].url;
|
|
156
|
-
}
|
|
157
|
-
},
|
|
158
|
-
{
|
|
159
|
-
name: "uguu.se",
|
|
160
|
-
url: "https://uguu.se/upload.php",
|
|
161
|
-
buildForm: () => {
|
|
162
|
-
const form = new form_data_1.default();
|
|
163
|
-
form.append("files[]", buffer, {
|
|
164
|
-
filename: `file.${ext}`,
|
|
165
|
-
contentType: mime || "application/octet-stream"
|
|
166
|
-
});
|
|
167
|
-
return form;
|
|
168
|
-
},
|
|
169
|
-
parseResponse: res => {
|
|
170
|
-
var _a, _b, _c;
|
|
171
|
-
if (!((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.url))
|
|
172
|
-
throw new Error("Failed to get URL from uguu.se");
|
|
173
|
-
return res.data.files[0].url;
|
|
174
|
-
}
|
|
175
|
-
},
|
|
176
|
-
{
|
|
177
|
-
name: "tmpfiles",
|
|
178
|
-
url: "https://tmpfiles.org/api/v1/upload",
|
|
179
|
-
buildForm: () => {
|
|
180
|
-
const form = new form_data_1.default();
|
|
181
|
-
form.append("file", buffer, {
|
|
182
|
-
filename: `file.${ext}`,
|
|
183
|
-
contentType: mime
|
|
184
|
-
});
|
|
185
|
-
return form;
|
|
186
|
-
},
|
|
187
|
-
parseResponse: res => {
|
|
188
|
-
const match = res.data.data.url.match(/https:\/\/tmpfiles\.org\/(.*)/);
|
|
189
|
-
if (!match)
|
|
190
|
-
throw new Error("Failed to parse tmpfiles URL.");
|
|
191
|
-
return `https://tmpfiles.org/dl/${match[1]}`;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
];
|
|
195
|
-
for (const service of services) {
|
|
196
|
-
try {
|
|
197
|
-
const form = service.buildForm();
|
|
198
|
-
const res = await axios_1.default.post(service.url, form, {
|
|
199
|
-
headers: form.getHeaders()
|
|
200
|
-
});
|
|
201
|
-
const url = service.parseResponse(res);
|
|
202
|
-
return url;
|
|
203
|
-
}
|
|
204
|
-
catch (error) {
|
|
205
|
-
logger === null || logger === void 0 ? void 0 : logger.debug(`[${service.name}] eror:`, (error === null || error === void 0 ? void 0 : error.message) || error);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
throw new Error("All upload services failed.");
|
|
209
|
-
}
|
|
210
|
-
async function vid2jpg(videoUrl) {
|
|
211
|
-
try {
|
|
212
|
-
const { data } = await axios_1.default.get(`https://ezgif.com/video-to-jpg?url=${encodeURIComponent(videoUrl)}`);
|
|
213
|
-
const $ = cheerio.load(data);
|
|
214
|
-
const fileToken = $('input[name="file"]').attr("value");
|
|
215
|
-
if (!fileToken) {
|
|
216
|
-
throw new Error("Failed to retrieve file token. The video URL may be invalid or inaccessible.");
|
|
217
|
-
}
|
|
218
|
-
const formData = new URLSearchParams();
|
|
219
|
-
formData.append("file", fileToken);
|
|
220
|
-
formData.append("end", "1");
|
|
221
|
-
formData.append("video-to-jpg", "Convert to JPG!");
|
|
222
|
-
const convert = await axios_1.default.post(`https://ezgif.com/video-to-jpg/${fileToken}`, formData);
|
|
223
|
-
const $2 = cheerio.load(convert.data);
|
|
224
|
-
let imageUrl = $2("#output img").first().attr("src");
|
|
225
|
-
if (!imageUrl) {
|
|
226
|
-
throw new Error("Could not locate the converted image output.");
|
|
227
|
-
}
|
|
228
|
-
if (imageUrl.startsWith("//")) {
|
|
229
|
-
imageUrl = "https:" + imageUrl;
|
|
230
|
-
}
|
|
231
|
-
else if (imageUrl.startsWith("/")) {
|
|
232
|
-
const cdnMatch = imageUrl.match(/\/(s\d+\..+?)\/.*/);
|
|
233
|
-
if (cdnMatch) {
|
|
234
|
-
imageUrl = "https://" + imageUrl.slice(2);
|
|
235
|
-
}
|
|
236
|
-
else {
|
|
237
|
-
imageUrl = "https://ezgif.com" + imageUrl;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
return imageUrl;
|
|
241
|
-
}
|
|
242
|
-
catch (error) {
|
|
243
|
-
throw new Error("Failed to convert video to JPG: " + error.message);
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const extractVideoThumb = async (videoPath, time = '00:00:00', size = { width: 256 }) => {
|
|
250
|
-
return new Promise((resolve, reject) => {
|
|
251
|
-
const args = [
|
|
252
|
-
'-ss', time,
|
|
253
|
-
'-i', videoPath,
|
|
254
|
-
'-y',
|
|
255
|
-
'-vf', `scale=${size.width}:-1`,
|
|
256
|
-
'-vframes', '1',
|
|
257
|
-
'-f', 'image2',
|
|
258
|
-
'-vcodec', 'mjpeg',
|
|
259
|
-
'pipe:1'
|
|
260
|
-
];
|
|
261
|
-
const ffmpeg = (0, child_process_1.spawn)('ffmpeg', args);
|
|
262
|
-
const chunks = [];
|
|
263
|
-
let errorOutput = '';
|
|
264
|
-
ffmpeg.stdout.on('data', chunk => chunks.push(chunk));
|
|
265
|
-
ffmpeg.stderr.on('data', data => {
|
|
266
|
-
errorOutput += data.toString();
|
|
267
|
-
});
|
|
268
|
-
ffmpeg.on('error', reject);
|
|
269
|
-
ffmpeg.on('close', code => {
|
|
270
|
-
if (code === 0) return resolve(Buffer.concat(chunks));
|
|
271
|
-
reject(new Error(`ffmpeg exited with code ${code}\n${errorOutput}`));
|
|
272
|
-
});
|
|
273
|
-
});
|
|
274
|
-
};
|
|
275
|
-
exports.extractVideoThumb = extractVideoThumb;
|
|
276
|
-
const extractImageThumb = async (bufferOrFilePath, width = 32, quality = 50) => require('./image-processing').extractImageThumb(bufferOrFilePath, width, quality);
|
|
277
|
-
exports.extractImageThumb = extractImageThumb;
|
|
278
|
-
const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
|
|
279
|
-
.replace(/\+/g, '-')
|
|
280
|
-
.replace(/\//g, '_')
|
|
281
|
-
.replace(/\=+$/, '')));
|
|
282
|
-
exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
|
|
283
|
-
const generateProfilePicture = async (mediaUpload, dimensions) => require('./image-processing').generateProfilePicture(mediaUpload, dimensions);
|
|
284
|
-
exports.generateProfilePicture = generateProfilePicture;
|
|
285
|
-
|
|
286
|
-
const mediaMessageSHA256B64 = (message) => {
|
|
287
|
-
const media = Object.values(message)[0];
|
|
288
|
-
return (media === null || media === void 0 ? void 0 : media.fileSha256) && Buffer.from(media.fileSha256).toString('base64');
|
|
289
|
-
};
|
|
290
|
-
exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
|
|
291
|
-
async function getAudioDuration(buffer) {
|
|
292
|
-
const musicMetadata = await import('music-metadata');
|
|
293
|
-
let metadata;
|
|
294
|
-
const options = {
|
|
295
|
-
duration: true
|
|
296
|
-
};
|
|
297
|
-
if (Buffer.isBuffer(buffer)) {
|
|
298
|
-
metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
|
|
299
|
-
}
|
|
300
|
-
else if (typeof buffer === 'string') {
|
|
301
|
-
metadata = await musicMetadata.parseFile(buffer, options);
|
|
302
|
-
}
|
|
303
|
-
else {
|
|
304
|
-
metadata = await musicMetadata.parseStream(buffer, undefined, options);
|
|
305
|
-
}
|
|
306
|
-
return metadata.format.duration;
|
|
307
|
-
}
|
|
308
|
-
async function getAudioWaveform(buffer, logger) {
|
|
309
|
-
try {
|
|
310
|
-
const { default: decoder } = await eval('import(\'audio-decode\')');
|
|
311
|
-
let audioData;
|
|
312
|
-
if (Buffer.isBuffer(buffer)) {
|
|
313
|
-
audioData = buffer;
|
|
314
|
-
}
|
|
315
|
-
else if (typeof buffer === 'string') {
|
|
316
|
-
const rStream = (0, fs_1.createReadStream)(buffer);
|
|
317
|
-
audioData = await (0, exports.toBuffer)(rStream);
|
|
318
|
-
}
|
|
319
|
-
else {
|
|
320
|
-
audioData = await (0, exports.toBuffer)(buffer);
|
|
321
|
-
}
|
|
322
|
-
const audioBuffer = await decoder(audioData);
|
|
323
|
-
const rawData = audioBuffer.getChannelData(0);
|
|
324
|
-
const samples = 64;
|
|
325
|
-
const blockSize = Math.floor(rawData.length / samples);
|
|
326
|
-
const filteredData = [];
|
|
327
|
-
for (let i = 0; i < samples; i++) {
|
|
328
|
-
const blockStart = blockSize * i;
|
|
329
|
-
let sum = 0;
|
|
330
|
-
for (let j = 0; j < blockSize; j++) {
|
|
331
|
-
sum = sum + Math.abs(rawData[blockStart + j]);
|
|
332
|
-
}
|
|
333
|
-
filteredData.push(sum / blockSize);
|
|
334
|
-
}
|
|
335
|
-
const multiplier = Math.pow(Math.max(...filteredData), -1);
|
|
336
|
-
const normalizedData = filteredData.map((n) => n * multiplier);
|
|
337
|
-
const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)));
|
|
338
|
-
return waveform;
|
|
339
|
-
}
|
|
340
|
-
catch (e) {
|
|
341
|
-
logger === null || logger === void 0 ? void 0 : logger.debug('Failed to generate waveform: ' + e);
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
const toReadable = (buffer) => {
|
|
345
|
-
const readable = new stream_1.Readable({ read: () => { } });
|
|
346
|
-
readable.push(buffer);
|
|
347
|
-
readable.push(null);
|
|
348
|
-
return readable;
|
|
349
|
-
};
|
|
350
|
-
exports.toReadable = toReadable;
|
|
351
|
-
const toBuffer = async (stream) => {
|
|
352
|
-
const chunks = [];
|
|
353
|
-
for await (const chunk of stream) {
|
|
354
|
-
chunks.push(chunk);
|
|
355
|
-
}
|
|
356
|
-
stream.destroy();
|
|
357
|
-
return Buffer.concat(chunks);
|
|
358
|
-
};
|
|
359
|
-
exports.toBuffer = toBuffer;
|
|
360
|
-
const getStream = async (item, opts) => {
|
|
361
|
-
if (Buffer.isBuffer(item)) {
|
|
362
|
-
return { stream: (0, exports.toReadable)(item), type: 'buffer' };
|
|
363
|
-
}
|
|
364
|
-
if ('stream' in item) {
|
|
365
|
-
return { stream: item.stream, type: 'readable' };
|
|
366
|
-
}
|
|
367
|
-
if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
|
|
368
|
-
return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
|
|
369
|
-
}
|
|
370
|
-
return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
|
|
371
|
-
};
|
|
372
|
-
exports.getStream = getStream;
|
|
373
|
-
|
|
374
|
-
async function generateThumbnail(file, mediaType, options) {
|
|
375
|
-
var _a;
|
|
376
|
-
let thumbnail;
|
|
377
|
-
let originalImageDimensions;
|
|
378
|
-
if (mediaType === 'image') {
|
|
379
|
-
const { buffer, original } = await (0, exports.extractImageThumb)(file);
|
|
380
|
-
thumbnail = buffer.toString('base64');
|
|
381
|
-
if (original.width && original.height) {
|
|
382
|
-
originalImageDimensions = {
|
|
383
|
-
width: original.width,
|
|
384
|
-
height: original.height,
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
else if (mediaType === 'video') {
|
|
389
|
-
try {
|
|
390
|
-
let videoPath = file;
|
|
391
|
-
if (Buffer.isBuffer(file) || file instanceof stream_1.Readable) {
|
|
392
|
-
videoPath = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageIDV2)() + '.mp4');
|
|
393
|
-
const buffer = Buffer.isBuffer(file) ? file : await (0, exports.toBuffer)(file);
|
|
394
|
-
await fs_1.promises.writeFile(videoPath, buffer);
|
|
395
|
-
}
|
|
396
|
-
const thumbnailBuffer = await (0, exports.extractVideoThumb)(videoPath);
|
|
397
|
-
const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageIDV2)() + '.jpg');
|
|
398
|
-
await fs_1.promises.writeFile(imgFilename, thumbnailBuffer);
|
|
399
|
-
const { buffer: processedThumbnailBuffer, original } = await (0, exports.extractImageThumb)(imgFilename);
|
|
400
|
-
thumbnail = processedThumbnailBuffer.toString('base64');
|
|
401
|
-
if (original.width && original.height) {
|
|
402
|
-
originalImageDimensions = {
|
|
403
|
-
width: original.width,
|
|
404
|
-
height: original.height,
|
|
405
|
-
};
|
|
406
|
-
}
|
|
407
|
-
await fs_1.promises.unlink(imgFilename);
|
|
408
|
-
if (videoPath !== file) {
|
|
409
|
-
await fs_1.promises.unlink(videoPath);
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
catch (err) {
|
|
413
|
-
(_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug('could not generate video thumb: ' + err);
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
return {
|
|
417
|
-
thumbnail,
|
|
418
|
-
originalImageDimensions
|
|
419
|
-
};
|
|
420
|
-
}
|
|
421
|
-
const getHttpStream = async (url, options = {}) => {
|
|
422
|
-
const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' });
|
|
423
|
-
return fetched.data;
|
|
424
|
-
};
|
|
425
|
-
exports.getHttpStream = getHttpStream;
|
|
426
|
-
const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
427
|
-
const { stream, type } = await (0, exports.getStream)(media, opts);
|
|
428
|
-
logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
|
|
429
|
-
let bodyPath;
|
|
430
|
-
let didSaveToTmpPath = false;
|
|
431
|
-
try {
|
|
432
|
-
const buffer = await (0, exports.toBuffer)(stream);
|
|
433
|
-
if (type === 'file') {
|
|
434
|
-
bodyPath = media.url;
|
|
435
|
-
}
|
|
436
|
-
else if (saveOriginalFileIfRequired) {
|
|
437
|
-
bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)());
|
|
438
|
-
(0, fs_1.writeFileSync)(bodyPath, buffer);
|
|
439
|
-
didSaveToTmpPath = true;
|
|
440
|
-
}
|
|
441
|
-
const fileLength = buffer.length;
|
|
442
|
-
const fileSha256 = Crypto.createHash('sha256').update(buffer).digest();
|
|
443
|
-
stream === null || stream === void 0 ? void 0 : stream.destroy();
|
|
444
|
-
logger === null || logger === void 0 ? void 0 : logger.debug('prepare stream data successfully');
|
|
445
|
-
return {
|
|
446
|
-
mediaKey: undefined,
|
|
447
|
-
encWriteStream: buffer,
|
|
448
|
-
fileLength,
|
|
449
|
-
fileSha256,
|
|
450
|
-
fileEncSha256: undefined,
|
|
451
|
-
bodyPath,
|
|
452
|
-
didSaveToTmpPath
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
catch (error) {
|
|
456
|
-
stream.destroy();
|
|
457
|
-
if (didSaveToTmpPath) {
|
|
458
|
-
try {
|
|
459
|
-
await fs_1.promises.unlink(bodyPath);
|
|
460
|
-
}
|
|
461
|
-
catch (err) {
|
|
462
|
-
logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
throw error;
|
|
466
|
-
}
|
|
467
|
-
};
|
|
468
|
-
exports.prepareStream = prepareStream;
|
|
469
|
-
const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
470
|
-
const { stream, type } = await (0, exports.getStream)(media, opts);
|
|
471
|
-
logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
|
|
472
|
-
const mediaKey = Crypto.randomBytes(32);
|
|
473
|
-
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
|
|
474
|
-
const encWriteStream = new stream_1.Readable({ read: () => { } });
|
|
475
|
-
let bodyPath;
|
|
476
|
-
let writeStream;
|
|
477
|
-
let didSaveToTmpPath = false;
|
|
478
|
-
if (type === 'file') {
|
|
479
|
-
bodyPath = media.url;
|
|
480
|
-
}
|
|
481
|
-
else if (saveOriginalFileIfRequired) {
|
|
482
|
-
bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)());
|
|
483
|
-
writeStream = (0, fs_1.createWriteStream)(bodyPath);
|
|
484
|
-
didSaveToTmpPath = true;
|
|
485
|
-
}
|
|
486
|
-
let fileLength = 0;
|
|
487
|
-
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
|
|
488
|
-
let hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
|
489
|
-
let sha256Plain = Crypto.createHash('sha256');
|
|
490
|
-
let sha256Enc = Crypto.createHash('sha256');
|
|
491
|
-
try {
|
|
492
|
-
for await (const data of stream) {
|
|
493
|
-
fileLength += data.length;
|
|
494
|
-
if (type === 'remote'
|
|
495
|
-
&& (opts === null || opts === void 0 ? void 0 : opts.maxContentLength)
|
|
496
|
-
&& fileLength + data.length > opts.maxContentLength) {
|
|
497
|
-
throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
|
|
498
|
-
data: { media, type }
|
|
499
|
-
});
|
|
500
|
-
}
|
|
501
|
-
sha256Plain = sha256Plain.update(data);
|
|
502
|
-
if (writeStream) {
|
|
503
|
-
if (!writeStream.write(data)) {
|
|
504
|
-
await (0, events_1.once)(writeStream, 'drain');
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
onChunk(aes.update(data));
|
|
508
|
-
}
|
|
509
|
-
onChunk(aes.final());
|
|
510
|
-
const mac = hmac.digest().slice(0, 10);
|
|
511
|
-
sha256Enc = sha256Enc.update(mac);
|
|
512
|
-
const fileSha256 = sha256Plain.digest();
|
|
513
|
-
const fileEncSha256 = sha256Enc.digest();
|
|
514
|
-
encWriteStream.push(mac);
|
|
515
|
-
encWriteStream.push(null);
|
|
516
|
-
writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
|
|
517
|
-
stream.destroy();
|
|
518
|
-
logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
|
|
519
|
-
return {
|
|
520
|
-
mediaKey,
|
|
521
|
-
encWriteStream,
|
|
522
|
-
bodyPath,
|
|
523
|
-
mac,
|
|
524
|
-
fileEncSha256,
|
|
525
|
-
fileSha256,
|
|
526
|
-
fileLength,
|
|
527
|
-
didSaveToTmpPath
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
|
-
catch (error) {
|
|
531
|
-
encWriteStream.destroy();
|
|
532
|
-
writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
|
|
533
|
-
aes.destroy();
|
|
534
|
-
hmac.destroy();
|
|
535
|
-
sha256Plain.destroy();
|
|
536
|
-
sha256Enc.destroy();
|
|
537
|
-
stream.destroy();
|
|
538
|
-
if (didSaveToTmpPath) {
|
|
539
|
-
try {
|
|
540
|
-
await fs_1.promises.unlink(bodyPath);
|
|
541
|
-
}
|
|
542
|
-
catch (err) {
|
|
543
|
-
logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
throw error;
|
|
547
|
-
}
|
|
548
|
-
function onChunk(buff) {
|
|
549
|
-
sha256Enc = sha256Enc.update(buff);
|
|
550
|
-
hmac = hmac.update(buff);
|
|
551
|
-
encWriteStream.push(buff);
|
|
552
|
-
}
|
|
553
|
-
};
|
|
554
|
-
exports.encryptedStream = encryptedStream;
|
|
555
|
-
const DEF_HOST = 'mmg.whatsapp.net';
|
|
556
|
-
const AES_CHUNK_SIZE = 16;
|
|
557
|
-
const toSmallestChunkSize = (num) => {
|
|
558
|
-
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
|
|
559
|
-
};
|
|
560
|
-
const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
|
|
561
|
-
exports.getUrlFromDirectPath = getUrlFromDirectPath;
|
|
562
|
-
const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
563
|
-
const isValidMediaUrl = url === null || url === void 0 ? void 0 : url.startsWith('https://mmg.whatsapp.net/');
|
|
564
|
-
const downloadUrl = isValidMediaUrl ? url : (0, exports.getUrlFromDirectPath)(directPath);
|
|
565
|
-
if (!downloadUrl) {
|
|
566
|
-
throw new boom_1.Boom('No valid media URL or directPath present in message', { statusCode: 400 });
|
|
567
|
-
}
|
|
568
|
-
const keys = await getMediaKeys(mediaKey, type);
|
|
569
|
-
return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
|
|
570
|
-
};
|
|
571
|
-
exports.downloadContentFromMessage = downloadContentFromMessage;
|
|
572
|
-
const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
573
|
-
let bytesFetched = 0;
|
|
574
|
-
let startChunk = 0;
|
|
575
|
-
let firstBlockIsIV = false;
|
|
576
|
-
if (startByte) {
|
|
577
|
-
const chunk = toSmallestChunkSize(startByte || 0);
|
|
578
|
-
if (chunk) {
|
|
579
|
-
startChunk = chunk - AES_CHUNK_SIZE;
|
|
580
|
-
bytesFetched = chunk;
|
|
581
|
-
firstBlockIsIV = true;
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
|
|
585
|
-
const headers = {
|
|
586
|
-
...(options === null || options === void 0 ? void 0 : options.headers) || {},
|
|
587
|
-
Origin: Defaults_1.DEFAULT_ORIGIN,
|
|
588
|
-
};
|
|
589
|
-
if (startChunk || endChunk) {
|
|
590
|
-
headers.Range = `bytes=${startChunk}-`;
|
|
591
|
-
if (endChunk) {
|
|
592
|
-
headers.Range += endChunk;
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
const fetched = await (0, exports.getHttpStream)(downloadUrl, {
|
|
596
|
-
...options || {},
|
|
597
|
-
headers,
|
|
598
|
-
maxBodyLength: Infinity,
|
|
599
|
-
maxContentLength: Infinity,
|
|
600
|
-
});
|
|
601
|
-
let remainingBytes = Buffer.from([]);
|
|
602
|
-
let aes;
|
|
603
|
-
const pushBytes = (bytes, push) => {
|
|
604
|
-
if (startByte || endByte) {
|
|
605
|
-
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
|
|
606
|
-
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
|
|
607
|
-
push(bytes.slice(start, end));
|
|
608
|
-
bytesFetched += bytes.length;
|
|
609
|
-
}
|
|
610
|
-
else {
|
|
611
|
-
push(bytes);
|
|
612
|
-
}
|
|
613
|
-
};
|
|
614
|
-
const output = new stream_1.Transform({
|
|
615
|
-
transform(chunk, _, callback) {
|
|
616
|
-
let data = Buffer.concat([remainingBytes, chunk]);
|
|
617
|
-
const decryptLength = toSmallestChunkSize(data.length);
|
|
618
|
-
remainingBytes = data.slice(decryptLength);
|
|
619
|
-
data = data.slice(0, decryptLength);
|
|
620
|
-
if (!aes) {
|
|
621
|
-
let ivValue = iv;
|
|
622
|
-
if (firstBlockIsIV) {
|
|
623
|
-
ivValue = data.slice(0, AES_CHUNK_SIZE);
|
|
624
|
-
data = data.slice(AES_CHUNK_SIZE);
|
|
625
|
-
}
|
|
626
|
-
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
|
|
627
|
-
if (endByte) {
|
|
628
|
-
aes.setAutoPadding(false);
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
try {
|
|
632
|
-
pushBytes(aes.update(data), b => this.push(b));
|
|
633
|
-
callback();
|
|
634
|
-
}
|
|
635
|
-
catch (error) {
|
|
636
|
-
callback(error);
|
|
637
|
-
}
|
|
638
|
-
},
|
|
639
|
-
final(callback) {
|
|
640
|
-
try {
|
|
641
|
-
pushBytes(aes.final(), b => this.push(b));
|
|
642
|
-
callback();
|
|
643
|
-
}
|
|
644
|
-
catch (error) {
|
|
645
|
-
callback(error);
|
|
646
|
-
}
|
|
647
|
-
},
|
|
648
|
-
});
|
|
649
|
-
return fetched.pipe(output, { end: true });
|
|
650
|
-
};
|
|
651
|
-
exports.downloadEncryptedContent = downloadEncryptedContent;
|
|
652
|
-
function extensionForMediaMessage(message) {
|
|
653
|
-
const getExtension = (mimetype) => mimetype.split(';')[0].split('/')[1];
|
|
654
|
-
const type = Object.keys(message)[0];
|
|
655
|
-
let extension;
|
|
656
|
-
if (type === 'locationMessage' ||
|
|
657
|
-
type === 'liveLocationMessage' ||
|
|
658
|
-
type === 'productMessage') {
|
|
659
|
-
extension = '.jpeg';
|
|
660
|
-
}
|
|
661
|
-
else {
|
|
662
|
-
const messageContent = message[type];
|
|
663
|
-
extension = getExtension(messageContent.mimetype);
|
|
664
|
-
}
|
|
665
|
-
return extension;
|
|
666
|
-
}
|
|
667
|
-
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
668
|
-
return async (stream, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
|
|
669
|
-
var _a, _b;
|
|
670
|
-
let uploadInfo = await refreshMediaConn(false);
|
|
671
|
-
let urls;
|
|
672
|
-
const hosts = [...customUploadHosts, ...uploadInfo.hosts];
|
|
673
|
-
const chunks = [];
|
|
674
|
-
if (!Buffer.isBuffer(stream)) {
|
|
675
|
-
for await (const chunk of stream) {
|
|
676
|
-
chunks.push(chunk);
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
const reqBody = Buffer.isBuffer(stream) ? stream : Buffer.concat(chunks);
|
|
680
|
-
fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
|
|
681
|
-
let media = Defaults_1.MEDIA_PATH_MAP[mediaType];
|
|
682
|
-
// Baileys oficial: sticker-pack usa /mms/sticker (no /mms/sticker-pack)
|
|
683
|
-
if (mediaType === 'sticker-pack') media = '/mms/sticker';
|
|
684
|
-
if (mediaType === 'thumbnail-sticker-pack') media = '/mms/image';
|
|
685
|
-
if (newsletter) {
|
|
686
|
-
media = media === null || media === void 0 ? void 0 : media.replace('/mms/', '/newsletter/newsletter-');
|
|
687
|
-
}
|
|
688
|
-
for (const { hostname, maxContentLengthBytes } of hosts) {
|
|
689
|
-
logger.debug(`uploading to "${hostname}"`);
|
|
690
|
-
const auth = encodeURIComponent(uploadInfo.auth);
|
|
691
|
-
const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
|
|
692
|
-
let result;
|
|
693
|
-
try {
|
|
694
|
-
if (maxContentLengthBytes && reqBody.length > maxContentLengthBytes) {
|
|
695
|
-
throw new boom_1.Boom(`Body too large for "${hostname}"`, { statusCode: 413 });
|
|
696
|
-
}
|
|
697
|
-
const body = await axios_1.default.post(url, reqBody, {
|
|
698
|
-
...options,
|
|
699
|
-
headers: {
|
|
700
|
-
...options.headers || {},
|
|
701
|
-
'Content-Type': 'application/octet-stream',
|
|
702
|
-
'Origin': Defaults_1.DEFAULT_ORIGIN
|
|
703
|
-
},
|
|
704
|
-
httpsAgent: fetchAgent,
|
|
705
|
-
timeout: timeoutMs,
|
|
706
|
-
responseType: 'json',
|
|
707
|
-
maxBodyLength: Infinity,
|
|
708
|
-
maxContentLength: Infinity,
|
|
709
|
-
});
|
|
710
|
-
result = body.data;
|
|
711
|
-
if ((result === null || result === void 0 ? void 0 : result.url) || (result === null || result === void 0 ? void 0 : result.directPath)) {
|
|
712
|
-
urls = {
|
|
713
|
-
mediaUrl: result.url,
|
|
714
|
-
directPath: result.direct_path,
|
|
715
|
-
handle: result.handle
|
|
716
|
-
};
|
|
717
|
-
break;
|
|
718
|
-
}
|
|
719
|
-
else {
|
|
720
|
-
uploadInfo = await refreshMediaConn(true);
|
|
721
|
-
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
catch (error) {
|
|
725
|
-
if (axios_1.default.isAxiosError(error)) {
|
|
726
|
-
result = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
|
|
727
|
-
}
|
|
728
|
-
const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
|
|
729
|
-
logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
if (!urls) {
|
|
733
|
-
throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
|
|
734
|
-
}
|
|
735
|
-
return urls;
|
|
736
|
-
};
|
|
737
|
-
};
|
|
738
|
-
exports.getWAUploadToServer = getWAUploadToServer;
|
|
739
|
-
const getMediaRetryKey = (mediaKey) => {
|
|
740
|
-
return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
|
|
741
|
-
};
|
|
742
|
-
const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
|
|
743
|
-
const recp = { stanzaId: key.id };
|
|
744
|
-
const recpBuffer = WAProto_1.proto.ServerErrorReceipt.encode(recp).finish();
|
|
745
|
-
const iv = Crypto.randomBytes(12);
|
|
746
|
-
const retryKey = await getMediaRetryKey(mediaKey);
|
|
747
|
-
const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
|
|
748
|
-
const req = {
|
|
749
|
-
tag: 'receipt',
|
|
750
|
-
attrs: {
|
|
751
|
-
id: key.id,
|
|
752
|
-
to: (0, WABinary_1.jidNormalizedUser)(meId),
|
|
753
|
-
type: 'server-error'
|
|
754
|
-
},
|
|
755
|
-
content: [
|
|
756
|
-
{
|
|
757
|
-
tag: 'encrypt',
|
|
758
|
-
attrs: {},
|
|
759
|
-
content: [
|
|
760
|
-
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
761
|
-
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
762
|
-
]
|
|
763
|
-
},
|
|
764
|
-
{
|
|
765
|
-
tag: 'rmr',
|
|
766
|
-
attrs: {
|
|
767
|
-
jid: key.remoteJid,
|
|
768
|
-
'from_me': (!!key.fromMe).toString(),
|
|
769
|
-
participant: key.participant || undefined
|
|
770
|
-
}
|
|
771
|
-
}
|
|
772
|
-
]
|
|
773
|
-
};
|
|
774
|
-
return req;
|
|
775
|
-
};
|
|
776
|
-
exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
|
|
777
|
-
const decodeMediaRetryNode = (node) => {
|
|
778
|
-
const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
|
|
779
|
-
const event = {
|
|
780
|
-
key: {
|
|
781
|
-
id: node.attrs.id,
|
|
782
|
-
remoteJid: rmrNode.attrs.jid,
|
|
783
|
-
fromMe: rmrNode.attrs.from_me === 'true',
|
|
784
|
-
participant: rmrNode.attrs.participant
|
|
785
|
-
}
|
|
786
|
-
};
|
|
787
|
-
const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
|
|
788
|
-
if (errorNode) {
|
|
789
|
-
const errorCode = +errorNode.attrs.code;
|
|
790
|
-
event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode) });
|
|
791
|
-
}
|
|
792
|
-
else {
|
|
793
|
-
const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
|
|
794
|
-
const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
|
|
795
|
-
const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
|
|
796
|
-
if (ciphertext && iv) {
|
|
797
|
-
event.media = { ciphertext, iv };
|
|
798
|
-
}
|
|
799
|
-
else {
|
|
800
|
-
event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
return event;
|
|
804
|
-
};
|
|
805
|
-
exports.decodeMediaRetryNode = decodeMediaRetryNode;
|
|
806
|
-
const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
807
|
-
const retryKey = await getMediaRetryKey(mediaKey);
|
|
808
|
-
const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
|
|
809
|
-
return WAProto_1.proto.MediaRetryNotification.decode(plaintext);
|
|
810
|
-
};
|
|
811
|
-
exports.decryptMediaRetryData = decryptMediaRetryData;
|
|
812
|
-
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
|
|
813
|
-
exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
|
|
814
|
-
const MEDIA_RETRY_STATUS_MAP = {
|
|
815
|
-
[WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
816
|
-
[WAProto_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
817
|
-
[WAProto_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
818
|
-
[WAProto_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
|
|
819
|
-
};
|
|
820
|
-
function __importStar(arg0) {
|
|
821
|
-
throw new Error('Function not implemented.');
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
const __kageModule73 = (() => {
|
|
825
|
-
const module = { exports: {} }; const exports = module.exports;
|
|
826
|
-
"use strict"
|
|
827
|
-
|
|
828
|
-
Object.defineProperty(exports, "__esModule", { value: true })
|
|
829
|
-
|
|
830
|
-
const { Boom } = require("@hapi/boom")
|
|
831
|
-
const { exec } = require("child_process")
|
|
832
|
-
const { once } = require("events")
|
|
833
|
-
const {
|
|
834
|
-
createHash,
|
|
835
|
-
randomBytes,
|
|
836
|
-
createHmac,
|
|
837
|
-
createCipheriv,
|
|
838
|
-
createDecipheriv
|
|
839
|
-
} = require("crypto")
|
|
840
|
-
const {
|
|
841
|
-
promises,
|
|
842
|
-
createReadStream,
|
|
843
|
-
createWriteStream
|
|
844
|
-
} = require("fs")
|
|
845
|
-
const {
|
|
846
|
-
parseBuffer,
|
|
847
|
-
parseFile,
|
|
848
|
-
parseStream
|
|
849
|
-
} = require('music-metadata')
|
|
850
|
-
const { tmpdir } = require("os")
|
|
851
|
-
const { join } = require("path")
|
|
852
|
-
const {
|
|
853
|
-
Readable,
|
|
854
|
-
Transform
|
|
855
|
-
} = require("stream")
|
|
856
|
-
const { proto } = require("../../WAProto")
|
|
857
|
-
const {
|
|
858
|
-
MEDIA_PATH_MAP,
|
|
859
|
-
MEDIA_HKDF_KEY_MAPPING
|
|
860
|
-
} = require("../Defaults/media")
|
|
861
|
-
const { DEFAULT_ORIGIN } = require("../Defaults/constants")
|
|
862
|
-
const {
|
|
863
|
-
getBinaryNodeChild,
|
|
864
|
-
getBinaryNodeChildBuffer,
|
|
865
|
-
jidNormalizedUser
|
|
866
|
-
} = require("../WABinary")
|
|
867
|
-
const {
|
|
868
|
-
aesDecryptGCM,
|
|
869
|
-
aesEncryptGCM,
|
|
870
|
-
hkdf
|
|
871
|
-
} = require("./crypto")
|
|
872
|
-
const { generateMessageID } = require("./generics")
|
|
873
|
-
|
|
874
|
-
const getTmpFilesDirectory = () => tmpdir()
|
|
875
|
-
|
|
876
|
-
const getImageProcessingLibrary = () => {
|
|
877
|
-
let sharp, jimp
|
|
878
|
-
|
|
879
|
-
try {
|
|
880
|
-
sharp = require('sharp')
|
|
881
|
-
} catch {}
|
|
882
|
-
|
|
883
|
-
if (sharp) {
|
|
884
|
-
return { sharp }
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
try {
|
|
888
|
-
jimp = require('jimp')
|
|
889
|
-
} catch {}
|
|
890
|
-
|
|
891
|
-
if (jimp) {
|
|
892
|
-
return { jimp }
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
throw new Boom('No image processing library available')
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
const hkdfInfoKey = (type) => {
|
|
899
|
-
const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type]
|
|
900
|
-
return `WhatsApp ${hkdfInfo} Keys`
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
const getRawMediaUploadData = async (media, mediaType, logger) => {
|
|
904
|
-
const { stream } = await getStream(media)
|
|
905
|
-
|
|
906
|
-
logger?.debug('got stream for raw upload')
|
|
907
|
-
|
|
908
|
-
const hasher = createHash('sha256')
|
|
909
|
-
const filePath = join(getTmpFilesDirectory(), mediaType + generateMessageID())
|
|
910
|
-
const fileWriteStream = createWriteStream(filePath)
|
|
911
|
-
|
|
912
|
-
let fileLength = 0
|
|
913
|
-
|
|
914
|
-
try {
|
|
915
|
-
for await (const data of stream) {
|
|
916
|
-
fileLength += data.length
|
|
917
|
-
hasher.update(data)
|
|
918
|
-
|
|
919
|
-
if (!fileWriteStream.write(data)) {
|
|
920
|
-
await once(fileWriteStream, 'drain')
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
fileWriteStream.end()
|
|
925
|
-
await once(fileWriteStream, 'finish')
|
|
926
|
-
stream.destroy()
|
|
927
|
-
|
|
928
|
-
const fileSha256 = hasher.digest()
|
|
929
|
-
|
|
930
|
-
logger?.debug('hashed data for raw upload')
|
|
931
|
-
|
|
932
|
-
return {
|
|
933
|
-
filePath: filePath,
|
|
934
|
-
fileSha256,
|
|
935
|
-
fileLength
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
catch (error) {
|
|
939
|
-
fileWriteStream.destroy()
|
|
940
|
-
stream.destroy()
|
|
941
|
-
|
|
942
|
-
try {
|
|
943
|
-
await promises.unlink(filePath)
|
|
944
|
-
}
|
|
945
|
-
catch {
|
|
946
|
-
|
|
947
|
-
}
|
|
948
|
-
throw error
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
async function getMediaKeys(buffer, mediaType) {
|
|
954
|
-
if (!buffer) {
|
|
955
|
-
throw new Boom('Cannot derive from empty media key')
|
|
956
|
-
}
|
|
957
|
-
if (typeof buffer === 'string') {
|
|
958
|
-
buffer = Buffer.from(buffer.replace('data:base64,', ''), 'base64')
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
const expandedMediaKey = await hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
|
|
962
|
-
return {
|
|
963
|
-
iv: expandedMediaKey.slice(0, 16),
|
|
964
|
-
cipherKey: expandedMediaKey.slice(16, 48),
|
|
965
|
-
macKey: expandedMediaKey.slice(48, 80)
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
|
|
971
|
-
const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`
|
|
972
|
-
exec(cmd, err => {
|
|
973
|
-
if (err) {
|
|
974
|
-
reject(err)
|
|
975
|
-
}
|
|
976
|
-
else {
|
|
977
|
-
resolve()
|
|
978
|
-
}
|
|
979
|
-
})
|
|
980
|
-
})
|
|
981
|
-
|
|
982
|
-
const extractImageThumb = async (bufferOrFilePath, width = 32, quality = 50) => {
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
if (bufferOrFilePath instanceof Readable) {
|
|
986
|
-
bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
const lib = await getImageProcessingLibrary()
|
|
990
|
-
|
|
991
|
-
if ('sharp' in lib && typeof lib.sharp === 'function') {
|
|
992
|
-
const img = lib.sharp(bufferOrFilePath)
|
|
993
|
-
const dimensions = await img.metadata()
|
|
994
|
-
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer()
|
|
995
|
-
return {
|
|
996
|
-
buffer,
|
|
997
|
-
original: {
|
|
998
|
-
width: dimensions.width,
|
|
999
|
-
height: dimensions.height
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
else if ('jimp' in lib && typeof lib.jimp.read === 'function') {
|
|
1004
|
-
const { read, MIME_JPEG, RESIZE_BEZIER, AUTO } = lib.jimp
|
|
1005
|
-
const jimp = await read(bufferOrFilePath)
|
|
1006
|
-
const dimensions = {
|
|
1007
|
-
width: jimp.getWidth(),
|
|
1008
|
-
height: jimp.getHeight()
|
|
1009
|
-
}
|
|
1010
|
-
const buffer = await jimp
|
|
1011
|
-
.quality(quality)
|
|
1012
|
-
.resize(width, AUTO, RESIZE_BEZIER)
|
|
1013
|
-
.getBufferAsync(MIME_JPEG)
|
|
1014
|
-
return {
|
|
1015
|
-
buffer,
|
|
1016
|
-
original: dimensions
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
else {
|
|
1020
|
-
throw new Boom('No image processing library available')
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
|
|
1025
|
-
.replace(/\+/g, '-')
|
|
1026
|
-
.replace(/\//g, '_')
|
|
1027
|
-
.replace(/\=+$/, '')))
|
|
1028
|
-
|
|
1029
|
-
const generateProfilePicture = async (mediaUpload, dimensions) => {
|
|
1030
|
-
let buffer
|
|
1031
|
-
|
|
1032
|
-
const { width: w = 640, height: h = 640 } = dimensions || {}
|
|
1033
|
-
|
|
1034
|
-
if (Buffer.isBuffer(mediaUpload)) {
|
|
1035
|
-
buffer = mediaUpload
|
|
1036
|
-
}
|
|
1037
|
-
else {
|
|
1038
|
-
|
|
1039
|
-
const { stream } = await getStream(mediaUpload)
|
|
1040
|
-
|
|
1041
|
-
buffer = await toBuffer(stream)
|
|
1042
|
-
}
|
|
1043
|
-
const lib = await getImageProcessingLibrary()
|
|
1044
|
-
|
|
1045
|
-
let img
|
|
1046
|
-
|
|
1047
|
-
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
1048
|
-
img = lib.sharp
|
|
1049
|
-
.default(buffer)
|
|
1050
|
-
.resize(w, h)
|
|
1051
|
-
.jpeg({
|
|
1052
|
-
quality: 50
|
|
1053
|
-
}).toBuffer()
|
|
1054
|
-
}
|
|
1055
|
-
else if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
|
1056
|
-
const jimp = await lib.jimp.read(buffer)
|
|
1057
|
-
const min = Math.min(jimp.width, jimp.height)
|
|
1058
|
-
const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min })
|
|
1059
|
-
img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 })
|
|
1060
|
-
}
|
|
1061
|
-
else {
|
|
1062
|
-
throw new Boom('No image processing library available');
|
|
1063
|
-
}
|
|
1064
|
-
return {
|
|
1065
|
-
img: await img
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
const mediaMessageSHA256B64 = (message) => {
|
|
1071
|
-
const media = Object.values(message)[0]
|
|
1072
|
-
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64')
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
async function getAudioDuration(buffer) {
|
|
1076
|
-
const options = {
|
|
1077
|
-
duration: true
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
let metadata
|
|
1081
|
-
|
|
1082
|
-
if (Buffer.isBuffer(buffer)) {
|
|
1083
|
-
metadata = await parseBuffer(buffer, undefined, options)
|
|
1084
|
-
}
|
|
1085
|
-
else if (typeof buffer === 'string') {
|
|
1086
|
-
metadata = await parseFile(buffer, options)
|
|
1087
|
-
}
|
|
1088
|
-
else {
|
|
1089
|
-
metadata = await parseStream(buffer, undefined, options)
|
|
1090
|
-
}
|
|
1091
|
-
return metadata.format?.duration
|
|
1092
|
-
}
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
async function getAudioWaveform(buffer, logger) {
|
|
1098
|
-
try {
|
|
1099
|
-
const { default: decoder } = await eval('import(\'audio-decode\')')
|
|
1100
|
-
|
|
1101
|
-
let audioData
|
|
1102
|
-
|
|
1103
|
-
if (Buffer.isBuffer(buffer)) {
|
|
1104
|
-
audioData = buffer
|
|
1105
|
-
}
|
|
1106
|
-
else if (typeof buffer === 'string') {
|
|
1107
|
-
const rStream = createReadStream(buffer)
|
|
1108
|
-
audioData = await toBuffer(rStream)
|
|
1109
|
-
}
|
|
1110
|
-
else {
|
|
1111
|
-
audioData = await toBuffer(buffer)
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
const audioBuffer = await decoder(audioData)
|
|
1115
|
-
const rawData = audioBuffer.getChannelData(0)
|
|
1116
|
-
const samples = 64
|
|
1117
|
-
const blockSize = Math.floor(rawData.length / samples)
|
|
1118
|
-
const filteredData = []
|
|
1119
|
-
|
|
1120
|
-
for (let i = 0; i < samples; i++) {
|
|
1121
|
-
const blockStart = blockSize * i
|
|
1122
|
-
let sum = 0
|
|
1123
|
-
for (let j = 0; j < blockSize; j++) {
|
|
1124
|
-
sum = sum + Math.abs(rawData[blockStart + j])
|
|
1125
|
-
}
|
|
1126
|
-
filteredData.push(sum / blockSize)
|
|
1127
|
-
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
const multiplier = Math.pow(Math.max(...filteredData), -1)
|
|
1131
|
-
const normalizedData = filteredData.map((n) => n * multiplier)
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)))
|
|
1135
|
-
return waveform
|
|
1136
|
-
}
|
|
1137
|
-
catch (e) {
|
|
1138
|
-
logger?.debug('Failed to generate waveform: ' + e)
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
|
|
1142
|
-
const toReadable = (buffer) => {
|
|
1143
|
-
const readable = new Readable({ read: () => { } })
|
|
1144
|
-
readable.push(buffer)
|
|
1145
|
-
readable.push(null)
|
|
1146
|
-
return readable
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
const toBuffer = async (stream) => {
|
|
1150
|
-
const chunks = []
|
|
1151
|
-
for await (const chunk of stream) {
|
|
1152
|
-
chunks.push(chunk)
|
|
1153
|
-
}
|
|
1154
|
-
stream.destroy()
|
|
1155
|
-
return Buffer.concat(chunks)
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
const getStream = async (item, opts) => {
|
|
1159
|
-
if (Buffer.isBuffer(item)) {
|
|
1160
|
-
return { stream: toReadable(item), type: 'buffer' }
|
|
1161
|
-
}
|
|
1162
|
-
|
|
1163
|
-
if ('stream' in item) {
|
|
1164
|
-
return { stream: item.stream, type: 'readable' }
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
const urlStr = item.url.toString()
|
|
1168
|
-
|
|
1169
|
-
if (urlStr.startsWith('data:')) {
|
|
1170
|
-
const buffer = Buffer.from(urlStr.split(',')[1], 'base64')
|
|
1171
|
-
return { stream: await toReadable(buffer), type: 'buffer' }
|
|
1172
|
-
}
|
|
1173
|
-
|
|
1174
|
-
if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
|
|
1175
|
-
return { stream: await getHttpStream(item.url, opts), type: 'remote' }
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
return { stream: createReadStream(item.url), type: 'file' }
|
|
1179
|
-
}
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
async function generateThumbnail(file, mediaType, options) {
|
|
1183
|
-
let thumbnail
|
|
1184
|
-
let originalImageDimensions
|
|
1185
|
-
|
|
1186
|
-
if (mediaType === 'image') {
|
|
1187
|
-
const { buffer, original } = await extractImageThumb(file)
|
|
1188
|
-
|
|
1189
|
-
thumbnail = buffer.toString('base64')
|
|
1190
|
-
|
|
1191
|
-
if (original.width && original.height) {
|
|
1192
|
-
originalImageDimensions = {
|
|
1193
|
-
width: original.width,
|
|
1194
|
-
height: original.height
|
|
1195
|
-
}
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
else if (mediaType === 'video') {
|
|
1199
|
-
const imgFilename = join(getTmpFilesDirectory(), generateMessageID() + '.jpg')
|
|
1200
|
-
try {
|
|
1201
|
-
await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 })
|
|
1202
|
-
const buff = await promises.readFile(imgFilename)
|
|
1203
|
-
|
|
1204
|
-
thumbnail = buff.toString('base64')
|
|
1205
|
-
|
|
1206
|
-
await promises.unlink(imgFilename)
|
|
1207
|
-
}
|
|
1208
|
-
catch (err) {
|
|
1209
|
-
options.logger?.debug('could not generate video thumb: ' + err)
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1212
|
-
return {
|
|
1213
|
-
thumbnail,
|
|
1214
|
-
originalImageDimensions
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
const getHttpStream = async (url, options = {}) => {
|
|
1219
|
-
const response = await fetch(url.toString(), {
|
|
1220
|
-
dispatcher: options.dispatcher,
|
|
1221
|
-
method: 'GET',
|
|
1222
|
-
headers: options.headers
|
|
1223
|
-
})
|
|
1224
|
-
|
|
1225
|
-
if (!response.ok) {
|
|
1226
|
-
throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } })
|
|
1227
|
-
}
|
|
1228
|
-
|
|
1229
|
-
return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body)
|
|
1230
|
-
}
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
1307
|
-
const { stream, type } = await getStream(media, opts)
|
|
1308
|
-
|
|
1309
|
-
logger?.debug('fetched media stream')
|
|
1310
|
-
|
|
1311
|
-
const mediaKey = randomBytes(32)
|
|
1312
|
-
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
|
|
1313
|
-
const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageID() + '-enc')
|
|
1314
|
-
const encFileWriteStream = createWriteStream(encFilePath)
|
|
1315
|
-
|
|
1316
|
-
let originalFileStream;
|
|
1317
|
-
let originalFilePath
|
|
1318
|
-
|
|
1319
|
-
if (saveOriginalFileIfRequired) {
|
|
1320
|
-
originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageID() + '-original')
|
|
1321
|
-
originalFileStream = createWriteStream(originalFilePath)
|
|
1322
|
-
}
|
|
1323
|
-
|
|
1324
|
-
let fileLength = 0
|
|
1325
|
-
|
|
1326
|
-
const aes = createCipheriv('aes-256-cbc', cipherKey, iv)
|
|
1327
|
-
const hmac = createHmac('sha256', macKey).update(iv)
|
|
1328
|
-
const sha256Plain = createHash('sha256');
|
|
1329
|
-
const sha256Enc = createHash('sha256')
|
|
1330
|
-
|
|
1331
|
-
const onChunk = async (buff) => {
|
|
1332
|
-
sha256Enc.update(buff)
|
|
1333
|
-
hmac.update(buff)
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
if (!encFileWriteStream.write(buff)) {
|
|
1337
|
-
await once(encFileWriteStream, 'drain')
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
|
|
1341
|
-
try {
|
|
1342
|
-
for await (const data of stream) {
|
|
1343
|
-
fileLength += data.length
|
|
1344
|
-
|
|
1345
|
-
if (type === 'remote' &&
|
|
1346
|
-
opts?.maxContentLength &&
|
|
1347
|
-
fileLength + data.length > opts.maxContentLength) {
|
|
1348
|
-
throw new Boom(`content length exceeded when encrypting "${type}"`, {
|
|
1349
|
-
data: { media, type }
|
|
1350
|
-
})
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
if (originalFileStream) {
|
|
1354
|
-
if (!originalFileStream.write(data)) {
|
|
1355
|
-
await once(originalFileStream, 'drain')
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
sha256Plain.update(data)
|
|
1360
|
-
|
|
1361
|
-
await onChunk(aes.update(data))
|
|
1362
|
-
}
|
|
1363
|
-
|
|
1364
|
-
await onChunk(aes.final())
|
|
1365
|
-
const mac = hmac.digest().slice(0, 10)
|
|
1366
|
-
|
|
1367
|
-
sha256Enc.update(mac)
|
|
1368
|
-
|
|
1369
|
-
const fileSha256 = sha256Plain.digest()
|
|
1370
|
-
const fileEncSha256 = sha256Enc.digest()
|
|
1371
|
-
|
|
1372
|
-
encFileWriteStream.write(mac)
|
|
1373
|
-
|
|
1374
|
-
const encFinishPromise = once(encFileWriteStream, 'finish')
|
|
1375
|
-
const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve()
|
|
1376
|
-
|
|
1377
|
-
encFileWriteStream.end()
|
|
1378
|
-
originalFileStream?.end?.()
|
|
1379
|
-
stream.destroy()
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
await encFinishPromise
|
|
1384
|
-
await originalFinishPromise
|
|
1385
|
-
|
|
1386
|
-
logger?.debug('encrypted data successfully')
|
|
1387
|
-
|
|
1388
|
-
return {
|
|
1389
|
-
mediaKey,
|
|
1390
|
-
originalFilePath,
|
|
1391
|
-
encFilePath,
|
|
1392
|
-
mac,
|
|
1393
|
-
fileEncSha256,
|
|
1394
|
-
fileSha256,
|
|
1395
|
-
fileLength
|
|
1396
|
-
}
|
|
1397
|
-
}
|
|
1398
|
-
catch (error) {
|
|
1399
|
-
|
|
1400
|
-
encFileWriteStream.destroy()
|
|
1401
|
-
originalFileStream?.destroy?.()
|
|
1402
|
-
aes.destroy()
|
|
1403
|
-
hmac.destroy()
|
|
1404
|
-
sha256Plain.destroy()
|
|
1405
|
-
sha256Enc.destroy()
|
|
1406
|
-
stream.destroy()
|
|
1407
|
-
|
|
1408
|
-
try {
|
|
1409
|
-
await promises.unlink(encFilePath)
|
|
1410
|
-
|
|
1411
|
-
if (originalFilePath) {
|
|
1412
|
-
await promises.unlink(originalFilePath)
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
catch (err) {
|
|
1416
|
-
logger?.error({ err }, 'failed deleting tmp files')
|
|
1417
|
-
}
|
|
1418
|
-
throw error
|
|
1419
|
-
}
|
|
1420
|
-
}
|
|
1421
|
-
|
|
1422
|
-
const DEF_HOST = 'mmg.whatsapp.net'
|
|
1423
|
-
|
|
1424
|
-
const AES_CHUNK_SIZE = 16
|
|
1425
|
-
|
|
1426
|
-
const toSmallestChunkSize = (num) => {
|
|
1427
|
-
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
|
|
1428
|
-
}
|
|
1429
|
-
const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`
|
|
1430
|
-
|
|
1431
|
-
const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
1432
|
-
const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/')
|
|
1433
|
-
const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath)
|
|
1434
|
-
|
|
1435
|
-
if (!downloadUrl) {
|
|
1436
|
-
throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 })
|
|
1437
|
-
}
|
|
1438
|
-
|
|
1439
|
-
const keys = await getMediaKeys(mediaKey, type)
|
|
1440
|
-
return downloadEncryptedContent(downloadUrl, keys, opts)
|
|
1441
|
-
}
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
1448
|
-
let bytesFetched = 0
|
|
1449
|
-
let startChunk = 0
|
|
1450
|
-
let firstBlockIsIV = false
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
if (startByte) {
|
|
1454
|
-
const chunk = toSmallestChunkSize(startByte || 0)
|
|
1455
|
-
|
|
1456
|
-
if (chunk) {
|
|
1457
|
-
startChunk = chunk - AES_CHUNK_SIZE
|
|
1458
|
-
bytesFetched = chunk
|
|
1459
|
-
firstBlockIsIV = true
|
|
1460
|
-
}
|
|
1461
|
-
}
|
|
1462
|
-
|
|
1463
|
-
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
|
1464
|
-
const headersInit = options?.headers ? options.headers : undefined
|
|
1465
|
-
const headers = {
|
|
1466
|
-
...(headersInit
|
|
1467
|
-
? Array.isArray(headersInit)
|
|
1468
|
-
? Object.fromEntries(headersInit)
|
|
1469
|
-
: headersInit
|
|
1470
|
-
: {}),
|
|
1471
|
-
Origin: DEFAULT_ORIGIN
|
|
1472
|
-
}
|
|
1473
|
-
|
|
1474
|
-
if (startChunk || endChunk) {
|
|
1475
|
-
headers.Range = `bytes=${startChunk}-`
|
|
1476
|
-
|
|
1477
|
-
if (endChunk) {
|
|
1478
|
-
headers.Range += endChunk
|
|
1479
|
-
}
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
const fetched = await getHttpStream(downloadUrl, {
|
|
1484
|
-
...(options || {}),
|
|
1485
|
-
headers
|
|
1486
|
-
})
|
|
1487
|
-
|
|
1488
|
-
let remainingBytes = Buffer.from([])
|
|
1489
|
-
let aes
|
|
1490
|
-
|
|
1491
|
-
const pushBytes = (bytes, push) => {
|
|
1492
|
-
if (startByte || endByte) {
|
|
1493
|
-
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
|
|
1494
|
-
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
|
|
1495
|
-
|
|
1496
|
-
push(bytes.slice(start, end))
|
|
1497
|
-
bytesFetched += bytes.length
|
|
1498
|
-
}
|
|
1499
|
-
else {
|
|
1500
|
-
push(bytes)
|
|
1501
|
-
}
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
const output = new Transform({
|
|
1505
|
-
transform(chunk, _, callback) {
|
|
1506
|
-
let data = Buffer.concat([remainingBytes, chunk])
|
|
1507
|
-
|
|
1508
|
-
const decryptLength = toSmallestChunkSize(data.length)
|
|
1509
|
-
|
|
1510
|
-
remainingBytes = data.slice(decryptLength)
|
|
1511
|
-
data = data.slice(0, decryptLength)
|
|
1512
|
-
|
|
1513
|
-
if (!aes) {
|
|
1514
|
-
let ivValue = iv
|
|
1515
|
-
|
|
1516
|
-
if (firstBlockIsIV) {
|
|
1517
|
-
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
|
1518
|
-
data = data.slice(AES_CHUNK_SIZE)
|
|
1519
|
-
}
|
|
1520
|
-
|
|
1521
|
-
aes = createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
if (endByte) {
|
|
1526
|
-
aes.setAutoPadding(false)
|
|
1527
|
-
}
|
|
1528
|
-
}
|
|
1529
|
-
try {
|
|
1530
|
-
pushBytes(aes.update(data), b => this.push(b))
|
|
1531
|
-
callback()
|
|
1532
|
-
}
|
|
1533
|
-
catch (error) {
|
|
1534
|
-
callback(error)
|
|
1535
|
-
}
|
|
1536
|
-
},
|
|
1537
|
-
final(callback) {
|
|
1538
|
-
try {
|
|
1539
|
-
pushBytes(aes.final(), b => this.push(b))
|
|
1540
|
-
callback()
|
|
1541
|
-
}
|
|
1542
|
-
catch (error) {
|
|
1543
|
-
callback(error)
|
|
1544
|
-
}
|
|
1545
|
-
}
|
|
1546
|
-
})
|
|
1547
|
-
|
|
1548
|
-
return fetched.pipe(output, { end: true })
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
function extensionForMediaMessage(message) {
|
|
1552
|
-
const getExtension = (mimetype) => mimetype.split('')[0].split('/')[1]
|
|
1553
|
-
const type = Object.keys(message)[0]
|
|
1554
|
-
let extension
|
|
1555
|
-
if (type === 'locationMessage' ||
|
|
1556
|
-
type === 'liveLocationMessage' ||
|
|
1557
|
-
type === 'productMessage') {
|
|
1558
|
-
extension = '.jpeg'
|
|
1559
|
-
}
|
|
1560
|
-
else {
|
|
1561
|
-
const messageContent = message[type]
|
|
1562
|
-
extension = getExtension(messageContent.mimetype)
|
|
1563
|
-
}
|
|
1564
|
-
return extension
|
|
1565
|
-
}
|
|
1566
|
-
|
|
1567
|
-
const isNodeRuntime = () => {
|
|
1568
|
-
return (typeof process !== 'undefined' &&
|
|
1569
|
-
process.versions?.node !== null &&
|
|
1570
|
-
typeof process.versions.bun === 'undefined' &&
|
|
1571
|
-
typeof globalThis.Deno === 'undefined')
|
|
1572
|
-
}
|
|
1573
|
-
|
|
1574
|
-
const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
|
|
1575
|
-
if (redirectCount > 5) {
|
|
1576
|
-
throw new Error('Too many redirects')
|
|
1577
|
-
}
|
|
1578
|
-
|
|
1579
|
-
const parsedUrl = new URL(url)
|
|
1580
|
-
const httpModule = parsedUrl.protocol === 'https:' ? require('https') : require('http')
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
const fileStats = await promises.stat(filePath)
|
|
1584
|
-
const fileSize = fileStats.size
|
|
1585
|
-
|
|
1586
|
-
return new Promise((resolve, reject) => {
|
|
1587
|
-
const req = httpModule.request({
|
|
1588
|
-
hostname: parsedUrl.hostname,
|
|
1589
|
-
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
|
1590
|
-
path: parsedUrl.pathname + parsedUrl.search,
|
|
1591
|
-
method: 'POST',
|
|
1592
|
-
headers: {
|
|
1593
|
-
...headers,
|
|
1594
|
-
'Content-Length': fileSize
|
|
1595
|
-
},
|
|
1596
|
-
agent,
|
|
1597
|
-
timeout: timeoutMs
|
|
1598
|
-
}, res => {
|
|
1599
|
-
|
|
1600
|
-
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
1601
|
-
res.resume()
|
|
1602
|
-
|
|
1603
|
-
const newUrl = new URL(res.headers.location, url).toString()
|
|
1604
|
-
|
|
1605
|
-
resolve(uploadWithNodeHttp({
|
|
1606
|
-
url: newUrl,
|
|
1607
|
-
filePath,
|
|
1608
|
-
headers,
|
|
1609
|
-
timeoutMs,
|
|
1610
|
-
agent
|
|
1611
|
-
}, redirectCount + 1))
|
|
1612
|
-
return
|
|
1613
|
-
}
|
|
1614
|
-
|
|
1615
|
-
let body = ''
|
|
1616
|
-
|
|
1617
|
-
res.on('data', chunk => (body += chunk))
|
|
1618
|
-
res.on('end', () => {
|
|
1619
|
-
try {
|
|
1620
|
-
resolve(JSON.parse(body))
|
|
1621
|
-
}
|
|
1622
|
-
catch {
|
|
1623
|
-
resolve(undefined)
|
|
1624
|
-
}
|
|
1625
|
-
})
|
|
1626
|
-
})
|
|
1627
|
-
|
|
1628
|
-
req.on('error', reject)
|
|
1629
|
-
req.on('timeout', () => {
|
|
1630
|
-
req.destroy()
|
|
1631
|
-
reject(new Error('Upload timeout'))
|
|
1632
|
-
})
|
|
1633
|
-
|
|
1634
|
-
const stream = createReadStream(filePath)
|
|
1635
|
-
|
|
1636
|
-
stream.pipe(req)
|
|
1637
|
-
stream.on('error', err => {
|
|
1638
|
-
req.destroy()
|
|
1639
|
-
reject(err)
|
|
1640
|
-
})
|
|
1641
|
-
})
|
|
1642
|
-
}
|
|
1643
|
-
|
|
1644
|
-
const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
|
|
1645
|
-
|
|
1646
|
-
const nodeStream = createReadStream(filePath)
|
|
1647
|
-
const webStream = Readable.toWeb(nodeStream)
|
|
1648
|
-
const response = await fetch(url, {
|
|
1649
|
-
dispatcher: agent,
|
|
1650
|
-
method: 'POST',
|
|
1651
|
-
body: webStream,
|
|
1652
|
-
headers,
|
|
1653
|
-
duplex: 'half',
|
|
1654
|
-
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
1655
|
-
})
|
|
1656
|
-
|
|
1657
|
-
try {
|
|
1658
|
-
return (await response.json())
|
|
1659
|
-
}
|
|
1660
|
-
catch {
|
|
1661
|
-
return undefined
|
|
1662
|
-
}
|
|
1663
|
-
}
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
const uploadMedia = async (params, logger) => {
|
|
1683
|
-
if (isNodeRuntime()) {
|
|
1684
|
-
logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)')
|
|
1685
|
-
return uploadWithNodeHttp(params)
|
|
1686
|
-
}
|
|
1687
|
-
else {
|
|
1688
|
-
logger?.debug('Using web-standard Fetch API for upload');
|
|
1689
|
-
return uploadWithFetch(params)
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
|
|
1693
|
-
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
1694
|
-
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
|
1695
|
-
|
|
1696
|
-
let uploadInfo = await refreshMediaConn(false)
|
|
1697
|
-
let urls
|
|
1698
|
-
|
|
1699
|
-
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
|
1700
|
-
|
|
1701
|
-
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
const customHeaders = (() => {
|
|
1705
|
-
const hdrs = options?.headers;
|
|
1706
|
-
if (!hdrs)
|
|
1707
|
-
return {};
|
|
1708
|
-
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs
|
|
1709
|
-
})()
|
|
1710
|
-
|
|
1711
|
-
const headers = {
|
|
1712
|
-
...customHeaders,
|
|
1713
|
-
'Content-Type': 'application/octet-stream',
|
|
1714
|
-
Origin: DEFAULT_ORIGIN
|
|
1715
|
-
}
|
|
1716
|
-
|
|
1717
|
-
for (const { hostname } of hosts) {
|
|
1718
|
-
logger.debug(`uploading to "${hostname}"`)
|
|
1719
|
-
|
|
1720
|
-
const auth = encodeURIComponent(uploadInfo.auth)
|
|
1721
|
-
const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
|
|
1722
|
-
if (mediaType === 'sticker-pack') { try { if (typeof media !== 'undefined') media = '/mms/sticker'; } catch (_) {} }
|
|
1723
|
-
if (mediaType === 'sticker-pack') { if (typeof media !== 'undefined') media = '/mms/sticker'; if (typeof mediaPath !== 'undefined') mediaPath = '/mms/sticker'; }
|
|
1724
|
-
if (mediaType === 'thumbnail-sticker-pack') { if (typeof media !== 'undefined') media = '/mms/image'; if (typeof mediaPath !== 'undefined') mediaPath = '/mms/image'; }
|
|
1725
|
-
|
|
1726
|
-
let result
|
|
1727
|
-
|
|
1728
|
-
try {
|
|
1729
|
-
result = await uploadMedia({
|
|
1730
|
-
url,
|
|
1731
|
-
filePath,
|
|
1732
|
-
headers,
|
|
1733
|
-
timeoutMs,
|
|
1734
|
-
agent: fetchAgent
|
|
1735
|
-
}, logger);
|
|
1736
|
-
if (result?.url || result?.direct_path) {
|
|
1737
|
-
urls = {
|
|
1738
|
-
mediaUrl: result.url,
|
|
1739
|
-
directPath: result.direct_path,
|
|
1740
|
-
meta_hmac: result.meta_hmac,
|
|
1741
|
-
fbid: result.fbid,
|
|
1742
|
-
ts: result.ts
|
|
1743
|
-
}
|
|
1744
|
-
break
|
|
1745
|
-
}
|
|
1746
|
-
else {
|
|
1747
|
-
uploadInfo = await refreshMediaConn(true)
|
|
1748
|
-
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
|
1749
|
-
}
|
|
1750
|
-
}
|
|
1751
|
-
catch (error) {
|
|
1752
|
-
const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
|
|
1753
|
-
logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`)
|
|
1754
|
-
}
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
if (!urls) {
|
|
1758
|
-
throw new Boom('Media upload failed on all hosts', { statusCode: 500 })
|
|
1759
|
-
}
|
|
1760
|
-
|
|
1761
|
-
return urls
|
|
1762
|
-
}
|
|
1763
|
-
}
|
|
1764
|
-
|
|
1765
|
-
const getMediaRetryKey = (mediaKey) => {
|
|
1766
|
-
return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
|
|
1767
|
-
}
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
|
|
1772
|
-
const recp = { stanzaId: key.id }
|
|
1773
|
-
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
|
|
1774
|
-
const iv = randomBytes(12)
|
|
1775
|
-
const retryKey = await getMediaRetryKey(mediaKey)
|
|
1776
|
-
const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id))
|
|
1777
|
-
const req = {
|
|
1778
|
-
tag: 'receipt',
|
|
1779
|
-
attrs: {
|
|
1780
|
-
id: key.id,
|
|
1781
|
-
to: jidNormalizedUser(meId),
|
|
1782
|
-
type: 'server-error'
|
|
1783
|
-
},
|
|
1784
|
-
content: [
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
{
|
|
1789
|
-
tag: 'encrypt',
|
|
1790
|
-
attrs: {},
|
|
1791
|
-
content: [
|
|
1792
|
-
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
1793
|
-
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
1794
|
-
]
|
|
1795
|
-
},
|
|
1796
|
-
{
|
|
1797
|
-
tag: 'rmr',
|
|
1798
|
-
attrs: {
|
|
1799
|
-
jid: key.remoteJid,
|
|
1800
|
-
from_me: (!!key.fromMe).toString(),
|
|
1801
|
-
participant: key.participant || undefined
|
|
1802
|
-
}
|
|
1803
|
-
}
|
|
1804
|
-
]
|
|
1805
|
-
}
|
|
1806
|
-
return req
|
|
1807
|
-
}
|
|
1808
|
-
|
|
1809
|
-
const decodeMediaRetryNode = (node) => {
|
|
1810
|
-
const rmrNode = getBinaryNodeChild(node, 'rmr')
|
|
1811
|
-
const event = {
|
|
1812
|
-
key: {
|
|
1813
|
-
id: node.attrs.id,
|
|
1814
|
-
remoteJid: rmrNode.attrs.jid,
|
|
1815
|
-
fromMe: rmrNode.attrs.from_me === 'true',
|
|
1816
|
-
participant: rmrNode.attrs.participant
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
const errorNode = getBinaryNodeChild(node, 'error')
|
|
1820
|
-
if (errorNode) {
|
|
1821
|
-
const errorCode = +errorNode.attrs.code
|
|
1822
|
-
event.error = new Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(errorCode) })
|
|
1823
|
-
}
|
|
1824
|
-
else {
|
|
1825
|
-
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
|
|
1826
|
-
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
|
|
1827
|
-
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
|
|
1828
|
-
if (ciphertext && iv) {
|
|
1829
|
-
event.media = { ciphertext, iv }
|
|
1830
|
-
}
|
|
1831
|
-
else {
|
|
1832
|
-
event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
|
1833
|
-
}
|
|
1834
|
-
}
|
|
1835
|
-
return event
|
|
1836
|
-
}
|
|
1837
|
-
|
|
1838
|
-
const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
1839
|
-
const retryKey = await getMediaRetryKey(mediaKey)
|
|
1840
|
-
const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
|
|
1841
|
-
return proto.MediaRetryNotification.decode(plaintext)
|
|
1842
|
-
}
|
|
1843
|
-
|
|
1844
|
-
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code]
|
|
1845
|
-
|
|
1846
|
-
const MEDIA_RETRY_STATUS_MAP = {
|
|
1847
|
-
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
1848
|
-
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
1849
|
-
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
1850
|
-
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
|
|
1851
|
-
}
|
|
1852
|
-
|
|
1853
|
-
module.exports = {
|
|
1854
|
-
hkdfInfoKey,
|
|
1855
|
-
getMediaKeys,
|
|
1856
|
-
extractVideoThumb,
|
|
1857
|
-
extractImageThumb,
|
|
1858
|
-
encodeBase64EncodedStringForUpload,
|
|
1859
|
-
generateProfilePicture,
|
|
1860
|
-
mediaMessageSHA256B64,
|
|
1861
|
-
getAudioDuration,
|
|
1862
|
-
getAudioWaveform,
|
|
1863
|
-
toReadable,
|
|
1864
|
-
toBuffer,
|
|
1865
|
-
getStream,
|
|
1866
|
-
generateThumbnail,
|
|
1867
|
-
getHttpStream,
|
|
1868
|
-
|
|
1869
|
-
encryptedStream,
|
|
1870
|
-
getUrlFromDirectPath,
|
|
1871
|
-
downloadContentFromMessage,
|
|
1872
|
-
downloadEncryptedContent,
|
|
1873
|
-
extensionForMediaMessage,
|
|
1874
|
-
uploadWithNodeHttp,
|
|
1875
|
-
getRawMediaUploadData,
|
|
1876
|
-
getWAUploadToServer,
|
|
1877
|
-
getMediaRetryKey,
|
|
1878
|
-
encryptMediaRetryRequest,
|
|
1879
|
-
decodeMediaRetryNode,
|
|
1880
|
-
decryptMediaRetryData,
|
|
1881
|
-
getStatusCodeForMediaRetry,
|
|
1882
|
-
MEDIA_RETRY_STATUS_MAP
|
|
1883
|
-
}
|
|
1884
|
-
return module.exports;
|
|
1885
|
-
})();
|
|
1886
|
-
for (const key of Object.keys(__kageModule73)) {
|
|
1887
|
-
if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule73[key]});
|
|
1888
|
-
}
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
const __kageModule177 = (() => {
|
|
1892
|
-
const module = { exports: {} }; const exports = module.exports;
|
|
1893
|
-
"use strict";
|
|
1894
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
1895
|
-
if (k2 === undefined) k2 = k;
|
|
1896
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
1897
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
1898
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
1899
|
-
}
|
|
1900
|
-
Object.defineProperty(o, k2, desc);
|
|
1901
|
-
}) : (function(o, m, k, k2) {
|
|
1902
|
-
if (k2 === undefined) k2 = k;
|
|
1903
|
-
o[k2] = m[k];
|
|
1904
|
-
}));
|
|
1905
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
1906
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
1907
|
-
}) : function(o, v) {
|
|
1908
|
-
o["default"] = v;
|
|
1909
|
-
});
|
|
1910
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
1911
|
-
var ownKeys = function(o) {
|
|
1912
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
1913
|
-
var ar = [];
|
|
1914
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
1915
|
-
return ar;
|
|
1916
|
-
};
|
|
1917
|
-
return ownKeys(o);
|
|
1918
|
-
};
|
|
1919
|
-
return function (mod) {
|
|
1920
|
-
if (mod && mod.__esModule) return mod;
|
|
1921
|
-
var result = {};
|
|
1922
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
1923
|
-
__setModuleDefault(result, mod);
|
|
1924
|
-
return result;
|
|
1925
|
-
};
|
|
1926
|
-
})();
|
|
1927
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1928
36
|
exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.uploadWithNodeHttp = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.DEF_MEDIA_HOST = exports.encryptedStream = exports.getHttpStream = exports.getStream = exports.toBuffer = exports.toReadable = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.extractVideoThumb = exports.getRawMediaUploadData = exports.hkdfInfoKey = exports.getImageProcessingLibrary = void 0;
|
|
1929
37
|
exports.getMediaKeys = getMediaKeys;
|
|
@@ -2722,10 +830,3 @@ const MEDIA_RETRY_STATUS_MAP = {
|
|
|
2722
830
|
[index_js_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
2723
831
|
[index_js_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
2724
832
|
};
|
|
2725
|
-
|
|
2726
|
-
return module.exports;
|
|
2727
|
-
})();
|
|
2728
|
-
for (const key of Object.keys(__kageModule177)) {
|
|
2729
|
-
if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule177[key]});
|
|
2730
|
-
}
|
|
2731
|
-
Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule177, configurable:true});
|