@badzz88/baileys 8.5.4 → 8.5.6

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