@periskope/baileys 6.7.18-alpha.2 → 6.7.18-alpha.21

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 (372) hide show
  1. package/README.md +1 -1
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +4633 -0
  4. package/WAProto/fix-imports.js +29 -0
  5. package/WAProto/index.js +4136 -4138
  6. package/lib/Defaults/index.d.ts +4 -3
  7. package/lib/Defaults/index.d.ts.map +1 -0
  8. package/lib/Defaults/index.js +36 -40
  9. package/lib/Defaults/index.js.map +1 -0
  10. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.js +30 -0
  17. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  18. package/lib/Signal/Group/group_cipher.d.ts +18 -0
  19. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  20. package/lib/Signal/Group/group_cipher.js +94 -0
  21. package/lib/Signal/Group/group_cipher.js.map +1 -0
  22. package/lib/Signal/Group/index.d.ts +12 -0
  23. package/lib/Signal/Group/index.d.ts.map +1 -0
  24. package/lib/Signal/Group/index.js +12 -0
  25. package/lib/Signal/Group/index.js.map +1 -0
  26. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  27. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  28. package/lib/Signal/Group/keyhelper.js +19 -0
  29. package/lib/Signal/Group/keyhelper.js.map +1 -0
  30. package/lib/Signal/Group/queue-job.d.ts +2 -0
  31. package/lib/Signal/Group/queue-job.d.ts.map +1 -0
  32. package/lib/Signal/Group/queue-job.js +54 -0
  33. package/lib/Signal/Group/queue-job.js.map +1 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  35. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  36. package/lib/Signal/Group/sender-chain-key.js +32 -0
  37. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  41. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  43. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  44. package/lib/Signal/Group/sender-key-message.js +67 -0
  45. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  47. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  48. package/lib/Signal/Group/sender-key-name.js +48 -0
  49. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  51. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  52. package/lib/Signal/Group/sender-key-record.js +50 -0
  53. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  55. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  56. package/lib/Signal/Group/sender-key-state.js +96 -0
  57. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  59. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  60. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +27 -39
  61. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  62. package/lib/Signal/libsignal.d.ts +3 -2
  63. package/lib/Signal/libsignal.d.ts.map +1 -0
  64. package/lib/Signal/libsignal.js +37 -57
  65. package/lib/Signal/libsignal.js.map +1 -0
  66. package/lib/Socket/Client/index.d.ts +3 -2
  67. package/lib/Socket/Client/index.d.ts.map +1 -0
  68. package/lib/Socket/Client/index.js +3 -18
  69. package/lib/Socket/Client/index.js.map +1 -0
  70. package/lib/Socket/Client/types.d.ts +2 -1
  71. package/lib/Socket/Client/types.d.ts.map +1 -0
  72. package/lib/Socket/Client/types.js +4 -6
  73. package/lib/Socket/Client/types.js.map +1 -0
  74. package/lib/Socket/Client/websocket.d.ts +2 -1
  75. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  76. package/lib/Socket/Client/websocket.js +14 -26
  77. package/lib/Socket/Client/websocket.js.map +1 -0
  78. package/lib/Socket/business.d.ts +88 -59
  79. package/lib/Socket/business.d.ts.map +1 -0
  80. package/lib/Socket/business.js +32 -37
  81. package/lib/Socket/business.js.map +1 -0
  82. package/lib/Socket/chats.d.ts +27 -21
  83. package/lib/Socket/chats.d.ts.map +1 -0
  84. package/lib/Socket/chats.js +132 -119
  85. package/lib/Socket/chats.js.map +1 -0
  86. package/lib/Socket/communities.d.ts +218 -0
  87. package/lib/Socket/communities.d.ts.map +1 -0
  88. package/lib/Socket/communities.js +351 -0
  89. package/lib/Socket/communities.js.map +1 -0
  90. package/lib/Socket/groups.d.ts +42 -35
  91. package/lib/Socket/groups.d.ts.map +1 -0
  92. package/lib/Socket/groups.js +57 -63
  93. package/lib/Socket/groups.js.map +1 -0
  94. package/lib/Socket/index.d.ts +124 -65
  95. package/lib/Socket/index.d.ts.map +1 -0
  96. package/lib/Socket/index.js +6 -7
  97. package/lib/Socket/index.js.map +1 -0
  98. package/lib/Socket/messages-recv.d.ts +74 -45
  99. package/lib/Socket/messages-recv.d.ts.map +1 -0
  100. package/lib/Socket/messages-recv.js +294 -164
  101. package/lib/Socket/messages-recv.js.map +1 -0
  102. package/lib/Socket/messages-send.d.ts +71 -42
  103. package/lib/Socket/messages-send.d.ts.map +1 -0
  104. package/lib/Socket/messages-send.js +100 -83
  105. package/lib/Socket/messages-send.js.map +1 -0
  106. package/lib/Socket/mex.d.ts +3 -0
  107. package/lib/Socket/mex.d.ts.map +1 -0
  108. package/lib/Socket/mex.js +42 -0
  109. package/lib/Socket/mex.js.map +1 -0
  110. package/lib/Socket/newsletter.d.ts +142 -0
  111. package/lib/Socket/newsletter.d.ts.map +1 -0
  112. package/lib/Socket/newsletter.js +179 -0
  113. package/lib/Socket/newsletter.js.map +1 -0
  114. package/lib/Socket/socket.d.ts +12 -11
  115. package/lib/Socket/socket.d.ts.map +1 -0
  116. package/lib/Socket/socket.js +100 -106
  117. package/lib/Socket/socket.js.map +1 -0
  118. package/lib/Socket/usync.d.ts +14 -13
  119. package/lib/Socket/usync.d.ts.map +1 -0
  120. package/lib/Socket/usync.js +9 -11
  121. package/lib/Socket/usync.js.map +1 -0
  122. package/lib/Types/Auth.d.ts +4 -3
  123. package/lib/Types/Auth.d.ts.map +1 -0
  124. package/lib/Types/Auth.js +2 -2
  125. package/lib/Types/Auth.js.map +1 -0
  126. package/lib/Types/Call.d.ts +1 -0
  127. package/lib/Types/Call.d.ts.map +1 -0
  128. package/lib/Types/Call.js +2 -2
  129. package/lib/Types/Call.js.map +1 -0
  130. package/lib/Types/Chat.d.ts +11 -7
  131. package/lib/Types/Chat.d.ts.map +1 -0
  132. package/lib/Types/Chat.js +2 -4
  133. package/lib/Types/Chat.js.map +1 -0
  134. package/lib/Types/Contact.d.ts +5 -0
  135. package/lib/Types/Contact.d.ts.map +1 -0
  136. package/lib/Types/Contact.js +2 -2
  137. package/lib/Types/Contact.js.map +1 -0
  138. package/lib/Types/Events.d.ts +44 -10
  139. package/lib/Types/Events.d.ts.map +1 -0
  140. package/lib/Types/Events.js +2 -2
  141. package/lib/Types/Events.js.map +1 -0
  142. package/lib/Types/GroupMetadata.d.ts +3 -1
  143. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  144. package/lib/Types/GroupMetadata.js +2 -2
  145. package/lib/Types/GroupMetadata.js.map +1 -0
  146. package/lib/Types/Label.d.ts +1 -0
  147. package/lib/Types/Label.d.ts.map +1 -0
  148. package/lib/Types/Label.js +3 -5
  149. package/lib/Types/Label.js.map +1 -0
  150. package/lib/Types/LabelAssociation.d.ts +1 -0
  151. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  152. package/lib/Types/LabelAssociation.js +3 -5
  153. package/lib/Types/LabelAssociation.js.map +1 -0
  154. package/lib/Types/Message.d.ts +17 -9
  155. package/lib/Types/Message.d.ts.map +1 -0
  156. package/lib/Types/Message.js +7 -7
  157. package/lib/Types/Message.js.map +1 -0
  158. package/lib/Types/Newsletter.d.ts +135 -0
  159. package/lib/Types/Newsletter.d.ts.map +1 -0
  160. package/lib/Types/Newsletter.js +31 -0
  161. package/lib/Types/Newsletter.js.map +1 -0
  162. package/lib/Types/Product.d.ts +2 -1
  163. package/lib/Types/Product.d.ts.map +1 -0
  164. package/lib/Types/Product.js +2 -2
  165. package/lib/Types/Product.js.map +1 -0
  166. package/lib/Types/Signal.d.ts +2 -1
  167. package/lib/Types/Signal.d.ts.map +1 -0
  168. package/lib/Types/Signal.js +2 -2
  169. package/lib/Types/Signal.js.map +1 -0
  170. package/lib/Types/Socket.d.ts +8 -7
  171. package/lib/Types/Socket.d.ts.map +1 -0
  172. package/lib/Types/Socket.js +3 -2
  173. package/lib/Types/Socket.js.map +1 -0
  174. package/lib/Types/State.d.ts +4 -2
  175. package/lib/Types/State.d.ts.map +1 -0
  176. package/lib/Types/State.js +2 -2
  177. package/lib/Types/State.js.map +1 -0
  178. package/lib/Types/USync.d.ts +3 -2
  179. package/lib/Types/USync.d.ts.map +1 -0
  180. package/lib/Types/USync.js +2 -2
  181. package/lib/Types/USync.js.map +1 -0
  182. package/lib/Types/index.d.ts +15 -13
  183. package/lib/Types/index.d.ts.map +1 -0
  184. package/lib/Types/index.js +15 -30
  185. package/lib/Types/index.js.map +1 -0
  186. package/lib/Utils/auth-utils.d.ts +3 -2
  187. package/lib/Utils/auth-utils.d.ts.map +1 -0
  188. package/lib/Utils/auth-utils.js +24 -33
  189. package/lib/Utils/auth-utils.js.map +1 -0
  190. package/lib/Utils/baileys-event-stream.d.ts +2 -1
  191. package/lib/Utils/baileys-event-stream.d.ts.map +1 -0
  192. package/lib/Utils/baileys-event-stream.js +15 -22
  193. package/lib/Utils/baileys-event-stream.js.map +1 -0
  194. package/lib/Utils/business.d.ts +3 -2
  195. package/lib/Utils/business.d.ts.map +1 -0
  196. package/lib/Utils/business.js +61 -70
  197. package/lib/Utils/business.js.map +1 -0
  198. package/lib/Utils/chat-utils.d.ts +12 -11
  199. package/lib/Utils/chat-utils.d.ts.map +1 -0
  200. package/lib/Utils/chat-utils.js +141 -139
  201. package/lib/Utils/chat-utils.js.map +1 -0
  202. package/lib/Utils/crypto.d.ts +2 -1
  203. package/lib/Utils/crypto.d.ts.map +1 -0
  204. package/lib/Utils/crypto.js +37 -86
  205. package/lib/Utils/crypto.js.map +1 -0
  206. package/lib/Utils/decode-wa-message.d.ts +7 -7
  207. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  208. package/lib/Utils/decode-wa-message.js +43 -43
  209. package/lib/Utils/decode-wa-message.js.map +1 -0
  210. package/lib/Utils/event-buffer.d.ts +3 -2
  211. package/lib/Utils/event-buffer.d.ts.map +1 -0
  212. package/lib/Utils/event-buffer.js +24 -30
  213. package/lib/Utils/event-buffer.js.map +1 -0
  214. package/lib/Utils/generics.d.ts +11 -9
  215. package/lib/Utils/generics.d.ts.map +1 -0
  216. package/lib/Utils/generics.js +88 -111
  217. package/lib/Utils/generics.js.map +1 -0
  218. package/lib/Utils/history.d.ts +4 -3
  219. package/lib/Utils/history.d.ts.map +1 -0
  220. package/lib/Utils/history.js +37 -46
  221. package/lib/Utils/history.js.map +1 -0
  222. package/lib/Utils/index.d.ts +18 -17
  223. package/lib/Utils/index.d.ts.map +1 -0
  224. package/lib/Utils/index.js +18 -33
  225. package/lib/Utils/index.js.map +1 -0
  226. package/lib/Utils/link-preview.d.ts +4 -3
  227. package/lib/Utils/link-preview.d.ts.map +1 -0
  228. package/lib/Utils/link-preview.js +11 -48
  229. package/lib/Utils/link-preview.js.map +1 -0
  230. package/lib/Utils/logger.d.ts +6 -5
  231. package/lib/Utils/logger.d.ts.map +1 -0
  232. package/lib/Utils/logger.js +3 -7
  233. package/lib/Utils/logger.js.map +1 -0
  234. package/lib/Utils/lt-hash.d.ts +9 -8
  235. package/lib/Utils/lt-hash.d.ts.map +1 -0
  236. package/lib/Utils/lt-hash.js +21 -24
  237. package/lib/Utils/lt-hash.js.map +1 -0
  238. package/lib/Utils/make-mutex.d.ts +1 -0
  239. package/lib/Utils/make-mutex.d.ts.map +1 -0
  240. package/lib/Utils/make-mutex.js +5 -9
  241. package/lib/Utils/make-mutex.js.map +1 -0
  242. package/lib/Utils/messages-media.d.ts +20 -11
  243. package/lib/Utils/messages-media.d.ts.map +1 -0
  244. package/lib/Utils/messages-media.js +200 -234
  245. package/lib/Utils/messages-media.js.map +1 -0
  246. package/lib/Utils/messages.d.ts +9 -8
  247. package/lib/Utils/messages.d.ts.map +1 -0
  248. package/lib/Utils/messages.js +217 -199
  249. package/lib/Utils/messages.js.map +1 -0
  250. package/lib/Utils/noise-handler.d.ts +5 -4
  251. package/lib/Utils/noise-handler.d.ts.map +1 -0
  252. package/lib/Utils/noise-handler.js +22 -26
  253. package/lib/Utils/noise-handler.js.map +1 -0
  254. package/lib/Utils/process-message.d.ts +5 -4
  255. package/lib/Utils/process-message.d.ts.map +1 -0
  256. package/lib/Utils/process-message.js +125 -130
  257. package/lib/Utils/process-message.js.map +1 -0
  258. package/lib/Utils/signal.d.ts +5 -4
  259. package/lib/Utils/signal.d.ts.map +1 -0
  260. package/lib/Utils/signal.js +47 -52
  261. package/lib/Utils/signal.js.map +1 -0
  262. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  263. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  264. package/lib/Utils/use-multi-file-auth-state.js +23 -26
  265. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  266. package/lib/Utils/validate-connection.d.ts +4 -3
  267. package/lib/Utils/validate-connection.d.ts.map +1 -0
  268. package/lib/Utils/validate-connection.js +55 -61
  269. package/lib/Utils/validate-connection.js.map +1 -0
  270. package/lib/WABinary/constants.d.ts +5 -4
  271. package/lib/WABinary/constants.d.ts.map +1 -0
  272. package/lib/WABinary/constants.js +1174 -1176
  273. package/lib/WABinary/constants.js.map +1 -0
  274. package/lib/WABinary/decode.d.ts +2 -1
  275. package/lib/WABinary/decode.d.ts.map +1 -0
  276. package/lib/WABinary/decode.js +13 -51
  277. package/lib/WABinary/decode.js.map +1 -0
  278. package/lib/WABinary/encode.d.ts +2 -1
  279. package/lib/WABinary/encode.d.ts.map +1 -0
  280. package/lib/WABinary/encode.js +5 -41
  281. package/lib/WABinary/encode.js.map +1 -0
  282. package/lib/WABinary/generic-utils.d.ts +4 -3
  283. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  284. package/lib/WABinary/generic-utils.js +30 -38
  285. package/lib/WABinary/generic-utils.js.map +1 -0
  286. package/lib/WABinary/index.d.ts +6 -5
  287. package/lib/WABinary/index.d.ts.map +1 -0
  288. package/lib/WABinary/index.js +6 -21
  289. package/lib/WABinary/index.js.map +1 -0
  290. package/lib/WABinary/jid-utils.d.ts +1 -0
  291. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  292. package/lib/WABinary/jid-utils.js +21 -35
  293. package/lib/WABinary/jid-utils.js.map +1 -0
  294. package/lib/WABinary/types.d.ts +2 -1
  295. package/lib/WABinary/types.d.ts.map +1 -0
  296. package/lib/WABinary/types.js +2 -2
  297. package/lib/WABinary/types.js.map +1 -0
  298. package/lib/WAM/BinaryInfo.d.ts +2 -1
  299. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  300. package/lib/WAM/BinaryInfo.js +2 -5
  301. package/lib/WAM/BinaryInfo.js.map +1 -0
  302. package/lib/WAM/constants.d.ts +1 -0
  303. package/lib/WAM/constants.d.ts.map +1 -0
  304. package/lib/WAM/constants.js +4 -6
  305. package/lib/WAM/constants.js.map +1 -0
  306. package/lib/WAM/encode.d.ts +2 -1
  307. package/lib/WAM/encode.d.ts.map +1 -0
  308. package/lib/WAM/encode.js +12 -14
  309. package/lib/WAM/encode.js.map +1 -0
  310. package/lib/WAM/index.d.ts +4 -3
  311. package/lib/WAM/index.d.ts.map +1 -0
  312. package/lib/WAM/index.js +4 -19
  313. package/lib/WAM/index.js.map +1 -0
  314. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +4 -3
  315. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  316. package/lib/WAUSync/Protocols/USyncContactProtocol.js +6 -9
  317. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  318. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +3 -2
  319. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  320. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +9 -12
  321. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  322. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +3 -2
  323. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  324. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +7 -10
  325. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  326. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +3 -2
  327. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  328. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -11
  329. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  330. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +4 -3
  331. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  332. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +19 -21
  333. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  334. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -2
  335. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  336. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +2 -5
  337. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  338. package/lib/WAUSync/Protocols/index.d.ts +5 -4
  339. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  340. package/lib/WAUSync/Protocols/index.js +5 -20
  341. package/lib/WAUSync/Protocols/index.js.map +1 -0
  342. package/lib/WAUSync/USyncQuery.d.ts +4 -3
  343. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  344. package/lib/WAUSync/USyncQuery.js +18 -20
  345. package/lib/WAUSync/USyncQuery.js.map +1 -0
  346. package/lib/WAUSync/USyncUser.d.ts +6 -5
  347. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  348. package/lib/WAUSync/USyncUser.js +2 -5
  349. package/lib/WAUSync/USyncUser.js.map +1 -0
  350. package/lib/WAUSync/index.d.ts +4 -3
  351. package/lib/WAUSync/index.d.ts.map +1 -0
  352. package/lib/WAUSync/index.js +4 -19
  353. package/lib/WAUSync/index.js.map +1 -0
  354. package/lib/index.d.ts +9 -8
  355. package/lib/index.d.ts.map +1 -0
  356. package/lib/index.js +11 -30
  357. package/lib/index.js.map +1 -0
  358. package/package.json +26 -28
  359. package/WASignalGroup/GroupProtocol.js +0 -1697
  360. package/WASignalGroup/ciphertext_message.js +0 -16
  361. package/WASignalGroup/group_cipher.js +0 -120
  362. package/WASignalGroup/group_session_builder.js +0 -46
  363. package/WASignalGroup/index.js +0 -5
  364. package/WASignalGroup/keyhelper.js +0 -21
  365. package/WASignalGroup/protobufs.js +0 -3
  366. package/WASignalGroup/queue_job.js +0 -69
  367. package/WASignalGroup/sender_chain_key.js +0 -50
  368. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  369. package/WASignalGroup/sender_key_message.js +0 -92
  370. package/WASignalGroup/sender_key_name.js +0 -70
  371. package/WASignalGroup/sender_key_record.js +0 -56
  372. package/WASignalGroup/sender_key_state.js +0 -129
@@ -1,100 +1,45 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.getHttpStream = exports.getStream = exports.toBuffer = exports.toReadable = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.hkdfInfoKey = void 0;
40
- exports.processImage = processImage;
41
- exports.getMediaKeys = getMediaKeys;
42
- exports.getAudioDuration = getAudioDuration;
43
- exports.getAudioWaveform = getAudioWaveform;
44
- exports.generateThumbnail = generateThumbnail;
45
- exports.extensionForMediaMessage = extensionForMediaMessage;
46
- const boom_1 = require("@hapi/boom");
47
- const axios_1 = __importDefault(require("axios"));
48
- const child_process_1 = require("child_process");
49
- const Crypto = __importStar(require("crypto"));
50
- const events_1 = require("events");
51
- const fs_1 = require("fs");
52
- const os_1 = require("os");
53
- const path_1 = require("path");
54
- const stream_1 = require("stream");
55
- const WAProto_1 = require("../../WAProto");
56
- const Defaults_1 = require("../Defaults");
57
- const WABinary_1 = require("../WABinary");
58
- const crypto_1 = require("./crypto");
59
- const generics_1 = require("./generics");
60
- const sharp_1 = __importDefault(require("sharp"));
61
- const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
1
+ import { Boom } from '@hapi/boom';
2
+ import axios, {} from 'axios';
3
+ import { exec } from 'child_process';
4
+ import * as Crypto from 'crypto';
5
+ import { once } from 'events';
6
+ import { createReadStream, createWriteStream, promises as fs, WriteStream } from 'fs';
7
+ import { tmpdir } from 'os';
8
+ import { join } from 'path';
9
+ import { Readable, Transform } from 'stream';
10
+ import { URL } from 'url';
11
+ import { proto } from '../../WAProto/index.js';
12
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults/index.js';
13
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
14
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
15
+ import { generateMessageIDV2 } from './generics.js';
16
+ import sharp from 'sharp';
17
+ const getTmpFilesDirectory = () => tmpdir();
62
18
  const getImageProcessingLibrary = async () => {
63
- const [_jimp, sharp] = await Promise.all([
64
- (async () => {
65
- const jimp = await Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { });
66
- return jimp;
67
- })(),
68
- (async () => {
69
- const sharp = await Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { });
70
- return sharp;
71
- })()
72
- ]);
19
+ //@ts-ignore
20
+ const [jimp, sharp] = await Promise.all([import('jimp').catch(() => { }), import('sharp').catch(() => { })]);
73
21
  if (sharp) {
74
22
  return { sharp };
75
23
  }
76
- const jimp = (_jimp === null || _jimp === void 0 ? void 0 : _jimp.default) || _jimp;
77
24
  if (jimp) {
78
25
  return { jimp };
79
26
  }
80
- throw new boom_1.Boom('No image processing library available');
27
+ throw new Boom('No image processing library available');
81
28
  };
82
- const hkdfInfoKey = (type) => {
83
- const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
29
+ export const hkdfInfoKey = (type) => {
30
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
84
31
  return `WhatsApp ${hkdfInfo} Keys`;
85
32
  };
86
- exports.hkdfInfoKey = hkdfInfoKey;
87
33
  //!BK: Added a new function to get the URL info
88
- async function processImage(imageUrl) {
34
+ export async function processImage(imageUrl) {
89
35
  try {
90
- console.log('processing image', imageUrl);
91
36
  // Fetch the image
92
37
  const response = await fetch(imageUrl);
93
38
  let imageBuffer = Buffer.from(await response.arrayBuffer());
94
39
  // Convert WebP to JPEG if needed
95
40
  const isWebP = imageUrl.endsWith('.webp');
96
41
  if (isWebP) {
97
- imageBuffer = await (0, sharp_1.default)(imageBuffer).jpeg().toBuffer(); // Convert to JPEG
42
+ imageBuffer = await sharp(imageBuffer).jpeg().toBuffer(); // Convert to JPEG
98
43
  }
99
44
  return imageBuffer;
100
45
  }
@@ -103,16 +48,54 @@ async function processImage(imageUrl) {
103
48
  return null;
104
49
  }
105
50
  }
51
+ export const getRawMediaUploadData = async (media, mediaType, logger) => {
52
+ const { stream } = await getStream(media);
53
+ logger?.debug('got stream for raw upload');
54
+ const hasher = Crypto.createHash('sha256');
55
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
56
+ const fileWriteStream = createWriteStream(filePath);
57
+ let fileLength = 0;
58
+ try {
59
+ for await (const data of stream) {
60
+ fileLength += data.length;
61
+ hasher.update(data);
62
+ if (!fileWriteStream.write(data)) {
63
+ await once(fileWriteStream, 'drain');
64
+ }
65
+ }
66
+ fileWriteStream.end();
67
+ await once(fileWriteStream, 'finish');
68
+ stream.destroy();
69
+ const fileSha256 = hasher.digest();
70
+ logger?.debug('hashed data for raw upload');
71
+ return {
72
+ filePath: filePath,
73
+ fileSha256,
74
+ fileLength
75
+ };
76
+ }
77
+ catch (error) {
78
+ fileWriteStream.destroy();
79
+ stream.destroy();
80
+ try {
81
+ await fs.unlink(filePath);
82
+ }
83
+ catch {
84
+ //
85
+ }
86
+ throw error;
87
+ }
88
+ };
106
89
  /** generates all the keys required to encrypt/decrypt & sign a media message */
107
- async function getMediaKeys(buffer, mediaType) {
90
+ export async function getMediaKeys(buffer, mediaType) {
108
91
  if (!buffer) {
109
- throw new boom_1.Boom('Cannot derive from empty media key');
92
+ throw new Boom('Cannot derive from empty media key');
110
93
  }
111
94
  if (typeof buffer === 'string') {
112
95
  buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
113
96
  }
114
97
  // expand using HKDF to 112 bytes, also pass in the relevant app info
115
- const expandedMediaKey = await (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
98
+ const expandedMediaKey = await hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
116
99
  return {
117
100
  iv: expandedMediaKey.slice(0, 16),
118
101
  cipherKey: expandedMediaKey.slice(16, 48),
@@ -122,7 +105,7 @@ async function getMediaKeys(buffer, mediaType) {
122
105
  /** Extracts video thumb using FFMPEG */
123
106
  const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
124
107
  const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
125
- (0, child_process_1.exec)(cmd, err => {
108
+ exec(cmd, err => {
126
109
  if (err) {
127
110
  reject(err);
128
111
  }
@@ -131,13 +114,14 @@ const extractVideoThumb = async (path, destPath, time, size) => new Promise((res
131
114
  }
132
115
  });
133
116
  });
134
- const extractImageThumb = async (bufferOrFilePath, width = 32) => {
135
- var _a, _b;
136
- if (bufferOrFilePath instanceof stream_1.Readable) {
137
- bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
117
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
118
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
119
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
120
+ if (bufferOrFilePath instanceof Readable) {
121
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
138
122
  }
139
123
  const lib = await getImageProcessingLibrary();
140
- if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
124
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
141
125
  const img = lib.sharp.default(bufferOrFilePath);
142
126
  const dimensions = await img.metadata();
143
127
  const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
@@ -149,112 +133,100 @@ const extractImageThumb = async (bufferOrFilePath, width = 32) => {
149
133
  }
150
134
  };
151
135
  }
152
- else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
153
- const { read, MIME_JPEG, RESIZE_BILINEAR, AUTO } = lib.jimp;
154
- const jimp = await read(bufferOrFilePath);
136
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
137
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
155
138
  const dimensions = {
156
- width: jimp.getWidth(),
157
- height: jimp.getHeight()
139
+ width: jimp.width,
140
+ height: jimp.height
158
141
  };
159
- const buffer = await jimp.quality(50).resize(width, AUTO, RESIZE_BILINEAR).getBufferAsync(MIME_JPEG);
142
+ const buffer = await jimp
143
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
144
+ .getBuffer('image/jpeg', { quality: 50 });
160
145
  return {
161
146
  buffer,
162
147
  original: dimensions
163
148
  };
164
149
  }
165
150
  else {
166
- throw new boom_1.Boom('No image processing library available');
151
+ throw new Boom('No image processing library available');
167
152
  }
168
153
  };
169
- exports.extractImageThumb = extractImageThumb;
170
- const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
171
- exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
172
- const generateProfilePicture = async (mediaUpload) => {
173
- var _a, _b;
174
- let bufferOrFilePath;
154
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
155
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
156
+ let buffer;
157
+ const { width: w = 640, height: h = 640 } = dimensions || {};
175
158
  if (Buffer.isBuffer(mediaUpload)) {
176
- bufferOrFilePath = mediaUpload;
177
- }
178
- else if ('url' in mediaUpload) {
179
- const imageBuffer = await processImage(mediaUpload.url.toString());
180
- if (imageBuffer) {
181
- bufferOrFilePath = imageBuffer;
182
- }
183
- else {
184
- bufferOrFilePath = mediaUpload.url.toString();
185
- }
159
+ buffer = mediaUpload;
186
160
  }
187
161
  else {
188
- bufferOrFilePath = await (0, exports.toBuffer)(mediaUpload.stream);
162
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
163
+ const { stream } = await getStream(mediaUpload);
164
+ // Convert the resulting stream to a buffer
165
+ buffer = await toBuffer(stream);
189
166
  }
190
167
  const lib = await getImageProcessingLibrary();
191
168
  let img;
192
- if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
169
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
193
170
  img = lib.sharp
194
- .default(bufferOrFilePath)
195
- .resize(640, 640)
171
+ .default(buffer)
172
+ .resize(w, h)
196
173
  .jpeg({
197
174
  quality: 50
198
175
  })
199
176
  .toBuffer();
200
177
  }
201
- else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
202
- const { read, MIME_JPEG, RESIZE_BILINEAR } = lib.jimp;
203
- const jimp = await read(bufferOrFilePath);
204
- const min = Math.min(jimp.getWidth(), jimp.getHeight());
205
- const cropped = jimp.crop(0, 0, min, min);
206
- img = cropped.quality(50).resize(640, 640, RESIZE_BILINEAR).getBufferAsync(MIME_JPEG);
178
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
179
+ const jimp = await lib.jimp.Jimp.read(buffer);
180
+ const min = Math.min(jimp.width, jimp.height);
181
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
182
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
207
183
  }
208
184
  else {
209
- throw new boom_1.Boom('No image processing library available');
185
+ throw new Boom('No image processing library available');
210
186
  }
211
187
  return {
212
188
  img: await img
213
189
  };
214
190
  };
215
- exports.generateProfilePicture = generateProfilePicture;
216
191
  /** gets the SHA256 of the given media message */
217
- const mediaMessageSHA256B64 = (message) => {
192
+ export const mediaMessageSHA256B64 = (message) => {
218
193
  const media = Object.values(message)[0];
219
- return (media === null || media === void 0 ? void 0 : media.fileSha256) && Buffer.from(media.fileSha256).toString('base64');
194
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
220
195
  };
221
- exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
222
- async function getAudioDuration(buffer) {
223
- const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
196
+ export async function getAudioDuration(buffer) {
197
+ const musicMetadata = await import('music-metadata');
224
198
  let metadata;
199
+ const options = {
200
+ duration: true
201
+ };
225
202
  if (Buffer.isBuffer(buffer)) {
226
- metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
203
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
227
204
  }
228
205
  else if (typeof buffer === 'string') {
229
- const rStream = (0, fs_1.createReadStream)(buffer);
230
- try {
231
- metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true });
232
- }
233
- finally {
234
- rStream.destroy();
235
- }
206
+ metadata = await musicMetadata.parseFile(buffer, options);
236
207
  }
237
208
  else {
238
- metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true });
209
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
239
210
  }
240
211
  return metadata.format.duration;
241
212
  }
242
213
  /**
243
214
  referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
244
215
  */
245
- async function getAudioWaveform(buffer, logger) {
216
+ export async function getAudioWaveform(buffer, logger) {
246
217
  try {
247
- const { default: decoder } = await eval("import('audio-decode')");
218
+ // @ts-ignore
219
+ const { default: decoder } = await import('audio-decode');
248
220
  let audioData;
249
221
  if (Buffer.isBuffer(buffer)) {
250
222
  audioData = buffer;
251
223
  }
252
224
  else if (typeof buffer === 'string') {
253
- const rStream = (0, fs_1.createReadStream)(buffer);
254
- audioData = await (0, exports.toBuffer)(rStream);
225
+ const rStream = createReadStream(buffer);
226
+ audioData = await toBuffer(rStream);
255
227
  }
256
228
  else {
257
- audioData = await (0, exports.toBuffer)(buffer);
229
+ audioData = await toBuffer(buffer);
258
230
  }
259
231
  const audioBuffer = await decoder(audioData);
260
232
  const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
@@ -277,17 +249,16 @@ async function getAudioWaveform(buffer, logger) {
277
249
  return waveform;
278
250
  }
279
251
  catch (e) {
280
- logger === null || logger === void 0 ? void 0 : logger.debug('Failed to generate waveform: ' + e);
252
+ logger?.debug('Failed to generate waveform: ' + e);
281
253
  }
282
254
  }
283
- const toReadable = (buffer) => {
284
- const readable = new stream_1.Readable({ read: () => { } });
255
+ export const toReadable = (buffer) => {
256
+ const readable = new Readable({ read: () => { } });
285
257
  readable.push(buffer);
286
258
  readable.push(null);
287
259
  return readable;
288
260
  };
289
- exports.toReadable = toReadable;
290
- const toBuffer = async (stream) => {
261
+ export const toBuffer = async (stream) => {
291
262
  const chunks = [];
292
263
  for await (const chunk of stream) {
293
264
  chunks.push(chunk);
@@ -295,27 +266,29 @@ const toBuffer = async (stream) => {
295
266
  stream.destroy();
296
267
  return Buffer.concat(chunks);
297
268
  };
298
- exports.toBuffer = toBuffer;
299
- const getStream = async (item, opts) => {
269
+ export const getStream = async (item, opts) => {
300
270
  if (Buffer.isBuffer(item)) {
301
- return { stream: (0, exports.toReadable)(item), type: 'buffer' };
271
+ return { stream: toReadable(item), type: 'buffer' };
302
272
  }
303
273
  if ('stream' in item) {
304
274
  return { stream: item.stream, type: 'readable' };
305
275
  }
306
- if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
307
- return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
276
+ const urlStr = item.url.toString();
277
+ if (urlStr.startsWith('data:')) {
278
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
279
+ return { stream: toReadable(buffer), type: 'buffer' };
308
280
  }
309
- return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
281
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
282
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' };
283
+ }
284
+ return { stream: createReadStream(item.url), type: 'file' };
310
285
  };
311
- exports.getStream = getStream;
312
286
  /** generates a thumbnail for a given media, if required */
313
- async function generateThumbnail(file, mediaType, options) {
314
- var _a;
287
+ export async function generateThumbnail(file, mediaType, options) {
315
288
  let thumbnail;
316
289
  let originalImageDimensions;
317
290
  if (mediaType === 'image') {
318
- const { buffer, original } = await (0, exports.extractImageThumb)(file);
291
+ const { buffer, original } = await extractImageThumb(file);
319
292
  thumbnail = buffer.toString('base64');
320
293
  if (original.width && original.height) {
321
294
  originalImageDimensions = {
@@ -325,15 +298,15 @@ async function generateThumbnail(file, mediaType, options) {
325
298
  }
326
299
  }
327
300
  else if (mediaType === 'video') {
328
- const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageIDV2)() + '.jpg');
301
+ const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg');
329
302
  try {
330
303
  await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
331
- const buff = await fs_1.promises.readFile(imgFilename);
304
+ const buff = await fs.readFile(imgFilename);
332
305
  thumbnail = buff.toString('base64');
333
- await fs_1.promises.unlink(imgFilename);
306
+ await fs.unlink(imgFilename);
334
307
  }
335
308
  catch (err) {
336
- (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug('could not generate video thumb: ' + err);
309
+ options.logger?.debug('could not generate video thumb: ' + err);
337
310
  }
338
311
  }
339
312
  return {
@@ -341,24 +314,22 @@ async function generateThumbnail(file, mediaType, options) {
341
314
  originalImageDimensions
342
315
  };
343
316
  }
344
- const getHttpStream = async (url, options = {}) => {
345
- const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' });
317
+ export const getHttpStream = async (url, options = {}) => {
318
+ const fetched = await axios.get(url.toString(), { ...options, responseType: 'stream' });
346
319
  return fetched.data;
347
320
  };
348
- exports.getHttpStream = getHttpStream;
349
- const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
350
- var _a, _b;
351
- const { stream, type } = await (0, exports.getStream)(media, opts);
352
- logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
321
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
322
+ const { stream, type } = await getStream(media, opts);
323
+ logger?.debug('fetched media stream');
353
324
  const mediaKey = Crypto.randomBytes(32);
354
325
  const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
355
- const encFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-enc');
356
- const encFileWriteStream = (0, fs_1.createWriteStream)(encFilePath);
326
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
327
+ const encFileWriteStream = createWriteStream(encFilePath);
357
328
  let originalFileStream;
358
329
  let originalFilePath;
359
330
  if (saveOriginalFileIfRequired) {
360
- originalFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-original');
361
- originalFileStream = (0, fs_1.createWriteStream)(originalFilePath);
331
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
332
+ originalFileStream = createWriteStream(originalFilePath);
362
333
  }
363
334
  let fileLength = 0;
364
335
  const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
@@ -373,14 +344,14 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
373
344
  try {
374
345
  for await (const data of stream) {
375
346
  fileLength += data.length;
376
- if (type === 'remote' && (opts === null || opts === void 0 ? void 0 : opts.maxContentLength) && fileLength + data.length > opts.maxContentLength) {
377
- throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
347
+ if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
348
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
378
349
  data: { media, type }
379
350
  });
380
351
  }
381
352
  if (originalFileStream) {
382
353
  if (!originalFileStream.write(data)) {
383
- await (0, events_1.once)(originalFileStream, 'drain');
354
+ await once(originalFileStream, 'drain');
384
355
  }
385
356
  }
386
357
  sha256Plain.update(data);
@@ -393,9 +364,9 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
393
364
  const fileEncSha256 = sha256Enc.digest();
394
365
  encFileWriteStream.write(mac);
395
366
  encFileWriteStream.end();
396
- (_a = originalFileStream === null || originalFileStream === void 0 ? void 0 : originalFileStream.end) === null || _a === void 0 ? void 0 : _a.call(originalFileStream);
367
+ originalFileStream?.end?.();
397
368
  stream.destroy();
398
- logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
369
+ logger?.debug('encrypted data successfully');
399
370
  return {
400
371
  mediaKey,
401
372
  originalFilePath,
@@ -409,43 +380,44 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
409
380
  catch (error) {
410
381
  // destroy all streams with error
411
382
  encFileWriteStream.destroy();
412
- (_b = originalFileStream === null || originalFileStream === void 0 ? void 0 : originalFileStream.destroy) === null || _b === void 0 ? void 0 : _b.call(originalFileStream);
383
+ originalFileStream?.destroy?.();
413
384
  aes.destroy();
414
385
  hmac.destroy();
415
386
  sha256Plain.destroy();
416
387
  sha256Enc.destroy();
417
388
  stream.destroy();
418
389
  try {
419
- await fs_1.promises.unlink(encFilePath);
390
+ await fs.unlink(encFilePath);
420
391
  if (originalFilePath) {
421
- await fs_1.promises.unlink(originalFilePath);
392
+ await fs.unlink(originalFilePath);
422
393
  }
423
394
  }
424
395
  catch (err) {
425
- logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed deleting tmp files');
396
+ logger?.error({ err }, 'failed deleting tmp files');
426
397
  }
427
398
  throw error;
428
399
  }
429
400
  };
430
- exports.encryptedStream = encryptedStream;
431
401
  const DEF_HOST = 'mmg.whatsapp.net';
432
402
  const AES_CHUNK_SIZE = 16;
433
403
  const toSmallestChunkSize = (num) => {
434
404
  return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
435
405
  };
436
- const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
437
- exports.getUrlFromDirectPath = getUrlFromDirectPath;
438
- const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
439
- const downloadUrl = url || (0, exports.getUrlFromDirectPath)(directPath);
406
+ export const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
407
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
408
+ const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
409
+ const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
410
+ if (!downloadUrl) {
411
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
412
+ }
440
413
  const keys = await getMediaKeys(mediaKey, type);
441
- return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
414
+ return downloadEncryptedContent(downloadUrl, keys, opts);
442
415
  };
443
- exports.downloadContentFromMessage = downloadContentFromMessage;
444
416
  /**
445
417
  * Decrypts and downloads an AES256-CBC encrypted file given the keys.
446
418
  * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
447
419
  * */
448
- const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
420
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
449
421
  let bytesFetched = 0;
450
422
  let startChunk = 0;
451
423
  let firstBlockIsIV = false;
@@ -460,8 +432,8 @@ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startB
460
432
  }
461
433
  const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
462
434
  const headers = {
463
- ...((options === null || options === void 0 ? void 0 : options.headers) || {}),
464
- Origin: Defaults_1.DEFAULT_ORIGIN
435
+ ...(options?.headers || {}),
436
+ Origin: DEFAULT_ORIGIN
465
437
  };
466
438
  if (startChunk || endChunk) {
467
439
  headers.Range = `bytes=${startChunk}-`;
@@ -470,7 +442,7 @@ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startB
470
442
  }
471
443
  }
472
444
  // download the message
473
- const fetched = await (0, exports.getHttpStream)(downloadUrl, {
445
+ const fetched = await getHttpStream(downloadUrl, {
474
446
  ...(options || {}),
475
447
  headers,
476
448
  maxBodyLength: Infinity,
@@ -489,7 +461,7 @@ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startB
489
461
  push(bytes);
490
462
  }
491
463
  };
492
- const output = new stream_1.Transform({
464
+ const output = new Transform({
493
465
  transform(chunk, _, callback) {
494
466
  let data = Buffer.concat([remainingBytes, chunk]);
495
467
  const decryptLength = toSmallestChunkSize(data.length);
@@ -528,9 +500,8 @@ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startB
528
500
  });
529
501
  return fetched.pipe(output, { end: true });
530
502
  };
531
- exports.downloadEncryptedContent = downloadEncryptedContent;
532
- function extensionForMediaMessage(message) {
533
- const getExtension = (mimetype) => mimetype.split(';')[0].split('/')[1];
503
+ export function extensionForMediaMessage(message) {
504
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
534
505
  const type = Object.keys(message)[0];
535
506
  let extension;
536
507
  if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
@@ -542,28 +513,27 @@ function extensionForMediaMessage(message) {
542
513
  }
543
514
  return extension;
544
515
  }
545
- const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
516
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
546
517
  return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
547
- var _a, _b;
548
518
  // send a query JSON to obtain the url & auth token to upload our media
549
519
  let uploadInfo = await refreshMediaConn(false);
550
520
  let urls;
551
521
  const hosts = [...customUploadHosts, ...uploadInfo.hosts];
552
- fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
522
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
553
523
  for (const { hostname } of hosts) {
554
524
  logger.debug(`uploading to "${hostname}"`);
555
525
  const auth = encodeURIComponent(uploadInfo.auth); // the auth token
556
- const url = `https://${hostname}${Defaults_1.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
526
+ const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
557
527
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
558
528
  let result;
559
529
  try {
560
- const body = await axios_1.default.post(url, (0, fs_1.createReadStream)(filePath), {
530
+ const body = await axios.post(url, createReadStream(filePath), {
561
531
  ...options,
562
532
  maxRedirects: 0,
563
533
  headers: {
564
534
  ...(options.headers || {}),
565
535
  'Content-Type': 'application/octet-stream',
566
- Origin: Defaults_1.DEFAULT_ORIGIN
536
+ Origin: DEFAULT_ORIGIN
567
537
  },
568
538
  httpsAgent: fetchAgent,
569
539
  timeout: timeoutMs,
@@ -572,7 +542,7 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
572
542
  maxContentLength: Infinity
573
543
  });
574
544
  result = body.data;
575
- if ((result === null || result === void 0 ? void 0 : result.url) || (result === null || result === void 0 ? void 0 : result.directPath)) {
545
+ if (result?.url || result?.directPath) {
576
546
  urls = {
577
547
  mediaUrl: result.url,
578
548
  directPath: result.direct_path
@@ -585,37 +555,36 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
585
555
  }
586
556
  }
587
557
  catch (error) {
588
- if (axios_1.default.isAxiosError(error)) {
589
- result = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
558
+ if (axios.isAxiosError(error)) {
559
+ result = error.response?.data;
590
560
  }
591
- const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
561
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
592
562
  logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
593
563
  }
594
564
  }
595
565
  if (!urls) {
596
- throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
566
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
597
567
  }
598
568
  return urls;
599
569
  };
600
570
  };
601
- exports.getWAUploadToServer = getWAUploadToServer;
602
571
  const getMediaRetryKey = (mediaKey) => {
603
- return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
572
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
604
573
  };
605
574
  /**
606
575
  * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
607
576
  */
608
- const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
577
+ export const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
609
578
  const recp = { stanzaId: key.id };
610
- const recpBuffer = WAProto_1.proto.ServerErrorReceipt.encode(recp).finish();
579
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
611
580
  const iv = Crypto.randomBytes(12);
612
581
  const retryKey = await getMediaRetryKey(mediaKey);
613
- const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
582
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
614
583
  const req = {
615
584
  tag: 'receipt',
616
585
  attrs: {
617
586
  id: key.id,
618
- to: (0, WABinary_1.jidNormalizedUser)(meId),
587
+ to: jidNormalizedUser(meId),
619
588
  type: 'server-error'
620
589
  },
621
590
  content: [
@@ -643,9 +612,8 @@ const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
643
612
  };
644
613
  return req;
645
614
  };
646
- exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
647
- const decodeMediaRetryNode = (node) => {
648
- const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
615
+ export const decodeMediaRetryNode = (node) => {
616
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
649
617
  const event = {
650
618
  key: {
651
619
  id: node.attrs.id,
@@ -654,39 +622,37 @@ const decodeMediaRetryNode = (node) => {
654
622
  participant: rmrNode.attrs.participant
655
623
  }
656
624
  };
657
- const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
625
+ const errorNode = getBinaryNodeChild(node, 'error');
658
626
  if (errorNode) {
659
627
  const errorCode = +errorNode.attrs.code;
660
- event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, {
628
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
661
629
  data: errorNode.attrs,
662
- statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode)
630
+ statusCode: getStatusCodeForMediaRetry(errorCode)
663
631
  });
664
632
  }
665
633
  else {
666
- const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
667
- const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
668
- const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
634
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
635
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
636
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
669
637
  if (ciphertext && iv) {
670
638
  event.media = { ciphertext, iv };
671
639
  }
672
640
  else {
673
- event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
641
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
674
642
  }
675
643
  }
676
644
  return event;
677
645
  };
678
- exports.decodeMediaRetryNode = decodeMediaRetryNode;
679
- const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
646
+ export const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
680
647
  const retryKey = await getMediaRetryKey(mediaKey);
681
- const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
682
- return WAProto_1.proto.MediaRetryNotification.decode(plaintext);
648
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
649
+ return proto.MediaRetryNotification.decode(plaintext);
683
650
  };
684
- exports.decryptMediaRetryData = decryptMediaRetryData;
685
- const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
686
- exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
651
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
687
652
  const MEDIA_RETRY_STATUS_MAP = {
688
- [WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
689
- [WAProto_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
690
- [WAProto_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
691
- [WAProto_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
653
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
654
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
655
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
656
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
692
657
  };
658
+ //# sourceMappingURL=messages-media.js.map