@neelegirl/baileys 1.5.5 → 1.5.7

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