@vinzsocket/baileys 3.0.0 → 3.0.10

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 (330) hide show
  1. package/WAProto/GenerateStatics.sh +2 -2
  2. package/WAProto/WAProto.proto +1339 -493
  3. package/WAProto/fix-imports.js +79 -14
  4. package/WAProto/index.d.ts +5274 -1945
  5. package/WAProto/index.js +97691 -1
  6. package/lib/Defaults/index.d.ts +25 -8
  7. package/lib/Defaults/index.d.ts.map +1 -1
  8. package/lib/Defaults/index.js +124 -109
  9. package/lib/Defaults/index.js.map +1 -1
  10. package/lib/Signal/Group/ciphertext-message.js +11 -15
  11. package/lib/Signal/Group/group-session-builder.js +27 -32
  12. package/lib/Signal/Group/group_cipher.d.ts +1 -2
  13. package/lib/Signal/Group/group_cipher.d.ts.map +1 -1
  14. package/lib/Signal/Group/group_cipher.js +75 -92
  15. package/lib/Signal/Group/group_cipher.js.map +1 -1
  16. package/lib/Signal/Group/index.js +12 -77
  17. package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
  18. package/lib/Signal/Group/keyhelper.js +16 -24
  19. package/lib/Signal/Group/keyhelper.js.map +1 -1
  20. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  21. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -1
  22. package/lib/Signal/Group/sender-chain-key.js +24 -34
  23. package/lib/Signal/Group/sender-chain-key.js.map +1 -1
  24. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -1
  25. package/lib/Signal/Group/sender-key-distribution-message.js +62 -58
  26. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -1
  27. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -1
  28. package/lib/Signal/Group/sender-key-message.js +64 -65
  29. package/lib/Signal/Group/sender-key-message.js.map +1 -1
  30. package/lib/Signal/Group/sender-key-name.js +41 -44
  31. package/lib/Signal/Group/sender-key-record.d.ts +1 -1
  32. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -1
  33. package/lib/Signal/Group/sender-key-record.js +36 -47
  34. package/lib/Signal/Group/sender-key-record.js.map +1 -1
  35. package/lib/Signal/Group/sender-key-state.d.ts +4 -4
  36. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -1
  37. package/lib/Signal/Group/sender-key-state.js +76 -93
  38. package/lib/Signal/Group/sender-key-state.js.map +1 -1
  39. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -1
  40. package/lib/Signal/Group/sender-message-key.js +25 -31
  41. package/lib/Signal/Group/sender-message-key.js.map +1 -1
  42. package/lib/Signal/libsignal.d.ts +4 -7
  43. package/lib/Signal/libsignal.d.ts.map +1 -1
  44. package/lib/Signal/libsignal.js +417 -401
  45. package/lib/Signal/libsignal.js.map +1 -1
  46. package/lib/Signal/lid-mapping.d.ts +16 -23
  47. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  48. package/lib/Signal/lid-mapping.js +273 -108
  49. package/lib/Signal/lid-mapping.js.map +1 -1
  50. package/lib/Socket/Client/index.js +3 -25
  51. package/lib/Socket/Client/types.d.ts +2 -2
  52. package/lib/Socket/Client/types.d.ts.map +1 -1
  53. package/lib/Socket/Client/types.js +10 -14
  54. package/lib/Socket/Client/websocket.d.ts +1 -1
  55. package/lib/Socket/Client/websocket.d.ts.map +1 -1
  56. package/lib/Socket/Client/websocket.js +53 -54
  57. package/lib/Socket/Client/websocket.js.map +1 -1
  58. package/lib/Socket/business.d.ts +45 -16
  59. package/lib/Socket/business.d.ts.map +1 -1
  60. package/lib/Socket/business.js +374 -360
  61. package/lib/Socket/business.js.map +1 -1
  62. package/lib/Socket/chats.d.ts +34 -8
  63. package/lib/Socket/chats.d.ts.map +1 -1
  64. package/lib/Socket/chats.js +1162 -1038
  65. package/lib/Socket/chats.js.map +1 -1
  66. package/lib/Socket/communities.d.ts +56 -16
  67. package/lib/Socket/communities.d.ts.map +1 -1
  68. package/lib/Socket/communities.js +418 -466
  69. package/lib/Socket/communities.js.map +1 -1
  70. package/lib/Socket/groups.d.ts +32 -8
  71. package/lib/Socket/groups.d.ts.map +1 -1
  72. package/lib/Socket/groups.js +337 -390
  73. package/lib/Socket/groups.js.map +1 -1
  74. package/lib/Socket/index.d.ts +56 -16
  75. package/lib/Socket/index.d.ts.map +1 -1
  76. package/lib/Socket/index.js +10 -18
  77. package/lib/Socket/index.js.map +1 -1
  78. package/lib/Socket/messages-recv.d.ts +49 -19
  79. package/lib/Socket/messages-recv.d.ts.map +1 -1
  80. package/lib/Socket/messages-recv.js +1738 -1391
  81. package/lib/Socket/messages-recv.js.map +1 -1
  82. package/lib/Socket/messages-send.d.ts +45 -15
  83. package/lib/Socket/messages-send.d.ts.map +1 -1
  84. package/lib/Socket/messages-send.js +1101 -1242
  85. package/lib/Socket/messages-send.js.map +1 -1
  86. package/lib/Socket/mex.js +38 -48
  87. package/lib/Socket/newsletter.d.ts +30 -7
  88. package/lib/Socket/newsletter.d.ts.map +1 -1
  89. package/lib/Socket/newsletter.js +175 -222
  90. package/lib/Socket/newsletter.js.map +1 -1
  91. package/lib/Socket/socket.d.ts +15 -6
  92. package/lib/Socket/socket.d.ts.map +1 -1
  93. package/lib/Socket/socket.js +932 -913
  94. package/lib/Socket/socket.js.map +1 -1
  95. package/lib/Types/Auth.d.ts +12 -0
  96. package/lib/Types/Auth.d.ts.map +1 -1
  97. package/lib/Types/Auth.js +2 -3
  98. package/lib/Types/Bussines.js +2 -3
  99. package/lib/Types/Call.d.ts +2 -1
  100. package/lib/Types/Call.d.ts.map +1 -1
  101. package/lib/Types/Call.js +2 -3
  102. package/lib/Types/Chat.d.ts +1 -0
  103. package/lib/Types/Chat.d.ts.map +1 -1
  104. package/lib/Types/Chat.js +8 -5
  105. package/lib/Types/Contact.d.ts +2 -0
  106. package/lib/Types/Contact.d.ts.map +1 -1
  107. package/lib/Types/Contact.js +2 -3
  108. package/lib/Types/Events.d.ts +66 -9
  109. package/lib/Types/Events.d.ts.map +1 -1
  110. package/lib/Types/Events.js +2 -1
  111. package/lib/Types/GroupMetadata.d.ts +5 -0
  112. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  113. package/lib/Types/GroupMetadata.js +2 -3
  114. package/lib/Types/Label.js +23 -26
  115. package/lib/Types/LabelAssociation.js +5 -8
  116. package/lib/Types/Message.d.ts +31 -11
  117. package/lib/Types/Message.d.ts.map +1 -1
  118. package/lib/Types/Message.js +9 -18
  119. package/lib/Types/Message.js.map +1 -1
  120. package/lib/Types/{Newsletter.d.ts → Mex.d.ts} +11 -5
  121. package/lib/Types/Mex.d.ts.map +1 -0
  122. package/lib/Types/Mex.js +37 -0
  123. package/lib/Types/Mex.js.map +1 -0
  124. package/lib/Types/Product.js +2 -3
  125. package/lib/Types/Signal.d.ts +21 -16
  126. package/lib/Types/Signal.d.ts.map +1 -1
  127. package/lib/Types/Signal.js +2 -1
  128. package/lib/Types/Socket.d.ts +23 -17
  129. package/lib/Types/Socket.d.ts.map +1 -1
  130. package/lib/Types/Socket.js +3 -2
  131. package/lib/Types/Socket.js.map +1 -1
  132. package/lib/Types/State.d.ts +58 -0
  133. package/lib/Types/State.d.ts.map +1 -1
  134. package/lib/Types/State.js +55 -15
  135. package/lib/Types/State.js.map +1 -1
  136. package/lib/Types/USync.js +2 -1
  137. package/lib/Types/index.d.ts +1 -1
  138. package/lib/Types/index.d.ts.map +1 -1
  139. package/lib/Types/index.js +25 -163
  140. package/lib/Types/index.js.map +1 -1
  141. package/lib/Utils/auth-utils.d.ts +7 -2
  142. package/lib/Utils/auth-utils.d.ts.map +1 -1
  143. package/lib/Utils/auth-utils.js +272 -458
  144. package/lib/Utils/auth-utils.js.map +1 -1
  145. package/lib/Utils/browser-utils.d.ts +4 -0
  146. package/lib/Utils/browser-utils.d.ts.map +1 -0
  147. package/lib/Utils/browser-utils.js +28 -0
  148. package/lib/Utils/browser-utils.js.map +1 -0
  149. package/lib/Utils/business.js +208 -221
  150. package/lib/Utils/chat-utils.d.ts +35 -6
  151. package/lib/Utils/chat-utils.d.ts.map +1 -1
  152. package/lib/Utils/chat-utils.js +828 -800
  153. package/lib/Utils/chat-utils.js.map +1 -1
  154. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  155. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  156. package/lib/Utils/companion-reg-client-utils.js +35 -0
  157. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  158. package/lib/Utils/crypto.d.ts +7 -11
  159. package/lib/Utils/crypto.d.ts.map +1 -1
  160. package/lib/Utils/crypto.js +88 -142
  161. package/lib/Utils/crypto.js.map +1 -1
  162. package/lib/Utils/decode-wa-message.d.ts +22 -2
  163. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  164. package/lib/Utils/decode-wa-message.js +293 -261
  165. package/lib/Utils/decode-wa-message.js.map +1 -1
  166. package/lib/Utils/event-buffer.d.ts +2 -0
  167. package/lib/Utils/event-buffer.d.ts.map +1 -1
  168. package/lib/Utils/event-buffer.js +599 -558
  169. package/lib/Utils/event-buffer.js.map +1 -1
  170. package/lib/Utils/generics.d.ts +6 -7
  171. package/lib/Utils/generics.d.ts.map +1 -1
  172. package/lib/Utils/generics.js +331 -362
  173. package/lib/Utils/generics.js.map +1 -1
  174. package/lib/Utils/history.d.ts +14 -10
  175. package/lib/Utils/history.d.ts.map +1 -1
  176. package/lib/Utils/history.js +129 -93
  177. package/lib/Utils/history.js.map +1 -1
  178. package/lib/Utils/identity-change-handler.d.ts +44 -0
  179. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  180. package/lib/Utils/identity-change-handler.js +50 -0
  181. package/lib/Utils/identity-change-handler.js.map +1 -0
  182. package/lib/Utils/index.d.ts +4 -4
  183. package/lib/Utils/index.d.ts.map +1 -1
  184. package/lib/Utils/index.js +22 -234
  185. package/lib/Utils/index.js.map +1 -1
  186. package/lib/Utils/link-preview.d.ts +1 -2
  187. package/lib/Utils/link-preview.d.ts.map +1 -1
  188. package/lib/Utils/link-preview.js +69 -83
  189. package/lib/Utils/link-preview.js.map +1 -1
  190. package/lib/Utils/logger.js +3 -9
  191. package/lib/Utils/lt-hash.d.ts +7 -12
  192. package/lib/Utils/lt-hash.d.ts.map +1 -1
  193. package/lib/Utils/lt-hash.js +3 -50
  194. package/lib/Utils/lt-hash.js.map +1 -1
  195. package/lib/Utils/make-mutex.d.ts +1 -0
  196. package/lib/Utils/make-mutex.d.ts.map +1 -1
  197. package/lib/Utils/make-mutex.js +30 -40
  198. package/lib/Utils/make-mutex.js.map +1 -1
  199. package/lib/Utils/message-retry-manager.d.ts +38 -5
  200. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  201. package/lib/Utils/message-retry-manager.js +259 -159
  202. package/lib/Utils/message-retry-manager.js.map +1 -1
  203. package/lib/Utils/messages-media.d.ts +30 -10
  204. package/lib/Utils/messages-media.d.ts.map +1 -1
  205. package/lib/Utils/messages-media.js +734 -710
  206. package/lib/Utils/messages-media.js.map +1 -1
  207. package/lib/Utils/messages.d.ts +19 -4
  208. package/lib/Utils/messages.d.ts.map +1 -1
  209. package/lib/Utils/messages.js +817 -800
  210. package/lib/Utils/messages.js.map +1 -1
  211. package/lib/Utils/noise-handler.d.ts +4 -4
  212. package/lib/Utils/noise-handler.d.ts.map +1 -1
  213. package/lib/Utils/noise-handler.js +195 -165
  214. package/lib/Utils/noise-handler.js.map +1 -1
  215. package/lib/Utils/offline-node-processor.d.ts +17 -0
  216. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  217. package/lib/Utils/offline-node-processor.js +40 -0
  218. package/lib/Utils/offline-node-processor.js.map +1 -0
  219. package/lib/Utils/pre-key-manager.d.ts +28 -0
  220. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  221. package/lib/Utils/pre-key-manager.js +106 -0
  222. package/lib/Utils/pre-key-manager.js.map +1 -0
  223. package/lib/Utils/process-message.d.ts +26 -9
  224. package/lib/Utils/process-message.d.ts.map +1 -1
  225. package/lib/Utils/process-message.js +601 -422
  226. package/lib/Utils/process-message.js.map +1 -1
  227. package/lib/Utils/reporting-utils.d.ts +11 -0
  228. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  229. package/lib/Utils/reporting-utils.js +258 -0
  230. package/lib/Utils/reporting-utils.js.map +1 -0
  231. package/lib/Utils/signal.d.ts +17 -4
  232. package/lib/Utils/signal.d.ts.map +1 -1
  233. package/lib/Utils/signal.js +180 -203
  234. package/lib/Utils/signal.js.map +1 -1
  235. package/lib/Utils/stanza-ack.d.ts +11 -0
  236. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  237. package/lib/Utils/stanza-ack.js +38 -0
  238. package/lib/Utils/stanza-ack.js.map +1 -0
  239. package/lib/Utils/sync-action-utils.d.ts +19 -0
  240. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  241. package/lib/Utils/sync-action-utils.js +49 -0
  242. package/lib/Utils/sync-action-utils.js.map +1 -0
  243. package/lib/Utils/tc-token-utils.d.ts +37 -0
  244. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  245. package/lib/Utils/tc-token-utils.js +163 -0
  246. package/lib/Utils/tc-token-utils.js.map +1 -0
  247. package/lib/Utils/use-multi-file-auth-state.js +98 -98
  248. package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
  249. package/lib/Utils/validate-connection.d.ts.map +1 -1
  250. package/lib/Utils/validate-connection.js +191 -185
  251. package/lib/Utils/validate-connection.js.map +1 -1
  252. package/lib/WABinary/constants.js +1297 -35
  253. package/lib/WABinary/decode.d.ts.map +1 -1
  254. package/lib/WABinary/decode.js +254 -229
  255. package/lib/WABinary/decode.js.map +1 -1
  256. package/lib/WABinary/encode.js +210 -209
  257. package/lib/WABinary/encode.js.map +1 -1
  258. package/lib/WABinary/generic-utils.d.ts +1 -1
  259. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  260. package/lib/WABinary/generic-utils.js +99 -105
  261. package/lib/WABinary/generic-utils.js.map +1 -1
  262. package/lib/WABinary/index.js +6 -58
  263. package/lib/WABinary/jid-utils.d.ts +12 -1
  264. package/lib/WABinary/jid-utils.d.ts.map +1 -1
  265. package/lib/WABinary/jid-utils.js +83 -67
  266. package/lib/WABinary/jid-utils.js.map +1 -1
  267. package/lib/WABinary/types.js +2 -2
  268. package/lib/WAM/BinaryInfo.js +9 -13
  269. package/lib/WAM/constants.d.ts +1 -1
  270. package/lib/WAM/constants.d.ts.map +1 -1
  271. package/lib/WAM/constants.js +22853 -1
  272. package/lib/WAM/constants.js.map +1 -1
  273. package/lib/WAM/encode.js +135 -132
  274. package/lib/WAM/index.js +4 -36
  275. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  276. package/lib/WAUSync/Protocols/USyncContactProtocol.js +50 -31
  277. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  278. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -58
  279. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -29
  280. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +35 -37
  281. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +4 -2
  282. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  283. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +23 -27
  284. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  285. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +47 -61
  286. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +2 -1
  287. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -1
  288. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +27 -23
  289. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -1
  290. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  291. package/lib/WAUSync/Protocols/index.js +6 -58
  292. package/lib/WAUSync/Protocols/index.js.map +1 -1
  293. package/lib/WAUSync/USyncQuery.d.ts +1 -1
  294. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  295. package/lib/WAUSync/USyncQuery.js +94 -94
  296. package/lib/WAUSync/USyncQuery.js.map +1 -1
  297. package/lib/WAUSync/USyncUser.d.ts +4 -0
  298. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  299. package/lib/WAUSync/USyncUser.js +30 -26
  300. package/lib/WAUSync/USyncUser.js.map +1 -1
  301. package/lib/WAUSync/index.js +4 -36
  302. package/lib/index.d.ts +0 -1
  303. package/lib/index.js +11 -112
  304. package/package.json +49 -22
  305. package/README.md +0 -1315
  306. package/lib/Signal/Group/queue-job.d.ts +0 -2
  307. package/lib/Signal/Group/queue-job.js +0 -59
  308. package/lib/Store/index.d.ts +0 -4
  309. package/lib/Store/index.js +0 -47
  310. package/lib/Store/make-cache-manager-store.d.ts +0 -17
  311. package/lib/Store/make-cache-manager-store.js +0 -104
  312. package/lib/Store/make-in-memory-store.d.ts +0 -118
  313. package/lib/Store/make-in-memory-store.js +0 -490
  314. package/lib/Store/make-ordered-dictionary.d.ts +0 -14
  315. package/lib/Store/make-ordered-dictionary.js +0 -81
  316. package/lib/Store/object-repository.d.ts +0 -10
  317. package/lib/Store/object-repository.js +0 -30
  318. package/lib/Types/Newsletter.d.ts.map +0 -1
  319. package/lib/Types/Newsletter.js +0 -34
  320. package/lib/Types/Newsletter.js.map +0 -1
  321. package/lib/Utils/baileys-event-stream.d.ts +0 -17
  322. package/lib/Utils/baileys-event-stream.d.ts.map +0 -1
  323. package/lib/Utils/baileys-event-stream.js +0 -71
  324. package/lib/Utils/baileys-event-stream.js.map +0 -1
  325. package/lib/Utils/extended-messages.d.ts +0 -73
  326. package/lib/Utils/extended-messages.js +0 -283
  327. package/lib/Utils/lid-resolver.d.ts +0 -17
  328. package/lib/Utils/lid-resolver.js +0 -79
  329. package/lib/Utils/mention.d.ts +0 -27
  330. package/lib/Utils/mention.js +0 -135
@@ -1,764 +1,788 @@
1
- Object.defineProperty(exports, "__esModule", {
2
- value: true
3
- });
4
- exports.encryptedStream = exports.encryptMediaRetryRequest = exports.encodeBase64EncodedStringForUpload = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = void 0;
5
- exports.extensionForMediaMessage = extensionForMediaMessage;
6
- exports.generateProfilePicture = exports.extractImageThumb = void 0;
7
- exports.generateThumbnail = generateThumbnail;
8
- exports.getAudioDuration = getAudioDuration;
9
- exports.getAudioWaveform = getAudioWaveform;
10
- exports.getHttpStream = void 0;
11
- exports.getMediaKeys = getMediaKeys;
12
- exports.toReadable = exports.toBuffer = exports.mediaMessageSHA256B64 = exports.hkdfInfoKey = exports.getWAUploadToServer = exports.getUrlFromDirectPath = exports.getStream = exports.getStatusCodeForMediaRetry = exports.getRawMediaUploadData = void 0;
13
- var _boom = require("@hapi/boom");
14
- var _axios = _interopRequireDefault(require("axios"));
15
- var _child_process = require("child_process");
16
- var Crypto = _interopRequireWildcard(require("crypto"));
17
- var _events = require("events");
18
- var _fs = require("fs");
19
- var _os = require("os");
20
- var _path = require("path");
21
- var _stream = require("stream");
22
- var _url = require("url");
23
- var _index = require("../../WAProto/index.js");
24
- var _index2 = require("../Defaults/index.js");
25
- var _index3 = require("../WABinary/index.js");
26
- var _crypto2 = require("./crypto.js");
27
- var _generics = require("./generics.js");
28
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
29
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
30
- const getTmpFilesDirectory = () => (0, _os.tmpdir)();
1
+ import { Boom } from '@hapi/boom';
2
+ import { exec } from 'child_process';
3
+ import * as Crypto from 'crypto';
4
+ import { once } from 'events';
5
+ import { createReadStream, createWriteStream, promises as fs, WriteStream } from 'fs';
6
+ import { tmpdir } from 'os';
7
+ import { join } from 'path';
8
+ import { Readable, Transform } from 'stream';
9
+ import { URL } from 'url';
10
+ import { proto } from '../../WAProto/index.js';
11
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults/index.js';
12
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
13
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
14
+ import { generateMessageIDV2 } from './generics.js';
15
+ const getTmpFilesDirectory = () => tmpdir();
31
16
  const getImageProcessingLibrary = async () => {
32
- //@ts-ignore
33
- const [jimp, sharp] = await Promise.all([import('jimp').catch(() => {}), import('sharp').catch(() => {})]);
34
- if (sharp) {
35
- return {
36
- sharp
37
- };
38
- }
39
- if (jimp) {
40
- return {
41
- jimp
42
- };
43
- }
44
- throw new _boom.Boom('No image processing library available');
17
+ //@ts-ignore
18
+ const [jimp, sharp] = await Promise.all([import('jimp').catch(() => { }), import('sharp').catch(() => { })]);
19
+ if (sharp) {
20
+ return { sharp };
21
+ }
22
+ if (jimp) {
23
+ return { jimp };
24
+ }
25
+ throw new Boom('No image processing library available');
45
26
  };
46
- const hkdfInfoKey = type => {
47
- const hkdfInfo = _index2.MEDIA_HKDF_KEY_MAPPING[type];
48
- return `WhatsApp ${hkdfInfo} Keys`;
27
+ export const hkdfInfoKey = (type) => {
28
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
29
+ return `WhatsApp ${hkdfInfo} Keys`;
49
30
  };
50
- exports.hkdfInfoKey = hkdfInfoKey;
51
- const getRawMediaUploadData = async (media, mediaType, logger) => {
52
- const {
53
- stream
54
- } = await getStream(media);
55
- logger?.debug('got stream for raw upload');
56
- const hasher = Crypto.createHash('sha256');
57
- const filePath = (0, _path.join)((0, _os.tmpdir)(), mediaType + (0, _generics.generateMessageIDV2)());
58
- const fileWriteStream = (0, _fs.createWriteStream)(filePath);
59
- let fileLength = 0;
60
- try {
61
- for await (const data of stream) {
62
- fileLength += data.length;
63
- hasher.update(data);
64
- if (!fileWriteStream.write(data)) {
65
- await (0, _events.once)(fileWriteStream, 'drain');
66
- }
67
- }
68
- fileWriteStream.end();
69
- await (0, _events.once)(fileWriteStream, 'finish');
70
- stream.destroy();
71
- const fileSha256 = hasher.digest();
72
- logger?.debug('hashed data for raw upload');
73
- return {
74
- filePath: filePath,
75
- fileSha256,
76
- fileLength
77
- };
78
- } catch (error) {
79
- fileWriteStream.destroy();
80
- stream.destroy();
31
+ export const getRawMediaUploadData = async (media, mediaType, logger) => {
32
+ const { stream } = await getStream(media);
33
+ logger?.debug('got stream for raw upload');
34
+ const hasher = Crypto.createHash('sha256');
35
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
36
+ const fileWriteStream = createWriteStream(filePath);
37
+ let fileLength = 0;
81
38
  try {
82
- await _fs.promises.unlink(filePath);
83
- } catch {
84
- //
39
+ for await (const data of stream) {
40
+ fileLength += data.length;
41
+ hasher.update(data);
42
+ if (!fileWriteStream.write(data)) {
43
+ await once(fileWriteStream, 'drain');
44
+ }
45
+ }
46
+ fileWriteStream.end();
47
+ await once(fileWriteStream, 'finish');
48
+ stream.destroy();
49
+ const fileSha256 = hasher.digest();
50
+ logger?.debug('hashed data for raw upload');
51
+ return {
52
+ filePath: filePath,
53
+ fileSha256,
54
+ fileLength
55
+ };
56
+ }
57
+ catch (error) {
58
+ fileWriteStream.destroy();
59
+ stream.destroy();
60
+ try {
61
+ await fs.unlink(filePath);
62
+ }
63
+ catch {
64
+ //
65
+ }
66
+ throw error;
85
67
  }
86
- throw error;
87
- }
88
68
  };
89
69
  /** generates all the keys required to encrypt/decrypt & sign a media message */
90
- exports.getRawMediaUploadData = getRawMediaUploadData;
91
- async function getMediaKeys(buffer, mediaType) {
92
- if (!buffer) {
93
- throw new _boom.Boom('Cannot derive from empty media key');
94
- }
95
- if (typeof buffer === 'string') {
96
- buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
97
- }
98
- // expand using HKDF to 112 bytes, also pass in the relevant app info
99
- const expandedMediaKey = await (0, _crypto2.hkdf)(buffer, 112, {
100
- info: hkdfInfoKey(mediaType)
101
- });
102
- return {
103
- iv: expandedMediaKey.slice(0, 16),
104
- cipherKey: expandedMediaKey.slice(16, 48),
105
- macKey: expandedMediaKey.slice(48, 80)
106
- };
70
+ export async function getMediaKeys(buffer, mediaType) {
71
+ if (!buffer) {
72
+ throw new Boom('Cannot derive from empty media key');
73
+ }
74
+ if (typeof buffer === 'string') {
75
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
76
+ }
77
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
78
+ const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
79
+ return {
80
+ iv: expandedMediaKey.slice(0, 16),
81
+ cipherKey: expandedMediaKey.slice(16, 48),
82
+ macKey: expandedMediaKey.slice(48, 80)
83
+ };
107
84
  }
108
85
  /** Extracts video thumb using FFMPEG */
109
86
  const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
110
- const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
111
- (0, _child_process.exec)(cmd, err => {
112
- if (err) {
113
- reject(err);
114
- } else {
115
- resolve();
116
- }
117
- });
118
- });
119
- const extractImageThumb = async (bufferOrFilePath, width = 32) => {
120
- // TODO: Move entirely to sharp, removing jimp as it supports readable streams
121
- // This will have positive speed and performance impacts as well as minimizing RAM usage.
122
- if (bufferOrFilePath instanceof _stream.Readable) {
123
- bufferOrFilePath = await toBuffer(bufferOrFilePath);
124
- }
125
- const lib = await getImageProcessingLibrary();
126
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
127
- const img = lib.sharp.default(bufferOrFilePath);
128
- const dimensions = await img.metadata();
129
- const buffer = await img.resize(width).jpeg({
130
- quality: 50
131
- }).toBuffer();
132
- return {
133
- buffer,
134
- original: {
135
- width: dimensions.width,
136
- height: dimensions.height
137
- }
138
- };
139
- } else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
140
- const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
141
- const dimensions = {
142
- width: jimp.width,
143
- height: jimp.height
144
- };
145
- const buffer = await jimp.resize({
146
- w: width,
147
- mode: lib.jimp.ResizeStrategy.BILINEAR
148
- }).getBuffer('image/jpeg', {
149
- quality: 50
87
+ const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
88
+ exec(cmd, err => {
89
+ if (err) {
90
+ reject(err);
91
+ }
92
+ else {
93
+ resolve();
94
+ }
150
95
  });
96
+ });
97
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
98
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
99
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
100
+ if (bufferOrFilePath instanceof Readable) {
101
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
102
+ }
103
+ const lib = await getImageProcessingLibrary();
104
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
105
+ const img = lib.sharp.default(bufferOrFilePath);
106
+ const dimensions = await img.metadata();
107
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
108
+ return {
109
+ buffer,
110
+ original: {
111
+ width: dimensions.width,
112
+ height: dimensions.height
113
+ }
114
+ };
115
+ }
116
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
117
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
118
+ const dimensions = {
119
+ width: jimp.width,
120
+ height: jimp.height
121
+ };
122
+ const buffer = await jimp
123
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
124
+ .getBuffer('image/jpeg', { quality: 50 });
125
+ return {
126
+ buffer,
127
+ original: dimensions
128
+ };
129
+ }
130
+ else {
131
+ throw new Boom('No image processing library available');
132
+ }
133
+ };
134
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
135
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
136
+ let buffer;
137
+ const { width: w = 640, height: h = 640 } = dimensions || {};
138
+ if (Buffer.isBuffer(mediaUpload)) {
139
+ buffer = mediaUpload;
140
+ }
141
+ else {
142
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
143
+ const { stream } = await getStream(mediaUpload);
144
+ // Convert the resulting stream to a buffer
145
+ buffer = await toBuffer(stream);
146
+ }
147
+ const lib = await getImageProcessingLibrary();
148
+ let img;
149
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
150
+ img = lib.sharp
151
+ .default(buffer)
152
+ .resize(w, h)
153
+ .jpeg({
154
+ quality: 50
155
+ })
156
+ .toBuffer();
157
+ }
158
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
159
+ const jimp = await lib.jimp.Jimp.read(buffer);
160
+ const min = Math.min(jimp.width, jimp.height);
161
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
162
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
163
+ }
164
+ else {
165
+ throw new Boom('No image processing library available');
166
+ }
151
167
  return {
152
- buffer,
153
- original: dimensions
168
+ img: await img
154
169
  };
155
- } else {
156
- throw new _boom.Boom('No image processing library available');
157
- }
158
- };
159
- exports.extractImageThumb = extractImageThumb;
160
- const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
161
- exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
162
- const generateProfilePicture = async (mediaUpload, dimensions) => {
163
- let buffer;
164
- const {
165
- width: w = 640,
166
- height: h = 640
167
- } = dimensions || {};
168
- if (Buffer.isBuffer(mediaUpload)) {
169
- buffer = mediaUpload;
170
- } else {
171
- // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
172
- const {
173
- stream
174
- } = await getStream(mediaUpload);
175
- // Convert the resulting stream to a buffer
176
- buffer = await toBuffer(stream);
177
- }
178
- const lib = await getImageProcessingLibrary();
179
- let img;
180
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
181
- img = lib.sharp.default(buffer).resize(w, h).jpeg({
182
- quality: 50
183
- }).toBuffer();
184
- } else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
185
- const jimp = await lib.jimp.Jimp.read(buffer);
186
- const min = Math.min(jimp.width, jimp.height);
187
- const cropped = jimp.crop({
188
- x: 0,
189
- y: 0,
190
- w: min,
191
- h: min
192
- });
193
- img = cropped.resize({
194
- w,
195
- h,
196
- mode: lib.jimp.ResizeStrategy.BILINEAR
197
- }).getBuffer('image/jpeg', {
198
- quality: 50
199
- });
200
- } else {
201
- throw new _boom.Boom('No image processing library available');
202
- }
203
- return {
204
- img: await img
205
- };
206
170
  };
207
171
  /** gets the SHA256 of the given media message */
208
- exports.generateProfilePicture = generateProfilePicture;
209
- const mediaMessageSHA256B64 = message => {
210
- const media = Object.values(message)[0];
211
- return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
172
+ export const mediaMessageSHA256B64 = (message) => {
173
+ const media = Object.values(message)[0];
174
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
212
175
  };
213
- exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
214
- async function getAudioDuration(buffer) {
215
- const musicMetadata = await import('music-metadata');
216
- let metadata;
217
- const options = {
218
- duration: true
219
- };
220
- if (Buffer.isBuffer(buffer)) {
221
- metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
222
- } else if (typeof buffer === 'string') {
223
- metadata = await musicMetadata.parseFile(buffer, options);
224
- } else {
225
- metadata = await musicMetadata.parseStream(buffer, undefined, options);
226
- }
227
- return metadata.format.duration;
176
+ export async function getAudioDuration(buffer) {
177
+ const musicMetadata = await import('music-metadata');
178
+ let metadata;
179
+ const options = {
180
+ duration: true
181
+ };
182
+ if (Buffer.isBuffer(buffer)) {
183
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
184
+ }
185
+ else if (typeof buffer === 'string') {
186
+ metadata = await musicMetadata.parseFile(buffer, options);
187
+ }
188
+ else {
189
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
190
+ }
191
+ return metadata.format.duration;
228
192
  }
229
193
  /**
230
194
  referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
231
195
  */
232
- async function getAudioWaveform(buffer, logger) {
233
- try {
234
- // @ts-ignore
235
- const {
236
- default: decoder
237
- } = await import('audio-decode');
238
- let audioData;
239
- if (Buffer.isBuffer(buffer)) {
240
- audioData = buffer;
241
- } else if (typeof buffer === 'string') {
242
- const rStream = (0, _fs.createReadStream)(buffer);
243
- audioData = await toBuffer(rStream);
244
- } else {
245
- audioData = await toBuffer(buffer);
246
- }
247
- const audioBuffer = await decoder(audioData);
248
- const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
249
- const samples = 64; // Number of samples we want to have in our final data set
250
- const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
251
- const filteredData = [];
252
- for (let i = 0; i < samples; i++) {
253
- const blockStart = blockSize * i; // the location of the first sample in the block
254
- let sum = 0;
255
- for (let j = 0; j < blockSize; j++) {
256
- sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
257
- }
258
- filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
259
- }
260
- // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
261
- const multiplier = Math.pow(Math.max(...filteredData), -1);
262
- const normalizedData = filteredData.map(n => n * multiplier);
263
- // Generate waveform like WhatsApp
264
- const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
265
- return waveform;
266
- } catch (e) {
267
- logger?.debug('Failed to generate waveform: ' + e);
268
- }
196
+ export async function getAudioWaveform(buffer, logger) {
197
+ try {
198
+ // @ts-ignore
199
+ const { default: decoder } = await import('audio-decode');
200
+ let audioData;
201
+ if (Buffer.isBuffer(buffer)) {
202
+ audioData = buffer;
203
+ }
204
+ else if (typeof buffer === 'string') {
205
+ const rStream = createReadStream(buffer);
206
+ audioData = await toBuffer(rStream);
207
+ }
208
+ else {
209
+ audioData = await toBuffer(buffer);
210
+ }
211
+ const audioBuffer = await decoder(audioData);
212
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
213
+ const samples = 64; // Number of samples we want to have in our final data set
214
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
215
+ const filteredData = [];
216
+ for (let i = 0; i < samples; i++) {
217
+ const blockStart = blockSize * i; // the location of the first sample in the block
218
+ let sum = 0;
219
+ for (let j = 0; j < blockSize; j++) {
220
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
221
+ }
222
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
223
+ }
224
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
225
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
226
+ const normalizedData = filteredData.map(n => n * multiplier);
227
+ // Generate waveform like WhatsApp
228
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
229
+ return waveform;
230
+ }
231
+ catch (e) {
232
+ logger?.debug('Failed to generate waveform: ' + e);
233
+ }
269
234
  }
270
- const toReadable = buffer => {
271
- const readable = new _stream.Readable({
272
- read: () => {}
273
- });
274
- readable.push(buffer);
275
- readable.push(null);
276
- return readable;
235
+ export const toReadable = (buffer) => {
236
+ const readable = new Readable({ read: () => { } });
237
+ readable.push(buffer);
238
+ readable.push(null);
239
+ return readable;
277
240
  };
278
- exports.toReadable = toReadable;
279
- const toBuffer = async stream => {
280
- const chunks = [];
281
- for await (const chunk of stream) {
282
- chunks.push(chunk);
283
- }
284
- stream.destroy();
285
- return Buffer.concat(chunks);
241
+ export const toBuffer = async (stream) => {
242
+ const chunks = [];
243
+ for await (const chunk of stream) {
244
+ chunks.push(chunk);
245
+ }
246
+ stream.destroy();
247
+ return Buffer.concat(chunks);
286
248
  };
287
- exports.toBuffer = toBuffer;
288
- const getStream = async (item, opts) => {
289
- if (Buffer.isBuffer(item)) {
290
- return {
291
- stream: toReadable(item),
292
- type: 'buffer'
293
- };
294
- }
295
- if ('stream' in item) {
296
- return {
297
- stream: item.stream,
298
- type: 'readable'
299
- };
300
- }
301
- const urlStr = item.url.toString();
302
- if (urlStr.startsWith('data:')) {
303
- const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
304
- return {
305
- stream: toReadable(buffer),
306
- type: 'buffer'
307
- };
308
- }
309
- if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
310
- return {
311
- stream: await getHttpStream(item.url, opts),
312
- type: 'remote'
313
- };
314
- }
315
- return {
316
- stream: (0, _fs.createReadStream)(item.url),
317
- type: 'file'
318
- };
249
+ export const getStream = async (item, opts) => {
250
+ if (Buffer.isBuffer(item)) {
251
+ return { stream: toReadable(item), type: 'buffer' };
252
+ }
253
+ if ('stream' in item) {
254
+ return { stream: item.stream, type: 'readable' };
255
+ }
256
+ const urlStr = item.url.toString();
257
+ if (urlStr.startsWith('data:')) {
258
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
259
+ return { stream: toReadable(buffer), type: 'buffer' };
260
+ }
261
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
262
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' };
263
+ }
264
+ return { stream: createReadStream(item.url), type: 'file' };
319
265
  };
320
266
  /** generates a thumbnail for a given media, if required */
321
- exports.getStream = getStream;
322
- async function generateThumbnail(file, mediaType, options) {
323
- let thumbnail;
324
- let originalImageDimensions;
325
- if (mediaType === 'image') {
326
- const {
327
- buffer,
328
- original
329
- } = await extractImageThumb(file);
330
- thumbnail = buffer.toString('base64');
331
- if (original.width && original.height) {
332
- originalImageDimensions = {
333
- width: original.width,
334
- height: original.height
335
- };
336
- }
337
- } else if (mediaType === 'video') {
338
- const imgFilename = (0, _path.join)(getTmpFilesDirectory(), (0, _generics.generateMessageIDV2)() + '.jpg');
339
- try {
340
- await extractVideoThumb(file, imgFilename, '00:00:00', {
341
- width: 32,
342
- height: 32
343
- });
344
- const buff = await _fs.promises.readFile(imgFilename);
345
- thumbnail = buff.toString('base64');
346
- await _fs.promises.unlink(imgFilename);
347
- } catch (err) {
348
- options.logger?.debug('could not generate video thumb: ' + err);
349
- }
350
- }
351
- return {
352
- thumbnail,
353
- originalImageDimensions
354
- };
267
+ export async function generateThumbnail(file, mediaType, options) {
268
+ let thumbnail;
269
+ let originalImageDimensions;
270
+ if (mediaType === 'image') {
271
+ const { buffer, original } = await extractImageThumb(file);
272
+ thumbnail = buffer.toString('base64');
273
+ if (original.width && original.height) {
274
+ originalImageDimensions = {
275
+ width: original.width,
276
+ height: original.height
277
+ };
278
+ }
279
+ }
280
+ else if (mediaType === 'video') {
281
+ const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg');
282
+ try {
283
+ await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
284
+ const buff = await fs.readFile(imgFilename);
285
+ thumbnail = buff.toString('base64');
286
+ await fs.unlink(imgFilename);
287
+ }
288
+ catch (err) {
289
+ options.logger?.debug('could not generate video thumb: ' + err);
290
+ }
291
+ }
292
+ return {
293
+ thumbnail,
294
+ originalImageDimensions
295
+ };
355
296
  }
356
- const getHttpStream = async (url, options = {}) => {
357
- const fetched = await _axios.default.get(url.toString(), {
358
- ...options,
359
- responseType: 'stream'
360
- });
361
- return fetched.data;
297
+ export const getHttpStream = async (url, options = {}) => {
298
+ const response = await fetch(url.toString(), {
299
+ dispatcher: options.dispatcher,
300
+ method: 'GET',
301
+ headers: options.headers
302
+ });
303
+ if (!response.ok) {
304
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
305
+ }
306
+ // @ts-ignore Node18+ Readable.fromWeb exists
307
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
362
308
  };
363
- exports.getHttpStream = getHttpStream;
364
- const encryptedStream = async (media, mediaType, {
365
- logger,
366
- saveOriginalFileIfRequired,
367
- opts
368
- } = {}) => {
369
- const {
370
- stream,
371
- type
372
- } = await getStream(media, opts);
373
- logger?.debug('fetched media stream');
374
- const mediaKey = Crypto.randomBytes(32);
375
- const {
376
- cipherKey,
377
- iv,
378
- macKey
379
- } = await getMediaKeys(mediaKey, mediaType);
380
- const encFilePath = (0, _path.join)(getTmpFilesDirectory(), mediaType + (0, _generics.generateMessageIDV2)() + '-enc');
381
- const encFileWriteStream = (0, _fs.createWriteStream)(encFilePath);
382
- let originalFileStream;
383
- let originalFilePath;
384
- if (saveOriginalFileIfRequired) {
385
- originalFilePath = (0, _path.join)(getTmpFilesDirectory(), mediaType + (0, _generics.generateMessageIDV2)() + '-original');
386
- originalFileStream = (0, _fs.createWriteStream)(originalFilePath);
387
- }
388
- let fileLength = 0;
389
- const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
390
- const hmac = Crypto.createHmac('sha256', macKey).update(iv);
391
- const sha256Plain = Crypto.createHash('sha256');
392
- const sha256Enc = Crypto.createHash('sha256');
393
- const onChunk = buff => {
394
- sha256Enc.update(buff);
395
- hmac.update(buff);
396
- encFileWriteStream.write(buff);
397
- };
398
- try {
399
- for await (const data of stream) {
400
- fileLength += data.length;
401
- if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
402
- throw new _boom.Boom(`content length exceeded when encrypting "${type}"`, {
403
- data: {
404
- media,
405
- type
406
- }
407
- });
408
- }
409
- if (originalFileStream) {
410
- if (!originalFileStream.write(data)) {
411
- await (0, _events.once)(originalFileStream, 'drain');
309
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
310
+ const { stream, type } = await getStream(media, opts);
311
+ logger?.debug('fetched media stream');
312
+ const mediaKey = Crypto.randomBytes(32);
313
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
314
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
315
+ const encFileWriteStream = createWriteStream(encFilePath);
316
+ let originalFileStream;
317
+ let originalFilePath;
318
+ if (saveOriginalFileIfRequired) {
319
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
320
+ originalFileStream = createWriteStream(originalFilePath);
321
+ }
322
+ let fileLength = 0;
323
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
324
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv);
325
+ const sha256Plain = Crypto.createHash('sha256');
326
+ const sha256Enc = Crypto.createHash('sha256');
327
+ const onChunk = async (buff) => {
328
+ sha256Enc.update(buff);
329
+ hmac.update(buff);
330
+ // Handle backpressure: if write returns false, wait for drain
331
+ if (!encFileWriteStream.write(buff)) {
332
+ await once(encFileWriteStream, 'drain');
412
333
  }
413
- }
414
- sha256Plain.update(data);
415
- onChunk(aes.update(data));
416
- }
417
- onChunk(aes.final());
418
- const mac = hmac.digest().slice(0, 10);
419
- sha256Enc.update(mac);
420
- const fileSha256 = sha256Plain.digest();
421
- const fileEncSha256 = sha256Enc.digest();
422
- encFileWriteStream.write(mac);
423
- encFileWriteStream.end();
424
- originalFileStream?.end?.();
425
- stream.destroy();
426
- logger?.debug('encrypted data successfully');
427
- return {
428
- mediaKey,
429
- originalFilePath,
430
- encFilePath,
431
- mac,
432
- fileEncSha256,
433
- fileSha256,
434
- fileLength
435
334
  };
436
- } catch (error) {
437
- // destroy all streams with error
438
- encFileWriteStream.destroy();
439
- originalFileStream?.destroy?.();
440
- aes.destroy();
441
- hmac.destroy();
442
- sha256Plain.destroy();
443
- sha256Enc.destroy();
444
- stream.destroy();
445
335
  try {
446
- await _fs.promises.unlink(encFilePath);
447
- if (originalFilePath) {
448
- await _fs.promises.unlink(originalFilePath);
449
- }
450
- } catch (err) {
451
- logger?.error({
452
- err
453
- }, 'failed deleting tmp files');
454
- }
455
- throw error;
456
- }
336
+ for await (const data of stream) {
337
+ fileLength += data.length;
338
+ if (type === 'remote' &&
339
+ opts?.maxContentLength &&
340
+ fileLength + data.length > opts.maxContentLength) {
341
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
342
+ data: { media, type }
343
+ });
344
+ }
345
+ if (originalFileStream) {
346
+ if (!originalFileStream.write(data)) {
347
+ await once(originalFileStream, 'drain');
348
+ }
349
+ }
350
+ sha256Plain.update(data);
351
+ await onChunk(aes.update(data));
352
+ }
353
+ await onChunk(aes.final());
354
+ const mac = hmac.digest().slice(0, 10);
355
+ sha256Enc.update(mac);
356
+ const fileSha256 = sha256Plain.digest();
357
+ const fileEncSha256 = sha256Enc.digest();
358
+ encFileWriteStream.write(mac);
359
+ const encFinishPromise = once(encFileWriteStream, 'finish');
360
+ const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
361
+ encFileWriteStream.end();
362
+ originalFileStream?.end?.();
363
+ stream.destroy();
364
+ // Wait for write streams to fully flush to disk
365
+ // This helps reduce memory pressure by allowing OS to release buffers
366
+ await encFinishPromise;
367
+ await originalFinishPromise;
368
+ logger?.debug('encrypted data successfully');
369
+ return {
370
+ mediaKey,
371
+ originalFilePath,
372
+ encFilePath,
373
+ mac,
374
+ fileEncSha256,
375
+ fileSha256,
376
+ fileLength
377
+ };
378
+ }
379
+ catch (error) {
380
+ // destroy all streams with error
381
+ encFileWriteStream.destroy();
382
+ originalFileStream?.destroy?.();
383
+ aes.destroy();
384
+ hmac.destroy();
385
+ sha256Plain.destroy();
386
+ sha256Enc.destroy();
387
+ stream.destroy();
388
+ try {
389
+ await fs.unlink(encFilePath);
390
+ if (originalFilePath) {
391
+ await fs.unlink(originalFilePath);
392
+ }
393
+ }
394
+ catch (err) {
395
+ logger?.error({ err }, 'failed deleting tmp files');
396
+ }
397
+ throw error;
398
+ }
457
399
  };
458
- exports.encryptedStream = encryptedStream;
459
- const DEF_HOST = 'mmg.whatsapp.net';
400
+ export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
460
401
  const AES_CHUNK_SIZE = 16;
461
- const toSmallestChunkSize = num => {
462
- return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
402
+ const toSmallestChunkSize = (num) => {
403
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
463
404
  };
464
- const getUrlFromDirectPath = directPath => `https://${DEF_HOST}${directPath}`;
465
- exports.getUrlFromDirectPath = getUrlFromDirectPath;
466
- const downloadContentFromMessage = async ({
467
- mediaKey,
468
- directPath,
469
- url
470
- }, type, opts = {}) => {
471
- const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
472
- const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
473
- if (!downloadUrl) {
474
- throw new _boom.Boom('No valid media URL or directPath present in message', {
475
- statusCode: 400
476
- });
477
- }
478
- const keys = await getMediaKeys(mediaKey, type);
479
- return downloadEncryptedContent(downloadUrl, keys, opts);
405
+ export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
406
+ const extractHost = (url) => {
407
+ if (!url)
408
+ return undefined;
409
+ try {
410
+ return new URL(url).host;
411
+ }
412
+ catch {
413
+ return undefined;
414
+ }
415
+ };
416
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
417
+ // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
418
+ // Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
419
+ const fallbackHost = opts.host ?? extractHost(url);
420
+ const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
421
+ if (!downloadUrl) {
422
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
423
+ }
424
+ const keys = await getMediaKeys(mediaKey, type);
425
+ return downloadEncryptedContent(downloadUrl, keys, opts);
480
426
  };
481
427
  /**
482
428
  * Decrypts and downloads an AES256-CBC encrypted file given the keys.
483
429
  * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
484
430
  * */
485
- exports.downloadContentFromMessage = downloadContentFromMessage;
486
- const downloadEncryptedContent = async (downloadUrl, {
487
- cipherKey,
488
- iv
489
- }, {
490
- startByte,
491
- endByte,
492
- options
493
- } = {}) => {
494
- let bytesFetched = 0;
495
- let startChunk = 0;
496
- let firstBlockIsIV = false;
497
- // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
498
- if (startByte) {
499
- const chunk = toSmallestChunkSize(startByte || 0);
500
- if (chunk) {
501
- startChunk = chunk - AES_CHUNK_SIZE;
502
- bytesFetched = chunk;
503
- firstBlockIsIV = true;
504
- }
505
- }
506
- const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
507
- const headers = {
508
- ...(options?.headers || {}),
509
- Origin: _index2.DEFAULT_ORIGIN
510
- };
511
- if (startChunk || endChunk) {
512
- headers.Range = `bytes=${startChunk}-`;
513
- if (endChunk) {
514
- headers.Range += endChunk;
515
- }
516
- }
517
- // download the message
518
- const fetched = await getHttpStream(downloadUrl, {
519
- ...(options || {}),
520
- headers,
521
- maxBodyLength: Infinity,
522
- maxContentLength: Infinity
523
- });
524
- let remainingBytes = Buffer.from([]);
525
- let aes;
526
- const pushBytes = (bytes, push) => {
527
- if (startByte || endByte) {
528
- const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
529
- const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
530
- push(bytes.slice(start, end));
531
- bytesFetched += bytes.length;
532
- } else {
533
- push(bytes);
534
- }
535
- };
536
- const output = new _stream.Transform({
537
- transform(chunk, _, callback) {
538
- let data = Buffer.concat([remainingBytes, chunk]);
539
- const decryptLength = toSmallestChunkSize(data.length);
540
- remainingBytes = data.slice(decryptLength);
541
- data = data.slice(0, decryptLength);
542
- if (!aes) {
543
- let ivValue = iv;
544
- if (firstBlockIsIV) {
545
- ivValue = data.slice(0, AES_CHUNK_SIZE);
546
- data = data.slice(AES_CHUNK_SIZE);
431
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
432
+ let bytesFetched = 0;
433
+ let startChunk = 0;
434
+ let firstBlockIsIV = false;
435
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
436
+ if (startByte) {
437
+ const chunk = toSmallestChunkSize(startByte || 0);
438
+ if (chunk) {
439
+ startChunk = chunk - AES_CHUNK_SIZE;
440
+ bytesFetched = chunk;
441
+ firstBlockIsIV = true;
547
442
  }
548
- aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
549
- // if an end byte that is not EOF is specified
550
- // stop auto padding (PKCS7) -- otherwise throws an error for decryption
551
- if (endByte) {
552
- aes.setAutoPadding(false);
443
+ }
444
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
445
+ const headersInit = options?.headers ? options.headers : undefined;
446
+ const headers = {
447
+ ...(headersInit
448
+ ? Array.isArray(headersInit)
449
+ ? Object.fromEntries(headersInit)
450
+ : headersInit
451
+ : {}),
452
+ Origin: DEFAULT_ORIGIN
453
+ };
454
+ if (startChunk || endChunk) {
455
+ headers.Range = `bytes=${startChunk}-`;
456
+ if (endChunk) {
457
+ headers.Range += endChunk;
458
+ }
459
+ }
460
+ // download the message
461
+ const fetched = await getHttpStream(downloadUrl, {
462
+ ...(options || {}),
463
+ headers
464
+ });
465
+ let remainingBytes = Buffer.from([]);
466
+ let aes;
467
+ const pushBytes = (bytes, push) => {
468
+ if (startByte || endByte) {
469
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
470
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
471
+ push(bytes.slice(start, end));
472
+ bytesFetched += bytes.length;
473
+ }
474
+ else {
475
+ push(bytes);
476
+ }
477
+ };
478
+ const output = new Transform({
479
+ transform(chunk, _, callback) {
480
+ let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
481
+ const decryptLength = toSmallestChunkSize(data.length);
482
+ remainingBytes = data.slice(decryptLength);
483
+ data = data.slice(0, decryptLength);
484
+ if (!aes) {
485
+ let ivValue = iv;
486
+ if (firstBlockIsIV) {
487
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
488
+ data = data.slice(AES_CHUNK_SIZE);
489
+ }
490
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
491
+ // if an end byte that is not EOF is specified
492
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
493
+ if (endByte) {
494
+ aes.setAutoPadding(false);
495
+ }
496
+ }
497
+ try {
498
+ pushBytes(aes.update(data), b => this.push(b));
499
+ callback();
500
+ }
501
+ catch (error) {
502
+ callback(error);
503
+ }
504
+ },
505
+ final(callback) {
506
+ try {
507
+ pushBytes(aes.final(), b => this.push(b));
508
+ callback();
509
+ }
510
+ catch (error) {
511
+ callback(error);
512
+ }
553
513
  }
554
- }
555
- try {
556
- pushBytes(aes.update(data), b => this.push(b));
557
- callback();
558
- } catch (error) {
559
- callback(error);
560
- }
561
- },
562
- final(callback) {
563
- try {
564
- pushBytes(aes.final(), b => this.push(b));
565
- callback();
566
- } catch (error) {
567
- callback(error);
568
- }
569
- }
570
- });
571
- return fetched.pipe(output, {
572
- end: true
573
- });
514
+ });
515
+ return fetched.pipe(output, { end: true });
574
516
  };
575
- exports.downloadEncryptedContent = downloadEncryptedContent;
576
- function extensionForMediaMessage(message) {
577
- const getExtension = mimetype => mimetype.split(';')[0]?.split('/')[1];
578
- const type = Object.keys(message)[0];
579
- let extension;
580
- if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
581
- extension = '.jpeg';
582
- } else {
583
- const messageContent = message[type];
584
- extension = getExtension(messageContent.mimetype);
585
- }
586
- return extension;
517
+ export function extensionForMediaMessage(message) {
518
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
519
+ const type = Object.keys(message)[0];
520
+ let extension;
521
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
522
+ extension = '.jpeg';
523
+ }
524
+ else {
525
+ const messageContent = message[type];
526
+ extension = getExtension(messageContent.mimetype);
527
+ }
528
+ return extension;
587
529
  }
588
- const getWAUploadToServer = ({
589
- customUploadHosts,
590
- fetchAgent,
591
- logger,
592
- options
593
- }, refreshMediaConn) => {
594
- return async (filePath, {
595
- mediaType,
596
- fileEncSha256B64,
597
- timeoutMs
598
- }) => {
599
- // send a query JSON to obtain the url & auth token to upload our media
600
- let uploadInfo = await refreshMediaConn(false);
601
- let urls;
602
- const hosts = [...customUploadHosts, ...uploadInfo.hosts];
603
- fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
604
- for (const {
605
- hostname
606
- } of hosts) {
607
- logger.debug(`uploading to "${hostname}"`);
608
- const auth = encodeURIComponent(uploadInfo.auth); // the auth token
609
- const url = `https://${hostname}${_index2.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
610
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
611
- let result;
612
- try {
613
- const body = await _axios.default.post(url, (0, _fs.createReadStream)(filePath), {
614
- ...options,
615
- maxRedirects: 0,
616
- headers: {
617
- ...(options.headers || {}),
618
- 'Content-Type': 'application/octet-stream',
619
- Origin: _index2.DEFAULT_ORIGIN
620
- },
621
- httpsAgent: fetchAgent,
622
- timeout: timeoutMs,
623
- responseType: 'json',
624
- maxBodyLength: Infinity,
625
- maxContentLength: Infinity
530
+ const isNodeRuntime = () => {
531
+ return (typeof process !== 'undefined' &&
532
+ process.versions?.node !== null &&
533
+ typeof process.versions.bun === 'undefined' &&
534
+ typeof globalThis.Deno === 'undefined');
535
+ };
536
+ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
537
+ if (redirectCount > 5) {
538
+ throw new Error('Too many redirects');
539
+ }
540
+ const parsedUrl = new URL(url);
541
+ const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
542
+ // Get file size for Content-Length header (required for Node.js streaming)
543
+ const fileStats = await fs.stat(filePath);
544
+ const fileSize = fileStats.size;
545
+ return new Promise((resolve, reject) => {
546
+ const req = httpModule.request({
547
+ hostname: parsedUrl.hostname,
548
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
549
+ path: parsedUrl.pathname + parsedUrl.search,
550
+ method: 'POST',
551
+ headers: {
552
+ ...headers,
553
+ 'Content-Length': fileSize
554
+ },
555
+ agent,
556
+ timeout: timeoutMs
557
+ }, res => {
558
+ // Handle redirects (3xx)
559
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
560
+ res.resume(); // Consume response to free resources
561
+ const newUrl = new URL(res.headers.location, url).toString();
562
+ resolve(uploadWithNodeHttp({
563
+ url: newUrl,
564
+ filePath,
565
+ headers,
566
+ timeoutMs,
567
+ agent
568
+ }, redirectCount + 1));
569
+ return;
570
+ }
571
+ let body = '';
572
+ res.on('data', chunk => (body += chunk));
573
+ res.on('end', () => {
574
+ try {
575
+ resolve(JSON.parse(body));
576
+ }
577
+ catch {
578
+ resolve(undefined);
579
+ }
580
+ });
581
+ });
582
+ req.on('error', reject);
583
+ req.on('timeout', () => {
584
+ req.destroy();
585
+ reject(new Error('Upload timeout'));
626
586
  });
627
- result = body.data;
628
- if (result?.url || result?.directPath) {
629
- urls = {
630
- mediaUrl: result.url,
631
- directPath: result.direct_path,
632
- meta_hmac: result.meta_hmac,
633
- fbid: result.fbid,
634
- ts: result.ts
635
- };
636
- break;
637
- } else {
638
- uploadInfo = await refreshMediaConn(true);
639
- throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
587
+ const stream = createReadStream(filePath);
588
+ stream.pipe(req);
589
+ stream.on('error', err => {
590
+ req.destroy();
591
+ reject(err);
592
+ });
593
+ });
594
+ };
595
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
596
+ // Convert Node.js Readable to Web ReadableStream
597
+ const nodeStream = createReadStream(filePath);
598
+ const webStream = Readable.toWeb(nodeStream);
599
+ // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
600
+ const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
601
+ const response = await fetch(url, {
602
+ ...(dispatcher ? { dispatcher } : {}),
603
+ method: 'POST',
604
+ body: webStream,
605
+ headers,
606
+ duplex: 'half',
607
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
608
+ });
609
+ try {
610
+ return (await response.json());
611
+ }
612
+ catch {
613
+ return undefined;
614
+ }
615
+ };
616
+ /**
617
+ * Uploads media to WhatsApp servers.
618
+ *
619
+ * ## Why we have two upload implementations:
620
+ *
621
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
622
+ * the entire request body in memory before sending, even when using streams.
623
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
624
+ * See: https://github.com/nodejs/undici/issues/4058
625
+ *
626
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
627
+ * buffering, so we can use the web-standard Fetch API there.
628
+ *
629
+ * ## Future considerations:
630
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
631
+ * across all runtimes. Monitor the GitHub issue for updates.
632
+ */
633
+ const uploadMedia = async (params, logger) => {
634
+ if (isNodeRuntime()) {
635
+ logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
636
+ return uploadWithNodeHttp(params);
637
+ }
638
+ else {
639
+ logger?.debug('Using web-standard Fetch API for upload');
640
+ return uploadWithFetch(params);
641
+ }
642
+ };
643
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
644
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
645
+ // send a query JSON to obtain the url & auth token to upload our media
646
+ let uploadInfo = await refreshMediaConn(false);
647
+ let urls;
648
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
649
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
650
+ // Prepare common headers
651
+ const customHeaders = (() => {
652
+ const hdrs = options?.headers;
653
+ if (!hdrs)
654
+ return {};
655
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
656
+ })();
657
+ const headers = {
658
+ ...customHeaders,
659
+ 'Content-Type': 'application/octet-stream',
660
+ Origin: DEFAULT_ORIGIN
661
+ };
662
+ for (const { hostname } of hosts) {
663
+ logger.debug(`uploading to "${hostname}"`);
664
+ const auth = encodeURIComponent(uploadInfo.auth);
665
+ const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
666
+ let result;
667
+ try {
668
+ result = await uploadMedia({
669
+ url,
670
+ filePath,
671
+ headers,
672
+ timeoutMs,
673
+ agent: fetchAgent
674
+ }, logger);
675
+ if (result?.url || result?.direct_path) {
676
+ urls = {
677
+ mediaUrl: result.url,
678
+ directPath: result.direct_path,
679
+ meta_hmac: result.meta_hmac,
680
+ fbid: result.fbid,
681
+ ts: result.ts
682
+ };
683
+ break;
684
+ }
685
+ else {
686
+ uploadInfo = await refreshMediaConn(true);
687
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
688
+ }
689
+ }
690
+ catch (error) {
691
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
692
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
693
+ }
640
694
  }
641
- } catch (error) {
642
- if (_axios.default.isAxiosError(error)) {
643
- result = error.response?.data;
695
+ if (!urls) {
696
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
644
697
  }
645
- const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
646
- logger.warn({
647
- trace: error.stack,
648
- uploadResult: result
649
- }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
650
- }
651
- }
652
- if (!urls) {
653
- throw new _boom.Boom('Media upload failed on all hosts', {
654
- statusCode: 500
655
- });
656
- }
657
- return urls;
658
- };
698
+ return urls;
699
+ };
659
700
  };
660
- exports.getWAUploadToServer = getWAUploadToServer;
661
- const getMediaRetryKey = mediaKey => {
662
- return (0, _crypto2.hkdf)(mediaKey, 32, {
663
- info: 'WhatsApp Media Retry Notification'
664
- });
701
+ const getMediaRetryKey = (mediaKey) => {
702
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
665
703
  };
666
704
  /**
667
705
  * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
668
706
  */
669
- const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
670
- const recp = {
671
- stanzaId: key.id
672
- };
673
- const recpBuffer = _index.proto.ServerErrorReceipt.encode(recp).finish();
674
- const iv = Crypto.randomBytes(12);
675
- const retryKey = await getMediaRetryKey(mediaKey);
676
- const ciphertext = (0, _crypto2.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
677
- const req = {
678
- tag: 'receipt',
679
- attrs: {
680
- id: key.id,
681
- to: (0, _index3.jidNormalizedUser)(meId),
682
- type: 'server-error'
683
- },
684
- content: [
685
- // this encrypt node is actually pretty useless
686
- // the media is returned even without this node
687
- // keeping it here to maintain parity with WA Web
688
- {
689
- tag: 'encrypt',
690
- attrs: {},
691
- content: [{
692
- tag: 'enc_p',
693
- attrs: {},
694
- content: ciphertext
695
- }, {
696
- tag: 'enc_iv',
697
- attrs: {},
698
- content: iv
699
- }]
700
- }, {
701
- tag: 'rmr',
702
- attrs: {
703
- jid: key.remoteJid,
704
- from_me: (!!key.fromMe).toString(),
705
- // @ts-ignore
706
- participant: key.participant || undefined
707
- }
708
- }]
709
- };
710
- return req;
707
+ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
708
+ const recp = { stanzaId: key.id };
709
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
710
+ const iv = Crypto.randomBytes(12);
711
+ const retryKey = getMediaRetryKey(mediaKey);
712
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
713
+ const req = {
714
+ tag: 'receipt',
715
+ attrs: {
716
+ id: key.id,
717
+ to: jidNormalizedUser(meId),
718
+ type: 'server-error'
719
+ },
720
+ content: [
721
+ // this encrypt node is actually pretty useless
722
+ // the media is returned even without this node
723
+ // keeping it here to maintain parity with WA Web
724
+ {
725
+ tag: 'encrypt',
726
+ attrs: {},
727
+ content: [
728
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
729
+ { tag: 'enc_iv', attrs: {}, content: iv }
730
+ ]
731
+ },
732
+ {
733
+ tag: 'rmr',
734
+ attrs: {
735
+ jid: key.remoteJid,
736
+ from_me: (!!key.fromMe).toString(),
737
+ // @ts-ignore
738
+ participant: key.participant || undefined
739
+ }
740
+ }
741
+ ]
742
+ };
743
+ return req;
711
744
  };
712
- exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
713
- const decodeMediaRetryNode = node => {
714
- const rmrNode = (0, _index3.getBinaryNodeChild)(node, 'rmr');
715
- const event = {
716
- key: {
717
- id: node.attrs.id,
718
- remoteJid: rmrNode.attrs.jid,
719
- fromMe: rmrNode.attrs.from_me === 'true',
720
- participant: rmrNode.attrs.participant
721
- }
722
- };
723
- const errorNode = (0, _index3.getBinaryNodeChild)(node, 'error');
724
- if (errorNode) {
725
- const errorCode = +errorNode.attrs.code;
726
- event.error = new _boom.Boom(`Failed to re-upload media (${errorCode})`, {
727
- data: errorNode.attrs,
728
- statusCode: getStatusCodeForMediaRetry(errorCode)
729
- });
730
- } else {
731
- const encryptedInfoNode = (0, _index3.getBinaryNodeChild)(node, 'encrypt');
732
- const ciphertext = (0, _index3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
733
- const iv = (0, _index3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
734
- if (ciphertext && iv) {
735
- event.media = {
736
- ciphertext,
737
- iv
738
- };
739
- } else {
740
- event.error = new _boom.Boom('Failed to re-upload media (missing ciphertext)', {
741
- statusCode: 404
742
- });
743
- }
744
- }
745
- return event;
745
+ export const decodeMediaRetryNode = (node) => {
746
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
747
+ const event = {
748
+ key: {
749
+ id: node.attrs.id,
750
+ remoteJid: rmrNode.attrs.jid,
751
+ fromMe: rmrNode.attrs.from_me === 'true',
752
+ participant: rmrNode.attrs.participant
753
+ }
754
+ };
755
+ const errorNode = getBinaryNodeChild(node, 'error');
756
+ if (errorNode) {
757
+ const errorCode = +errorNode.attrs.code;
758
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
759
+ data: errorNode.attrs,
760
+ statusCode: getStatusCodeForMediaRetry(errorCode)
761
+ });
762
+ }
763
+ else {
764
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
765
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
766
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
767
+ if (ciphertext && iv) {
768
+ event.media = { ciphertext, iv };
769
+ }
770
+ else {
771
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
772
+ }
773
+ }
774
+ return event;
746
775
  };
747
- exports.decodeMediaRetryNode = decodeMediaRetryNode;
748
- const decryptMediaRetryData = async ({
749
- ciphertext,
750
- iv
751
- }, mediaKey, msgId) => {
752
- const retryKey = await getMediaRetryKey(mediaKey);
753
- const plaintext = (0, _crypto2.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
754
- return _index.proto.MediaRetryNotification.decode(plaintext);
776
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
777
+ const retryKey = getMediaRetryKey(mediaKey);
778
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
779
+ return proto.MediaRetryNotification.decode(plaintext);
755
780
  };
756
- exports.decryptMediaRetryData = decryptMediaRetryData;
757
- const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code];
758
- exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
781
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
759
782
  const MEDIA_RETRY_STATUS_MAP = {
760
- [_index.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
761
- [_index.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
762
- [_index.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
763
- [_index.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
764
- };
783
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
784
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
785
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
786
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
787
+ };
788
+ //# sourceMappingURL=messages-media.js.map