dcodeindra-baileyspro 2.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2534 -0
- package/WAProto/Adv/Adv.d.ts +518 -0
- package/WAProto/Adv/Adv.js +1734 -0
- package/WAProto/Adv/Adv.proto +36 -0
- package/WAProto/BotMetadata/BotMetadata.d.ts +5745 -0
- package/WAProto/BotMetadata/BotMetadata.js +16291 -0
- package/WAProto/BotMetadata/BotMetadata.proto +463 -0
- package/WAProto/Cert/Cert.d.ts +497 -0
- package/WAProto/Cert/Cert.js +1503 -0
- package/WAProto/Cert/Cert.proto +28 -0
- package/WAProto/ChatLockSettings/ChatLockSettings.d.ts +391 -0
- package/WAProto/ChatLockSettings/ChatLockSettings.js +1155 -0
- package/WAProto/ChatLockSettings/ChatLockSettings.proto +7 -0
- package/WAProto/CompanionReg/CompanionReg.d.ts +1055 -0
- package/WAProto/CompanionReg/CompanionReg.js +3532 -0
- package/WAProto/CompanionReg/CompanionReg.proto +89 -0
- package/WAProto/DeviceCapabilities/DeviceCapabilities.d.ts +187 -0
- package/WAProto/DeviceCapabilities/DeviceCapabilities.js +520 -0
- package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +14 -0
- package/WAProto/E2E/E2E.d.ts +28417 -0
- package/WAProto/E2E/E2E.js +98438 -0
- package/WAProto/E2E/E2E.proto +2289 -0
- package/WAProto/Ephemeral/Ephemeral.d.ts +95 -0
- package/WAProto/Ephemeral/Ephemeral.js +269 -0
- package/WAProto/Ephemeral/Ephemeral.proto +6 -0
- package/WAProto/HistorySync/HistorySync.d.ts +40728 -0
- package/WAProto/HistorySync/HistorySync.js +142980 -0
- package/WAProto/HistorySync/HistorySync.proto +207 -0
- package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.d.ts +189 -0
- package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +585 -0
- package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +11 -0
- package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.d.ts +461 -0
- package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +1559 -0
- package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +37 -0
- package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +29294 -0
- package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +101732 -0
- package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +76 -0
- package/WAProto/MmsRetry/MmsRetry.d.ts +200 -0
- package/WAProto/MmsRetry/MmsRetry.js +586 -0
- package/WAProto/MmsRetry/MmsRetry.proto +17 -0
- package/WAProto/Protocol/Protocol.d.ts +218 -0
- package/WAProto/Protocol/Protocol.js +701 -0
- package/WAProto/Protocol/Protocol.proto +20 -0
- package/WAProto/Reporting/Reporting.d.ts +301 -0
- package/WAProto/Reporting/Reporting.js +989 -0
- package/WAProto/Reporting/Reporting.proto +19 -0
- package/WAProto/ServerSync/ServerSync.d.ts +1050 -0
- package/WAProto/ServerSync/ServerSync.js +3176 -0
- package/WAProto/ServerSync/ServerSync.proto +59 -0
- package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.d.ts +1507 -0
- package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +4756 -0
- package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +88 -0
- package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.d.ts +617 -0
- package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1940 -0
- package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +38 -0
- package/WAProto/StatusAttributions/StatusAttributions.d.ts +636 -0
- package/WAProto/StatusAttributions/StatusAttributions.js +2037 -0
- package/WAProto/StatusAttributions/StatusAttributions.proto +61 -0
- package/WAProto/SyncAction/SyncAction.d.ts +7227 -0
- package/WAProto/SyncAction/SyncAction.js +22271 -0
- package/WAProto/SyncAction/SyncAction.proto +423 -0
- package/WAProto/UserPassword/UserPassword.d.ts +298 -0
- package/WAProto/UserPassword/UserPassword.js +898 -0
- package/WAProto/UserPassword/UserPassword.proto +27 -0
- package/WAProto/VnameCert/VnameCert.d.ts +658 -0
- package/WAProto/VnameCert/VnameCert.js +2225 -0
- package/WAProto/VnameCert/VnameCert.proto +60 -0
- package/WAProto/Wa6/Wa6.d.ts +1613 -0
- package/WAProto/Wa6/Wa6.js +6299 -0
- package/WAProto/Wa6/Wa6.proto +229 -0
- package/WAProto/Web/Web.d.ts +31718 -0
- package/WAProto/Web/Web.js +113402 -0
- package/WAProto/Web/Web.proto +545 -0
- package/WAProto/index.d.ts +49 -0
- package/WAProto/index.js +28 -0
- package/WASignalGroup/GroupProtocol.js +1771 -0
- package/WASignalGroup/ciphertext_message.js +10 -0
- package/WASignalGroup/group_cipher.js +103 -0
- package/WASignalGroup/group_session_builder.js +39 -0
- package/WASignalGroup/index.js +5 -0
- package/WASignalGroup/keyhelper.js +17 -0
- package/WASignalGroup/protobufs.js +2 -0
- package/WASignalGroup/queue_job.js +64 -0
- package/WASignalGroup/sender_chain_key.js +38 -0
- package/WASignalGroup/sender_key_distribution_message.js +68 -0
- package/WASignalGroup/sender_key_message.js +79 -0
- package/WASignalGroup/sender_key_name.js +59 -0
- package/WASignalGroup/sender_key_record.js +47 -0
- package/WASignalGroup/sender_key_state.js +110 -0
- package/WASignalGroup/sender_message_key.js +30 -0
- package/check-node-version.js +10 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.d.ts +51 -0
- package/lib/Defaults/index.js +108 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
- package/lib/Signal/Group/ciphertext-message.js +19 -0
- package/lib/Signal/Group/group-session-builder.d.ts +17 -0
- package/lib/Signal/Group/group-session-builder.js +72 -0
- package/lib/Signal/Group/group_cipher.d.ts +19 -0
- package/lib/Signal/Group/group_cipher.js +99 -0
- package/lib/Signal/Group/index.d.ts +11 -0
- package/lib/Signal/Group/index.js +61 -0
- package/lib/Signal/Group/keyhelper.d.ts +16 -0
- package/lib/Signal/Group/keyhelper.js +66 -0
- package/lib/Signal/Group/queue-job.d.ts +1 -0
- package/lib/Signal/Group/queue-job.js +64 -0
- package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
- package/lib/Signal/Group/sender-chain-key.js +39 -0
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +71 -0
- package/lib/Signal/Group/sender-key-message.d.ts +19 -0
- package/lib/Signal/Group/sender-key-message.js +73 -0
- package/lib/Signal/Group/sender-key-name.d.ts +19 -0
- package/lib/Signal/Group/sender-key-name.js +59 -0
- package/lib/Signal/Group/sender-key-record.d.ts +32 -0
- package/lib/Signal/Group/sender-key-record.js +53 -0
- package/lib/Signal/Group/sender-key-record.ts +77 -0
- package/lib/Signal/Group/sender-key-state.d.ts +44 -0
- package/lib/Signal/Group/sender-key-state.js +104 -0
- package/lib/Signal/Group/sender-message-key.d.ts +11 -0
- package/lib/Signal/Group/sender-message-key.js +33 -0
- package/lib/Signal/libsignal.d.ts +3 -0
- package/lib/Signal/libsignal.js +153 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/lib/Socket/Client/index.js +18 -0
- package/lib/Socket/Client/types.d.ts +15 -0
- package/lib/Socket/Client/types.js +14 -0
- package/lib/Socket/Client/websocket.d.ts +12 -0
- package/lib/Socket/Client/websocket.js +57 -0
- package/lib/Socket/business.d.ts +181 -0
- package/lib/Socket/business.js +259 -0
- package/lib/Socket/chats.d.ts +95 -0
- package/lib/Socket/chats.js +906 -0
- package/lib/Socket/community.d.ts +131 -0
- package/lib/Socket/community.js +369 -0
- package/lib/Socket/groups.d.ts +122 -0
- package/lib/Socket/groups.js +360 -0
- package/lib/Socket/index.d.ts +183 -0
- package/lib/Socket/index.js +10 -0
- package/lib/Socket/messages-recv.d.ts +170 -0
- package/lib/Socket/messages-recv.js +1074 -0
- package/lib/Socket/messages-send.d.ts +161 -0
- package/lib/Socket/messages-send.js +982 -0
- package/lib/Socket/newsletter.d.ts +140 -0
- package/lib/Socket/newsletter.js +242 -0
- package/lib/Socket/socket.d.ts +43 -0
- package/lib/Socket/socket.js +749 -0
- package/lib/Socket/usync.d.ts +36 -0
- package/lib/Socket/usync.js +71 -0
- package/lib/Store/index.d.ts +4 -0
- package/lib/Store/index.js +20 -0
- package/lib/Store/make-cache-manager-store.d.ts +13 -0
- package/lib/Store/make-cache-manager-store.js +77 -0
- package/lib/Store/make-in-memory-store.d.ts +117 -0
- package/lib/Store/make-in-memory-store.js +420 -0
- package/lib/Store/make-ordered-dictionary.d.ts +12 -0
- package/lib/Store/make-ordered-dictionary.js +83 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +28 -0
- package/lib/Types/Auth.d.ts +103 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.d.ts +13 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.d.ts +115 -0
- package/lib/Types/Chat.js +6 -0
- package/lib/Types/Contact.d.ts +35 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.d.ts +208 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.d.ts +81 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.d.ts +46 -0
- package/lib/Types/Label.js +28 -0
- package/lib/Types/LabelAssociation.d.ts +29 -0
- package/lib/Types/LabelAssociation.js +10 -0
- package/lib/Types/Message.d.ts +480 -0
- package/lib/Types/Message.js +9 -0
- package/lib/Types/MexUpdates.d.ts +9 -0
- package/lib/Types/MexUpdates.js +18 -0
- package/lib/Types/Newsletter.d.ts +92 -0
- package/lib/Types/Newsletter.js +33 -0
- package/lib/Types/Product.d.ts +78 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.d.ts +57 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.d.ts +116 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.d.ts +27 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.d.ts +25 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.d.ts +70 -0
- package/lib/Types/index.js +42 -0
- package/lib/Utils/auth-utils.d.ts +18 -0
- package/lib/Utils/auth-utils.js +198 -0
- package/lib/Utils/baileys-event-stream.d.ts +16 -0
- package/lib/Utils/baileys-event-stream.js +64 -0
- package/lib/Utils/business.d.ts +22 -0
- package/lib/Utils/business.js +243 -0
- package/lib/Utils/chat-utils.d.ts +72 -0
- package/lib/Utils/chat-utils.js +762 -0
- package/lib/Utils/crypto.d.ts +40 -0
- package/lib/Utils/crypto.js +150 -0
- package/lib/Utils/decode-wa-message.d.ts +252 -0
- package/lib/Utils/decode-wa-message.js +232 -0
- package/lib/Utils/event-buffer.d.ts +35 -0
- package/lib/Utils/event-buffer.js +539 -0
- package/lib/Utils/generics.d.ts +96 -0
- package/lib/Utils/generics.js +553 -0
- package/lib/Utils/history.d.ts +29 -0
- package/lib/Utils/history.js +109 -0
- package/lib/Utils/index.d.ts +19 -0
- package/lib/Utils/index.js +35 -0
- package/lib/Utils/link-preview.d.ts +21 -0
- package/lib/Utils/link-preview.js +112 -0
- package/lib/Utils/logger.d.ts +11 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/lt-hash.js +53 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +45 -0
- package/lib/Utils/messages-media.d.ts +104 -0
- package/lib/Utils/messages-media.js +751 -0
- package/lib/Utils/messages.d.ts +80 -0
- package/lib/Utils/messages.js +1741 -0
- package/lib/Utils/noise-handler.d.ts +19 -0
- package/lib/Utils/noise-handler.js +150 -0
- package/lib/Utils/process-message.d.ts +41 -0
- package/lib/Utils/process-message.js +391 -0
- package/lib/Utils/signal.d.ts +33 -0
- package/lib/Utils/signal.js +154 -0
- package/lib/Utils/use-mongo-file-auth-state.d.ts +5 -0
- package/lib/Utils/use-mongo-file-auth-state.js +75 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
- package/lib/Utils/use-multi-file-auth-state.js +123 -0
- package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
- package/lib/Utils/use-single-file-auth-state.js +75 -0
- package/lib/Utils/validate-connection.d.ts +10 -0
- package/lib/Utils/validate-connection.js +174 -0
- package/lib/WABinary/constants.d.ts +27 -0
- package/lib/WABinary/constants.js +45 -0
- package/lib/WABinary/decode.d.ts +6 -0
- package/lib/WABinary/decode.js +255 -0
- package/lib/WABinary/encode.d.ts +2 -0
- package/lib/WABinary/encode.js +243 -0
- package/lib/WABinary/generic-utils.d.ts +16 -0
- package/lib/WABinary/generic-utils.js +125 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.d.ts +34 -0
- package/lib/WABinary/jid-utils.js +73 -0
- package/lib/WABinary/types.d.ts +18 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +16 -0
- package/lib/WAM/BinaryInfo.js +14 -0
- package/lib/WAM/constants.d.ts +39 -0
- package/lib/WAM/constants.js +15362 -0
- package/lib/WAM/encode.d.ts +2 -0
- package/lib/WAM/encode.js +156 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +25 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +60 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +58 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +8 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +26 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/index.d.ts +6 -0
- package/lib/WAUSync/Protocols/index.js +22 -0
- package/lib/WAUSync/USyncQuery.d.ts +28 -0
- package/lib/WAUSync/USyncQuery.js +88 -0
- package/lib/WAUSync/USyncUser.d.ts +12 -0
- package/lib/WAUSync/USyncUser.js +27 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.d.ts +13 -0
- package/lib/index.js +45 -0
- package/package.json +63 -0
|
@@ -0,0 +1,751 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k)
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k] } }
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc)
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k
|
|
11
|
+
o[k2] = m[k]
|
|
12
|
+
}))
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v })
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v
|
|
17
|
+
})
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod
|
|
20
|
+
var result = {}
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
|
|
22
|
+
__setModuleDefault(result, mod)
|
|
23
|
+
return result
|
|
24
|
+
}
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod }
|
|
27
|
+
}
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true })
|
|
29
|
+
const boom_1 = require("@hapi/boom")
|
|
30
|
+
const axios_1 = __importDefault(require("axios"))
|
|
31
|
+
const child_process_1 = require("child_process")
|
|
32
|
+
const Crypto = __importStar(require("crypto"))
|
|
33
|
+
const events_1 = require("events")
|
|
34
|
+
const fs_1 = require("fs")
|
|
35
|
+
const os_1 = require("os")
|
|
36
|
+
const path_1 = require("path")
|
|
37
|
+
const stream_1 = require("stream")
|
|
38
|
+
const WAProto_1 = require("../../WAProto")
|
|
39
|
+
const Defaults_1 = require("../Defaults")
|
|
40
|
+
const WABinary_1 = require("../WABinary")
|
|
41
|
+
const crypto_1 = require("./crypto")
|
|
42
|
+
const generics_1 = require("./generics")
|
|
43
|
+
const getImageProcessingLibrary = async () => {
|
|
44
|
+
const [_jimp, sharp] = await Promise.all([
|
|
45
|
+
(async () => {
|
|
46
|
+
const jimp = await (Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }))
|
|
47
|
+
return jimp
|
|
48
|
+
})(),
|
|
49
|
+
(async () => {
|
|
50
|
+
const sharp = await (Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }))
|
|
51
|
+
return sharp
|
|
52
|
+
})()
|
|
53
|
+
])
|
|
54
|
+
if (sharp) {
|
|
55
|
+
return { sharp }
|
|
56
|
+
}
|
|
57
|
+
const jimp = _jimp?.default || _jimp
|
|
58
|
+
if (jimp) {
|
|
59
|
+
return { jimp }
|
|
60
|
+
}
|
|
61
|
+
throw new boom_1.Boom('No image processing library available')
|
|
62
|
+
}
|
|
63
|
+
const hkdfInfoKey = (type) => {
|
|
64
|
+
const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type]
|
|
65
|
+
return `WhatsApp ${hkdfInfo} Keys`
|
|
66
|
+
}
|
|
67
|
+
/** generates all the keys required to encrypt/decrypt & sign a media message */
|
|
68
|
+
async function getMediaKeys(buffer, mediaType) {
|
|
69
|
+
if (!buffer) {
|
|
70
|
+
throw new boom_1.Boom('Cannot derive from empty media key')
|
|
71
|
+
}
|
|
72
|
+
if (typeof buffer === 'string') {
|
|
73
|
+
buffer = Buffer.from(buffer.replace('data:base64,', ''), 'base64')
|
|
74
|
+
}
|
|
75
|
+
// expand using HKDF to 112 bytes, also pass in the relevant app info
|
|
76
|
+
const expandedMediaKey = await crypto_1.hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
|
|
77
|
+
return {
|
|
78
|
+
iv: expandedMediaKey.slice(0, 16),
|
|
79
|
+
cipherKey: expandedMediaKey.slice(16, 48),
|
|
80
|
+
macKey: expandedMediaKey.slice(48, 80),
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Extracts video thumb using FFMPEG */
|
|
84
|
+
const extractVideoThumb = (videoPath, time = '00:00:00', size = { width: 320 }) => {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const args = [
|
|
87
|
+
'-ss', time,
|
|
88
|
+
'-i', videoPath,
|
|
89
|
+
'-y',
|
|
90
|
+
'-vf', `scale=${size.width}:-1`,
|
|
91
|
+
'-vframes', '1',
|
|
92
|
+
'-f', 'image2',
|
|
93
|
+
'-vcodec', 'mjpeg',
|
|
94
|
+
'pipe:1'
|
|
95
|
+
]
|
|
96
|
+
const ffmpeg = child_process_1.spawn('ffmpeg', args)
|
|
97
|
+
const chunks = []
|
|
98
|
+
let errorOutput = ''
|
|
99
|
+
ffmpeg.stdout.on('data', chunk => chunks.push(chunk))
|
|
100
|
+
ffmpeg.stderr.on('data', data => {
|
|
101
|
+
errorOutput += data.toString()
|
|
102
|
+
})
|
|
103
|
+
ffmpeg.on('error', reject)
|
|
104
|
+
ffmpeg.on('close', code => {
|
|
105
|
+
if (code === 0) return resolve(Buffer.concat(chunks))
|
|
106
|
+
reject(new Error(`ffmpeg exited with code ${code}\n${errorOutput}`))
|
|
107
|
+
})
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
const extractImageThumb = async (bufferOrFilePath, width = 32, quality = 50) => {
|
|
111
|
+
if (typeof bufferOrFilePath === "string" && bufferOrFilePath.startsWith("http")) {
|
|
112
|
+
const response = await axios_1.default.get(bufferOrFilePath, { responseType: "arraybuffer" })
|
|
113
|
+
bufferOrFilePath = Buffer.from(response.data)
|
|
114
|
+
}
|
|
115
|
+
if (bufferOrFilePath instanceof stream_1.Readable) {
|
|
116
|
+
bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
|
117
|
+
}
|
|
118
|
+
const lib = await getImageProcessingLibrary()
|
|
119
|
+
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
120
|
+
const img = lib.sharp.default(bufferOrFilePath)
|
|
121
|
+
const dimensions = await img.metadata()
|
|
122
|
+
const buffer = await img
|
|
123
|
+
.resize({
|
|
124
|
+
width,
|
|
125
|
+
height: width,
|
|
126
|
+
fit: 'contain',
|
|
127
|
+
background: { r: 255, g: 255, b: 255, alpha: 0 }
|
|
128
|
+
})
|
|
129
|
+
.jpeg({ quality })
|
|
130
|
+
.toBuffer()
|
|
131
|
+
return {
|
|
132
|
+
buffer,
|
|
133
|
+
original: {
|
|
134
|
+
width: dimensions.width,
|
|
135
|
+
height: dimensions.height,
|
|
136
|
+
},
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
else if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
|
140
|
+
const { read, MIME_JPEG, RESIZE_BEZIER, AUTO } = lib.jimp
|
|
141
|
+
const jimp = await read(bufferOrFilePath)
|
|
142
|
+
const dimensions = {
|
|
143
|
+
width: jimp.getWidth(),
|
|
144
|
+
height: jimp.getHeight()
|
|
145
|
+
}
|
|
146
|
+
const buffer = await jimp
|
|
147
|
+
.quality(quality)
|
|
148
|
+
.resize(width, AUTO, RESIZE_BEZIER)
|
|
149
|
+
.getBufferAsync(MIME_JPEG)
|
|
150
|
+
return {
|
|
151
|
+
buffer,
|
|
152
|
+
original: dimensions
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
throw new boom_1.Boom('No image processing library available')
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
|
|
160
|
+
.replace(/\+/g, '-')
|
|
161
|
+
.replace(/\//g, '_')
|
|
162
|
+
.replace(/\=+$/, '')))
|
|
163
|
+
const generateProfilePicture = async (mediaUpload) => {
|
|
164
|
+
let bufferOrFilePath
|
|
165
|
+
if (Buffer.isBuffer(mediaUpload)) {
|
|
166
|
+
bufferOrFilePath = mediaUpload
|
|
167
|
+
}
|
|
168
|
+
else if ('url' in mediaUpload) {
|
|
169
|
+
bufferOrFilePath = mediaUpload.url.toString()
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
bufferOrFilePath = await toBuffer(mediaUpload.stream)
|
|
173
|
+
}
|
|
174
|
+
const lib = await getImageProcessingLibrary()
|
|
175
|
+
let img
|
|
176
|
+
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
177
|
+
img = await lib.sharp.default(bufferOrFilePath)
|
|
178
|
+
.resize(720, 720, {
|
|
179
|
+
fit: 'inside',
|
|
180
|
+
})
|
|
181
|
+
.jpeg({ quality: 50 })
|
|
182
|
+
.toBuffer()
|
|
183
|
+
}
|
|
184
|
+
else if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
|
|
185
|
+
const { read, MIME_JPEG } = lib.jimp
|
|
186
|
+
const image = await read(bufferOrFilePath)
|
|
187
|
+
const min = image.getWidth()
|
|
188
|
+
const max = image.getHeight()
|
|
189
|
+
const cropped = image.crop(0, 0, min, max)
|
|
190
|
+
img = await cropped.scaleToFit(720, 720).getBufferAsync(MIME_JPEG)
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
throw new boom_1.Boom('No image processing library available')
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
img: await img,
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** gets the SHA256 of the given media message */
|
|
200
|
+
const mediaMessageSHA256B64 = (message) => {
|
|
201
|
+
const media = Object.values(message)[0]
|
|
202
|
+
return (media === null || media === void 0 ? void 0 : media.fileSha256) && Buffer.from(media.fileSha256).toString('base64')
|
|
203
|
+
}
|
|
204
|
+
async function getAudioDuration(buffer) {
|
|
205
|
+
const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')))
|
|
206
|
+
let metadata
|
|
207
|
+
if (Buffer.isBuffer(buffer)) {
|
|
208
|
+
metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true })
|
|
209
|
+
}
|
|
210
|
+
else if (typeof buffer === 'string') {
|
|
211
|
+
const rStream = fs_1.createReadStream(buffer)
|
|
212
|
+
try {
|
|
213
|
+
metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true })
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
rStream.destroy()
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true })
|
|
221
|
+
}
|
|
222
|
+
return metadata.format.duration
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
|
|
226
|
+
*/
|
|
227
|
+
async function getAudioWaveform(buffer, logger) {
|
|
228
|
+
try {
|
|
229
|
+
const { default: decoder } = await eval('import(\'audio-decode\')')
|
|
230
|
+
let audioData
|
|
231
|
+
if (Buffer.isBuffer(buffer)) {
|
|
232
|
+
audioData = buffer
|
|
233
|
+
}
|
|
234
|
+
else if (typeof buffer === 'string') {
|
|
235
|
+
const rStream = fs_1.createReadStream(buffer)
|
|
236
|
+
audioData = await toBuffer(rStream)
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
audioData = await toBuffer(buffer)
|
|
240
|
+
}
|
|
241
|
+
const audioBuffer = await decoder(audioData)
|
|
242
|
+
const rawData = audioBuffer.getChannelData(0) // We only need to work with one channel of data
|
|
243
|
+
const samples = 64 // Number of samples we want to have in our final data set
|
|
244
|
+
const blockSize = Math.floor(rawData.length / samples) // the number of samples in each subdivision
|
|
245
|
+
const filteredData = []
|
|
246
|
+
for (let i = 0; i < samples; i++) {
|
|
247
|
+
const blockStart = blockSize * i // the location of the first sample in the block
|
|
248
|
+
let sum = 0
|
|
249
|
+
for (let j = 0; j < blockSize; j++) {
|
|
250
|
+
sum = sum + Math.abs(rawData[blockStart + j]) // find the sum of all the samples in the block
|
|
251
|
+
}
|
|
252
|
+
filteredData.push(sum / blockSize) // divide the sum by the block size to get the average
|
|
253
|
+
}
|
|
254
|
+
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
|
255
|
+
const multiplier = Math.pow(Math.max(...filteredData), -1)
|
|
256
|
+
const normalizedData = filteredData.map((n) => n * multiplier)
|
|
257
|
+
// Generate waveform like WhatsApp
|
|
258
|
+
const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)))
|
|
259
|
+
return waveform
|
|
260
|
+
}
|
|
261
|
+
catch (e) {
|
|
262
|
+
logger?.debug('Failed to generate waveform: ' + e)
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const toReadable = (buffer) => {
|
|
266
|
+
const readable = new stream_1.Readable({ read: () => { } })
|
|
267
|
+
readable.push(buffer)
|
|
268
|
+
readable.push(null)
|
|
269
|
+
return readable
|
|
270
|
+
}
|
|
271
|
+
const toBuffer = async (stream) => {
|
|
272
|
+
const chunks = []
|
|
273
|
+
for await (const chunk of stream) {
|
|
274
|
+
chunks.push(chunk)
|
|
275
|
+
}
|
|
276
|
+
stream.destroy()
|
|
277
|
+
return Buffer.concat(chunks)
|
|
278
|
+
}
|
|
279
|
+
const getStream = async (item, opts) => {
|
|
280
|
+
if (Buffer.isBuffer(item)) {
|
|
281
|
+
return { stream: toReadable(item), type: 'buffer' }
|
|
282
|
+
}
|
|
283
|
+
if ('stream' in item) {
|
|
284
|
+
return { stream: item.stream, type: 'readable' }
|
|
285
|
+
}
|
|
286
|
+
if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
|
|
287
|
+
return { stream: await getHttpStream(item.url, opts), type: 'remote' }
|
|
288
|
+
}
|
|
289
|
+
return { stream: fs_1.createReadStream(item.url), type: 'file' }
|
|
290
|
+
}
|
|
291
|
+
/** generates a thumbnail for a given media, if required */
|
|
292
|
+
async function generateThumbnail(file, mediaType, options) {
|
|
293
|
+
let thumbnail
|
|
294
|
+
let originalImageDimensions
|
|
295
|
+
if (mediaType === 'image') {
|
|
296
|
+
const { buffer, original } = await extractImageThumb(file, 256, 95)
|
|
297
|
+
thumbnail = buffer.toString('base64')
|
|
298
|
+
if (original.width && original.height) {
|
|
299
|
+
originalImageDimensions = {
|
|
300
|
+
width: original.width,
|
|
301
|
+
height: original.height,
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
else if (mediaType === 'video') {
|
|
306
|
+
try {
|
|
307
|
+
const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 })
|
|
308
|
+
thumbnail = buff.toString('base64')
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
options?.logger?.debug('could not generate video thumb: ' + err)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return {
|
|
315
|
+
thumbnail,
|
|
316
|
+
originalImageDimensions
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const getHttpStream = async (url, options = {}) => {
|
|
320
|
+
const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' })
|
|
321
|
+
return fetched.data
|
|
322
|
+
}
|
|
323
|
+
const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
324
|
+
const { stream, type } = await getStream(media, opts)
|
|
325
|
+
logger?.debug('fetched media stream')
|
|
326
|
+
const encFilePath = path_1.join(os_1.tmpdir(), mediaType + generics_1.generateMessageID() + '-plain')
|
|
327
|
+
const encFileWriteStream = fs_1.createWriteStream(encFilePath)
|
|
328
|
+
let originalFilePath
|
|
329
|
+
let originalFileStream
|
|
330
|
+
if (type === 'file') {
|
|
331
|
+
originalFilePath = media.url.toString()
|
|
332
|
+
} else if (saveOriginalFileIfRequired) {
|
|
333
|
+
originalFilePath = path_1.join(os_1.tmpdir(), mediaType + generics_1.generateMessageID() + '-original')
|
|
334
|
+
originalFileStream = fs_1.createWriteStream(originalFilePath)
|
|
335
|
+
}
|
|
336
|
+
let fileLength = 0
|
|
337
|
+
const sha256 = Crypto.createHash('sha256')
|
|
338
|
+
try {
|
|
339
|
+
for await (const data of stream) {
|
|
340
|
+
fileLength += data.length
|
|
341
|
+
if (type === 'remote'
|
|
342
|
+
&& opts?.maxContentLength
|
|
343
|
+
&& fileLength + data.length > opts.maxContentLength) {
|
|
344
|
+
throw new boom_1.Boom(`content length exceeded when preparing "${type}"`, {
|
|
345
|
+
data: { media, type }
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
sha256.update(data)
|
|
349
|
+
encFileWriteStream.write(data)
|
|
350
|
+
if (originalFileStream && !originalFileStream.write(data)) {
|
|
351
|
+
await events_1.once(originalFileStream, 'drain')
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const fileSha256 = sha256.digest()
|
|
355
|
+
encFileWriteStream.end()
|
|
356
|
+
originalFileStream?.end?.call(originalFileStream)
|
|
357
|
+
stream.destroy()
|
|
358
|
+
logger?.debug('prepared plain stream successfully')
|
|
359
|
+
return {
|
|
360
|
+
mediaKey: undefined,
|
|
361
|
+
originalFilePath,
|
|
362
|
+
encFilePath,
|
|
363
|
+
mac: undefined,
|
|
364
|
+
fileEncSha256: undefined,
|
|
365
|
+
fileSha256,
|
|
366
|
+
fileLength
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
encFileWriteStream.destroy()
|
|
371
|
+
originalFileStream?.destroy?.call(originalFileStream)
|
|
372
|
+
sha256.destroy()
|
|
373
|
+
stream.destroy()
|
|
374
|
+
try {
|
|
375
|
+
await fs_1.promises.unlink(encFilePath)
|
|
376
|
+
if (originalFilePath && didSaveToTmpPath) {
|
|
377
|
+
await fs_1.promises.unlink(originalFilePath)
|
|
378
|
+
}
|
|
379
|
+
} catch (err) {
|
|
380
|
+
logger?.error({ err }, 'failed deleting tmp files')
|
|
381
|
+
}
|
|
382
|
+
throw error
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
386
|
+
const { stream, type } = await getStream(media, opts)
|
|
387
|
+
logger?.debug('fetched media stream')
|
|
388
|
+
const mediaKey = Crypto.randomBytes(32)
|
|
389
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
|
|
390
|
+
const encFilePath = path_1.join(os_1.tmpdir(), mediaType + generics_1.generateMessageID() + '-enc')
|
|
391
|
+
const encFileWriteStream = fs_1.createWriteStream(encFilePath)
|
|
392
|
+
let originalFileStream
|
|
393
|
+
let originalFilePath
|
|
394
|
+
if (saveOriginalFileIfRequired) {
|
|
395
|
+
originalFilePath = path_1.join(os_1.tmpdir(), mediaType + generics_1.generateMessageID() + '-original')
|
|
396
|
+
originalFileStream = fs_1.createWriteStream(originalFilePath)
|
|
397
|
+
}
|
|
398
|
+
let fileLength = 0
|
|
399
|
+
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv)
|
|
400
|
+
const hmac = Crypto.createHmac('sha256', macKey).update(iv)
|
|
401
|
+
const sha256Plain = Crypto.createHash('sha256')
|
|
402
|
+
const sha256Enc = Crypto.createHash('sha256')
|
|
403
|
+
const onChunk = (buff) => {
|
|
404
|
+
sha256Enc.update(buff)
|
|
405
|
+
hmac.update(buff)
|
|
406
|
+
encFileWriteStream.write(buff)
|
|
407
|
+
}
|
|
408
|
+
try {
|
|
409
|
+
for await (const data of stream) {
|
|
410
|
+
fileLength += data.length
|
|
411
|
+
if (type === 'remote'
|
|
412
|
+
&& opts?.maxContentLength
|
|
413
|
+
&& fileLength + data.length > opts.maxContentLength) {
|
|
414
|
+
throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
|
|
415
|
+
data: { media, type }
|
|
416
|
+
})
|
|
417
|
+
}
|
|
418
|
+
if (originalFileStream) {
|
|
419
|
+
if (!originalFileStream.write(data)) {
|
|
420
|
+
await events_1.once(originalFileStream, 'drain')
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
sha256Plain.update(data)
|
|
424
|
+
onChunk(aes.update(data))
|
|
425
|
+
}
|
|
426
|
+
onChunk(aes.final())
|
|
427
|
+
const mac = hmac.digest().slice(0, 10)
|
|
428
|
+
sha256Enc.update(mac)
|
|
429
|
+
const fileSha256 = sha256Plain.digest()
|
|
430
|
+
const fileEncSha256 = sha256Enc.digest()
|
|
431
|
+
encFileWriteStream.write(mac)
|
|
432
|
+
encFileWriteStream.end()
|
|
433
|
+
originalFileStream?.end?.call(originalFileStream)
|
|
434
|
+
stream.destroy()
|
|
435
|
+
logger?.debug('encrypted data successfully')
|
|
436
|
+
return {
|
|
437
|
+
mediaKey,
|
|
438
|
+
originalFilePath,
|
|
439
|
+
encFilePath,
|
|
440
|
+
mac,
|
|
441
|
+
fileEncSha256,
|
|
442
|
+
fileSha256,
|
|
443
|
+
fileLength
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
// destroy all streams with error
|
|
448
|
+
encFileWriteStream.destroy()
|
|
449
|
+
originalFileStream?.destroy?.call(originalFileStream)
|
|
450
|
+
aes.destroy()
|
|
451
|
+
hmac.destroy()
|
|
452
|
+
sha256Plain.destroy()
|
|
453
|
+
sha256Enc.destroy()
|
|
454
|
+
stream.destroy()
|
|
455
|
+
try {
|
|
456
|
+
await fs_1.promises.unlink(encFilePath)
|
|
457
|
+
if (originalFilePath) {
|
|
458
|
+
await fs_1.promises.unlink(originalFilePath)
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
catch (err) {
|
|
462
|
+
logger?.error({ err }, 'failed deleting tmp files')
|
|
463
|
+
}
|
|
464
|
+
throw error
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const DEF_HOST = 'mmg.whatsapp.net'
|
|
468
|
+
const AES_CHUNK_SIZE = 16
|
|
469
|
+
const toSmallestChunkSize = (num) => {
|
|
470
|
+
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
|
|
471
|
+
}
|
|
472
|
+
const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`
|
|
473
|
+
const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
474
|
+
const downloadUrl = url || getUrlFromDirectPath(directPath)
|
|
475
|
+
const keys = await getMediaKeys(mediaKey, type)
|
|
476
|
+
return downloadEncryptedContent(downloadUrl, keys, opts)
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Decrypts and downloads an AES256-CBC encrypted file given the keys.
|
|
480
|
+
* Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
|
|
481
|
+
* */
|
|
482
|
+
const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
|
|
483
|
+
let bytesFetched = 0
|
|
484
|
+
let startChunk = 0
|
|
485
|
+
let firstBlockIsIV = false
|
|
486
|
+
// if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
|
|
487
|
+
if (startByte) {
|
|
488
|
+
const chunk = toSmallestChunkSize(startByte || 0)
|
|
489
|
+
if (chunk) {
|
|
490
|
+
startChunk = chunk - AES_CHUNK_SIZE
|
|
491
|
+
bytesFetched = chunk
|
|
492
|
+
firstBlockIsIV = true
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
|
|
496
|
+
const headers = {
|
|
497
|
+
...(options?.headers) || {},
|
|
498
|
+
Origin: Defaults_1.DEFAULT_ORIGIN,
|
|
499
|
+
}
|
|
500
|
+
if (startChunk || endChunk) {
|
|
501
|
+
headers.Range = `bytes=${startChunk}-`
|
|
502
|
+
if (endChunk) {
|
|
503
|
+
headers.Range += endChunk
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
// download the message
|
|
507
|
+
const fetched = await getHttpStream(downloadUrl, {
|
|
508
|
+
...options || {},
|
|
509
|
+
headers,
|
|
510
|
+
maxBodyLength: Infinity,
|
|
511
|
+
maxContentLength: Infinity,
|
|
512
|
+
})
|
|
513
|
+
let remainingBytes = Buffer.from([])
|
|
514
|
+
let aes
|
|
515
|
+
const pushBytes = (bytes, push) => {
|
|
516
|
+
if (startByte || endByte) {
|
|
517
|
+
const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
|
|
518
|
+
const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
|
|
519
|
+
push(bytes.slice(start, end))
|
|
520
|
+
bytesFetched += bytes.length
|
|
521
|
+
}
|
|
522
|
+
else {
|
|
523
|
+
push(bytes)
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
const output = new stream_1.Transform({
|
|
527
|
+
transform(chunk, _, callback) {
|
|
528
|
+
let data = Buffer.concat([remainingBytes, chunk])
|
|
529
|
+
const decryptLength = toSmallestChunkSize(data.length)
|
|
530
|
+
remainingBytes = data.slice(decryptLength)
|
|
531
|
+
data = data.slice(0, decryptLength)
|
|
532
|
+
if (!aes) {
|
|
533
|
+
let ivValue = iv
|
|
534
|
+
if (firstBlockIsIV) {
|
|
535
|
+
ivValue = data.slice(0, AES_CHUNK_SIZE)
|
|
536
|
+
data = data.slice(AES_CHUNK_SIZE)
|
|
537
|
+
}
|
|
538
|
+
aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
|
|
539
|
+
// if an end byte that is not EOF is specified
|
|
540
|
+
// stop auto padding (PKCS7) -- otherwise throws an error for decryption
|
|
541
|
+
if (endByte) {
|
|
542
|
+
aes.setAutoPadding(false)
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
try {
|
|
546
|
+
pushBytes(aes.update(data), b => this.push(b))
|
|
547
|
+
callback()
|
|
548
|
+
}
|
|
549
|
+
catch (error) {
|
|
550
|
+
callback(error)
|
|
551
|
+
}
|
|
552
|
+
},
|
|
553
|
+
final(callback) {
|
|
554
|
+
try {
|
|
555
|
+
pushBytes(aes.final(), b => this.push(b))
|
|
556
|
+
callback()
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
callback(error)
|
|
560
|
+
}
|
|
561
|
+
},
|
|
562
|
+
})
|
|
563
|
+
return fetched.pipe(output, { end: true })
|
|
564
|
+
}
|
|
565
|
+
function extensionForMediaMessage(message) {
|
|
566
|
+
const getExtension = (mimetype) => mimetype.split('')[0].split('/')[1]
|
|
567
|
+
const type = Object.keys(message)[0]
|
|
568
|
+
let extension
|
|
569
|
+
if (type === 'locationMessage' ||
|
|
570
|
+
type === 'liveLocationMessage' ||
|
|
571
|
+
type === 'productMessage') {
|
|
572
|
+
extension = '.jpeg'
|
|
573
|
+
}
|
|
574
|
+
else {
|
|
575
|
+
const messageContent = message[type]
|
|
576
|
+
extension = getExtension(messageContent.mimetype)
|
|
577
|
+
}
|
|
578
|
+
return extension
|
|
579
|
+
}
|
|
580
|
+
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
581
|
+
return async (filePath, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
|
|
582
|
+
// send a query JSON to obtain the url & auth token to upload our media
|
|
583
|
+
let uploadInfo = await refreshMediaConn(false)
|
|
584
|
+
let urls
|
|
585
|
+
let media = Defaults_1.MEDIA_PATH_MAP[mediaType]
|
|
586
|
+
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
|
587
|
+
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
|
588
|
+
if (newsletter) {
|
|
589
|
+
media = media?.replace('/mms/', '/newsletter/newsletter-')
|
|
590
|
+
}
|
|
591
|
+
for (const { hostname } of hosts) {
|
|
592
|
+
logger.debug(`uploading to "${hostname}"`)
|
|
593
|
+
const auth = encodeURIComponent(uploadInfo.auth) // the auth token
|
|
594
|
+
const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
|
|
595
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
596
|
+
let result
|
|
597
|
+
try {
|
|
598
|
+
const body = await axios_1.default.post(url, fs_1.createReadStream(filePath), {
|
|
599
|
+
...options,
|
|
600
|
+
maxRedirects: 0,
|
|
601
|
+
headers: {
|
|
602
|
+
...options.headers || {},
|
|
603
|
+
'Content-Type': 'application/octet-stream',
|
|
604
|
+
'Origin': Defaults_1.DEFAULT_ORIGIN
|
|
605
|
+
},
|
|
606
|
+
httpsAgent: fetchAgent,
|
|
607
|
+
timeout: timeoutMs,
|
|
608
|
+
responseType: 'json',
|
|
609
|
+
maxBodyLength: Infinity,
|
|
610
|
+
maxContentLength: Infinity,
|
|
611
|
+
})
|
|
612
|
+
result = body.data
|
|
613
|
+
if (result?.url || result?.directPath) {
|
|
614
|
+
urls = {
|
|
615
|
+
mediaUrl: result.url,
|
|
616
|
+
directPath: result.direct_path
|
|
617
|
+
}
|
|
618
|
+
break
|
|
619
|
+
}
|
|
620
|
+
else {
|
|
621
|
+
uploadInfo = await refreshMediaConn(true)
|
|
622
|
+
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
catch (error) {
|
|
626
|
+
if (axios_1.default.isAxiosError(error)) {
|
|
627
|
+
result = error.response?.data
|
|
628
|
+
}
|
|
629
|
+
const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
|
|
630
|
+
logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`)
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (!urls) {
|
|
634
|
+
throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 })
|
|
635
|
+
}
|
|
636
|
+
return urls
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
const getMediaRetryKey = (mediaKey) => {
|
|
640
|
+
return crypto_1.hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
|
644
|
+
*/
|
|
645
|
+
const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
|
|
646
|
+
const recp = { stanzaId: key.id }
|
|
647
|
+
const recpBuffer = WAProto_1.proto.ServerErrorReceipt.encode(recp).finish()
|
|
648
|
+
const iv = Crypto.randomBytes(12)
|
|
649
|
+
const retryKey = await getMediaRetryKey(mediaKey)
|
|
650
|
+
const ciphertext = crypto_1.aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id))
|
|
651
|
+
const req = {
|
|
652
|
+
tag: 'receipt',
|
|
653
|
+
attrs: {
|
|
654
|
+
id: key.id,
|
|
655
|
+
to: WABinary_1.jidNormalizedUser(meId),
|
|
656
|
+
type: 'server-error'
|
|
657
|
+
},
|
|
658
|
+
content: [
|
|
659
|
+
// this encrypt node is actually pretty useless
|
|
660
|
+
// the media is returned even without this node
|
|
661
|
+
// keeping it here to maintain parity with WA Web
|
|
662
|
+
{
|
|
663
|
+
tag: 'encrypt',
|
|
664
|
+
attrs: {},
|
|
665
|
+
content: [
|
|
666
|
+
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
667
|
+
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
668
|
+
]
|
|
669
|
+
},
|
|
670
|
+
{
|
|
671
|
+
tag: 'rmr',
|
|
672
|
+
attrs: {
|
|
673
|
+
jid: key.remoteJid,
|
|
674
|
+
'from_me': (!!key.fromMe).toString(),
|
|
675
|
+
// @ts-ignore
|
|
676
|
+
participant: key.participant || undefined
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
]
|
|
680
|
+
}
|
|
681
|
+
return req
|
|
682
|
+
}
|
|
683
|
+
const decodeMediaRetryNode = (node) => {
|
|
684
|
+
const rmrNode = WABinary_1.getBinaryNodeChild(node, 'rmr')
|
|
685
|
+
const event = {
|
|
686
|
+
key: {
|
|
687
|
+
id: node.attrs.id,
|
|
688
|
+
remoteJid: rmrNode.attrs.jid,
|
|
689
|
+
fromMe: rmrNode.attrs.from_me === 'true',
|
|
690
|
+
participant: rmrNode.attrs.participant
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const errorNode = WABinary_1.getBinaryNodeChild(node, 'error')
|
|
694
|
+
if (errorNode) {
|
|
695
|
+
const errorCode = +errorNode.attrs.code
|
|
696
|
+
event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(errorCode) })
|
|
697
|
+
}
|
|
698
|
+
else {
|
|
699
|
+
const encryptedInfoNode = WABinary_1.getBinaryNodeChild(node, 'encrypt')
|
|
700
|
+
const ciphertext = WABinary_1.getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
|
|
701
|
+
const iv = WABinary_1.getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
|
|
702
|
+
if (ciphertext && iv) {
|
|
703
|
+
event.media = { ciphertext, iv }
|
|
704
|
+
}
|
|
705
|
+
else {
|
|
706
|
+
event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return event
|
|
710
|
+
}
|
|
711
|
+
const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
712
|
+
const retryKey = await getMediaRetryKey(mediaKey)
|
|
713
|
+
const plaintext = crypto_1.aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
|
|
714
|
+
return WAProto_1.proto.MediaRetryNotification.decode(plaintext)
|
|
715
|
+
}
|
|
716
|
+
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code]
|
|
717
|
+
const MEDIA_RETRY_STATUS_MAP = {
|
|
718
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
719
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
720
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
721
|
+
[WAProto_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
|
|
722
|
+
}
|
|
723
|
+
module.exports = {
|
|
724
|
+
hkdfInfoKey,
|
|
725
|
+
getMediaKeys,
|
|
726
|
+
extractVideoThumb,
|
|
727
|
+
extractImageThumb,
|
|
728
|
+
encodeBase64EncodedStringForUpload,
|
|
729
|
+
generateProfilePicture,
|
|
730
|
+
mediaMessageSHA256B64,
|
|
731
|
+
getAudioDuration,
|
|
732
|
+
getAudioWaveform,
|
|
733
|
+
toReadable,
|
|
734
|
+
toBuffer,
|
|
735
|
+
getStream,
|
|
736
|
+
generateThumbnail,
|
|
737
|
+
getHttpStream,
|
|
738
|
+
prepareStream,
|
|
739
|
+
encryptedStream,
|
|
740
|
+
getUrlFromDirectPath,
|
|
741
|
+
downloadContentFromMessage,
|
|
742
|
+
downloadEncryptedContent,
|
|
743
|
+
extensionForMediaMessage,
|
|
744
|
+
getWAUploadToServer,
|
|
745
|
+
getMediaRetryKey,
|
|
746
|
+
encryptMediaRetryRequest,
|
|
747
|
+
decodeMediaRetryNode,
|
|
748
|
+
decryptMediaRetryData,
|
|
749
|
+
getStatusCodeForMediaRetry,
|
|
750
|
+
MEDIA_RETRY_STATUS_MAP
|
|
751
|
+
}
|