@modzneverdie/baileys 17.1.1 → 17.1.3

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 (427) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +6035 -0
  4. package/WAProto/fix-imports.js +81 -0
  5. package/WAProto/index.d.ts +2 -0
  6. package/WAProto/index.js +59469 -96804
  7. package/lib/Defaults/index.d.ts +29 -8
  8. package/lib/Defaults/index.d.ts.map +1 -0
  9. package/lib/Defaults/index.js +134 -141
  10. package/lib/Defaults/index.js.map +1 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +1 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.js +2 -5
  14. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +4 -3
  16. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.js +7 -41
  18. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  19. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  20. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  21. package/lib/Signal/Group/group_cipher.js +37 -51
  22. package/lib/Signal/Group/group_cipher.js.map +1 -0
  23. package/lib/Signal/Group/index.d.ts +12 -11
  24. package/lib/Signal/Group/index.d.ts.map +1 -0
  25. package/lib/Signal/Group/index.js +12 -57
  26. package/lib/Signal/Group/index.js.map +1 -0
  27. package/lib/Signal/Group/keyhelper.d.ts +2 -1
  28. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  29. package/lib/Signal/Group/keyhelper.js +7 -44
  30. package/lib/Signal/Group/keyhelper.js.map +1 -0
  31. package/lib/Signal/Group/sender-chain-key.d.ts +3 -2
  32. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.js +7 -15
  34. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.d.ts +2 -1
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +8 -11
  38. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  39. package/lib/Signal/Group/sender-key-message.d.ts +2 -1
  40. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.js +9 -12
  42. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  43. package/lib/Signal/Group/sender-key-name.d.ts +1 -0
  44. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.js +2 -5
  46. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  47. package/lib/Signal/Group/sender-key-record.d.ts +3 -2
  48. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.js +9 -21
  50. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  51. package/lib/Signal/Group/sender-key-state.d.ts +7 -6
  52. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.js +27 -42
  54. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  55. package/lib/Signal/Group/sender-message-key.d.ts +1 -0
  56. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.js +4 -7
  58. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  59. package/lib/Signal/libsignal.d.ts +5 -3
  60. package/lib/Signal/libsignal.d.ts.map +1 -0
  61. package/lib/Signal/libsignal.js +319 -90
  62. package/lib/Signal/libsignal.js.map +1 -0
  63. package/lib/Signal/lid-mapping.d.ts +19 -0
  64. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  65. package/lib/Signal/lid-mapping.js +271 -0
  66. package/lib/Signal/lid-mapping.js.map +1 -0
  67. package/lib/Socket/Client/index.d.ts +3 -3
  68. package/lib/Socket/Client/index.d.ts.map +1 -0
  69. package/lib/Socket/Client/index.js +3 -19
  70. package/lib/Socket/Client/index.js.map +1 -0
  71. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +4 -5
  72. package/lib/Socket/Client/types.d.ts.map +1 -0
  73. package/lib/Socket/Client/types.js +11 -0
  74. package/lib/Socket/Client/types.js.map +1 -0
  75. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +3 -2
  76. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  77. package/lib/Socket/Client/websocket.js +54 -0
  78. package/lib/Socket/Client/websocket.js.map +1 -0
  79. package/lib/Socket/business.d.ts +533 -168
  80. package/lib/Socket/business.d.ts.map +1 -0
  81. package/lib/Socket/business.js +405 -243
  82. package/lib/Socket/business.js.map +1 -0
  83. package/lib/Socket/chats.d.ts +84 -240
  84. package/lib/Socket/chats.d.ts.map +1 -0
  85. package/lib/Socket/chats.js +406 -385
  86. package/lib/Socket/chats.js.map +1 -0
  87. package/lib/Socket/communities.d.ts +645 -0
  88. package/lib/Socket/communities.d.ts.map +1 -0
  89. package/lib/Socket/communities.js +431 -0
  90. package/lib/Socket/communities.js.map +1 -0
  91. package/lib/Socket/dugong.d.ts +125 -249
  92. package/lib/Socket/dugong.d.ts.map +1 -0
  93. package/lib/Socket/dugong.js +749 -465
  94. package/lib/Socket/dugong.js.map +1 -0
  95. package/lib/Socket/groups.d.ts +93 -58
  96. package/lib/Socket/groups.d.ts.map +1 -0
  97. package/lib/Socket/groups.js +105 -95
  98. package/lib/Socket/groups.js.map +1 -0
  99. package/lib/Socket/index.d.ts +632 -169
  100. package/lib/Socket/index.d.ts.map +1 -0
  101. package/lib/Socket/index.js +15 -11
  102. package/lib/Socket/index.js.map +1 -0
  103. package/lib/Socket/messages-recv.d.ts +162 -85
  104. package/lib/Socket/messages-recv.d.ts.map +1 -0
  105. package/lib/Socket/messages-recv.js +806 -608
  106. package/lib/Socket/messages-recv.js.map +1 -0
  107. package/lib/Socket/messages-send.d.ts +576 -146
  108. package/lib/Socket/messages-send.d.ts.map +1 -0
  109. package/lib/Socket/messages-send.js +1563 -861
  110. package/lib/Socket/messages-send.js.map +1 -0
  111. package/lib/Socket/mex.d.ts +3 -0
  112. package/lib/Socket/mex.d.ts.map +1 -0
  113. package/lib/Socket/mex.js +48 -0
  114. package/lib/Socket/mex.js.map +1 -0
  115. package/lib/Socket/newsletter.d.ts +129 -86
  116. package/lib/Socket/newsletter.d.ts.map +1 -0
  117. package/lib/Socket/newsletter.js +438 -302
  118. package/lib/Socket/newsletter.js.map +1 -0
  119. package/lib/Socket/socket.d.ts +31 -19
  120. package/lib/Socket/socket.d.ts.map +1 -0
  121. package/lib/Socket/socket.js +512 -241
  122. package/lib/Socket/socket.js.map +1 -0
  123. package/lib/Types/Auth.d.ts +18 -12
  124. package/lib/Types/Auth.d.ts.map +1 -0
  125. package/lib/Types/Auth.js +2 -2
  126. package/lib/Types/Auth.js.map +1 -0
  127. package/lib/Types/Bussines.d.ts +37 -0
  128. package/lib/Types/Bussines.d.ts.map +1 -0
  129. package/lib/Types/Bussines.js +2 -0
  130. package/lib/Types/Bussines.js.map +1 -0
  131. package/lib/Types/Call.d.ts +3 -1
  132. package/lib/Types/Call.d.ts.map +1 -0
  133. package/lib/Types/Call.js +2 -2
  134. package/lib/Types/Call.js.map +1 -0
  135. package/lib/Types/Chat.d.ts +34 -13
  136. package/lib/Types/Chat.d.ts.map +1 -0
  137. package/lib/Types/Chat.js +8 -4
  138. package/lib/Types/Chat.js.map +1 -0
  139. package/lib/Types/Contact.d.ts +6 -1
  140. package/lib/Types/Contact.d.ts.map +1 -0
  141. package/lib/Types/Contact.js +2 -2
  142. package/lib/Types/Contact.js.map +1 -0
  143. package/lib/Types/Events.d.ts +97 -17
  144. package/lib/Types/Events.d.ts.map +1 -0
  145. package/lib/Types/Events.js +2 -2
  146. package/lib/Types/Events.js.map +1 -0
  147. package/lib/Types/GroupMetadata.d.ts +18 -5
  148. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  149. package/lib/Types/GroupMetadata.js +2 -2
  150. package/lib/Types/GroupMetadata.js.map +1 -0
  151. package/lib/Types/Label.d.ts +12 -0
  152. package/lib/Types/Label.d.ts.map +1 -0
  153. package/lib/Types/Label.js +3 -5
  154. package/lib/Types/Label.js.map +1 -0
  155. package/lib/Types/LabelAssociation.d.ts +1 -0
  156. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  157. package/lib/Types/LabelAssociation.js +3 -5
  158. package/lib/Types/LabelAssociation.js.map +1 -0
  159. package/lib/Types/Message.d.ts +355 -206
  160. package/lib/Types/Message.d.ts.map +1 -0
  161. package/lib/Types/Message.js +11 -9
  162. package/lib/Types/Message.js.map +1 -0
  163. package/lib/Types/Newsletter.d.ts +130 -98
  164. package/lib/Types/Newsletter.d.ts.map +1 -0
  165. package/lib/Types/Newsletter.js +31 -38
  166. package/lib/Types/Newsletter.js.map +1 -0
  167. package/lib/Types/Product.d.ts +2 -1
  168. package/lib/Types/Product.d.ts.map +1 -0
  169. package/lib/Types/Product.js +2 -2
  170. package/lib/Types/Product.js.map +1 -0
  171. package/lib/Types/Signal.d.ts +20 -1
  172. package/lib/Types/Signal.d.ts.map +1 -0
  173. package/lib/Types/Signal.js +2 -2
  174. package/lib/Types/Signal.js.map +1 -0
  175. package/lib/Types/Socket.d.ts +152 -105
  176. package/lib/Types/Socket.d.ts.map +1 -0
  177. package/lib/Types/Socket.js +3 -2
  178. package/lib/Types/Socket.js.map +1 -0
  179. package/lib/Types/State.d.ts +14 -2
  180. package/lib/Types/State.d.ts.map +1 -0
  181. package/lib/Types/State.js +13 -2
  182. package/lib/Types/State.js.map +1 -0
  183. package/lib/Types/USync.d.ts +3 -2
  184. package/lib/Types/USync.d.ts.map +1 -0
  185. package/lib/Types/USync.js +2 -2
  186. package/lib/Types/USync.js.map +1 -0
  187. package/lib/Types/index.d.ts +54 -45
  188. package/lib/Types/index.d.ts.map +1 -0
  189. package/lib/Types/index.js +32 -41
  190. package/lib/Types/index.js.map +1 -0
  191. package/lib/Utils/auth-utils.d.ts +7 -6
  192. package/lib/Utils/auth-utils.d.ts.map +1 -0
  193. package/lib/Utils/auth-utils.js +228 -144
  194. package/lib/Utils/auth-utils.js.map +1 -0
  195. package/lib/Utils/browser-utils.d.ts +4 -0
  196. package/lib/Utils/browser-utils.d.ts.map +1 -0
  197. package/lib/Utils/browser-utils.js +28 -0
  198. package/lib/Utils/browser-utils.js.map +1 -0
  199. package/lib/Utils/business.d.ts +3 -2
  200. package/lib/Utils/business.d.ts.map +1 -0
  201. package/lib/Utils/business.js +66 -69
  202. package/lib/Utils/business.js.map +1 -0
  203. package/lib/Utils/chat-utils.d.ts +19 -20
  204. package/lib/Utils/chat-utils.d.ts.map +1 -0
  205. package/lib/Utils/chat-utils.js +331 -248
  206. package/lib/Utils/chat-utils.js.map +1 -0
  207. package/lib/Utils/crypto.d.ts +10 -14
  208. package/lib/Utils/crypto.d.ts.map +1 -0
  209. package/lib/Utils/crypto.js +57 -90
  210. package/lib/Utils/crypto.js.map +1 -0
  211. package/lib/Utils/decode-wa-message.d.ts +37 -8
  212. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  213. package/lib/Utils/decode-wa-message.js +169 -84
  214. package/lib/Utils/decode-wa-message.js.map +1 -0
  215. package/lib/Utils/event-buffer.d.ts +7 -8
  216. package/lib/Utils/event-buffer.d.ts.map +1 -0
  217. package/lib/Utils/event-buffer.js +138 -78
  218. package/lib/Utils/event-buffer.js.map +1 -0
  219. package/lib/Utils/generics.d.ts +26 -27
  220. package/lib/Utils/generics.d.ts.map +1 -0
  221. package/lib/Utils/generics.js +170 -209
  222. package/lib/Utils/generics.js.map +1 -0
  223. package/lib/Utils/history.d.ts +16 -9
  224. package/lib/Utils/history.d.ts.map +1 -0
  225. package/lib/Utils/history.js +83 -48
  226. package/lib/Utils/history.js.map +1 -0
  227. package/lib/Utils/identity-change-handler.d.ts +37 -0
  228. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  229. package/lib/Utils/identity-change-handler.js +49 -0
  230. package/lib/Utils/identity-change-handler.js.map +1 -0
  231. package/lib/Utils/index.d.ts +23 -17
  232. package/lib/Utils/index.d.ts.map +1 -0
  233. package/lib/Utils/index.js +23 -33
  234. package/lib/Utils/index.js.map +1 -0
  235. package/lib/Utils/link-preview.d.ts +5 -5
  236. package/lib/Utils/link-preview.d.ts.map +1 -0
  237. package/lib/Utils/link-preview.js +14 -22
  238. package/lib/Utils/link-preview.js.map +1 -0
  239. package/lib/Utils/logger.d.ts +12 -3
  240. package/lib/Utils/logger.d.ts.map +1 -0
  241. package/lib/Utils/logger.js +3 -7
  242. package/lib/Utils/logger.js.map +1 -0
  243. package/lib/Utils/lt-hash.d.ts +8 -12
  244. package/lib/Utils/lt-hash.d.ts.map +1 -0
  245. package/lib/Utils/lt-hash.js +3 -46
  246. package/lib/Utils/lt-hash.js.map +1 -0
  247. package/lib/Utils/make-mutex.d.ts +4 -2
  248. package/lib/Utils/make-mutex.d.ts.map +1 -0
  249. package/lib/Utils/make-mutex.js +24 -34
  250. package/lib/Utils/make-mutex.js.map +1 -0
  251. package/lib/Utils/message-retry-manager.d.ts +110 -0
  252. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  253. package/lib/Utils/message-retry-manager.js +225 -0
  254. package/lib/Utils/message-retry-manager.js.map +1 -0
  255. package/lib/Utils/messages-media.d.ts +56 -42
  256. package/lib/Utils/messages-media.d.ts.map +1 -0
  257. package/lib/Utils/messages-media.js +411 -448
  258. package/lib/Utils/messages-media.js.map +1 -0
  259. package/lib/Utils/messages.d.ts +32 -18
  260. package/lib/Utils/messages.d.ts.map +1 -0
  261. package/lib/Utils/messages.js +1132 -710
  262. package/lib/Utils/messages.js.map +1 -0
  263. package/lib/Utils/noise-handler.d.ts +12 -13
  264. package/lib/Utils/noise-handler.d.ts.map +1 -0
  265. package/lib/Utils/noise-handler.js +145 -99
  266. package/lib/Utils/noise-handler.js.map +1 -0
  267. package/lib/Utils/offline-node-processor.d.ts +17 -0
  268. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  269. package/lib/Utils/offline-node-processor.js +40 -0
  270. package/lib/Utils/offline-node-processor.js.map +1 -0
  271. package/lib/Utils/pre-key-manager.d.ts +28 -0
  272. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  273. package/lib/Utils/pre-key-manager.js +106 -0
  274. package/lib/Utils/pre-key-manager.js.map +1 -0
  275. package/lib/Utils/process-message.d.ts +31 -12
  276. package/lib/Utils/process-message.d.ts.map +1 -0
  277. package/lib/Utils/process-message.js +357 -150
  278. package/lib/Utils/process-message.js.map +1 -0
  279. package/lib/Utils/reporting-utils.d.ts +11 -0
  280. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  281. package/lib/Utils/reporting-utils.js +258 -0
  282. package/lib/Utils/reporting-utils.js.map +1 -0
  283. package/lib/Utils/rich-messages.d.ts +277 -0
  284. package/lib/Utils/rich-messages.d.ts.map +1 -0
  285. package/lib/Utils/rich-messages.js +1144 -0
  286. package/lib/Utils/rich-messages.js.map +1 -0
  287. package/lib/Utils/signal.d.ts +7 -5
  288. package/lib/Utils/signal.d.ts.map +1 -0
  289. package/lib/Utils/signal.js +78 -72
  290. package/lib/Utils/signal.js.map +1 -0
  291. package/lib/Utils/stanza-ack.d.ts +11 -0
  292. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  293. package/lib/Utils/stanza-ack.js +38 -0
  294. package/lib/Utils/stanza-ack.js.map +1 -0
  295. package/lib/Utils/sticker-pack.d.ts +10 -0
  296. package/lib/Utils/sticker-pack.js +111 -0
  297. package/lib/Utils/sync-action-utils.d.ts +19 -0
  298. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  299. package/lib/Utils/sync-action-utils.js +48 -0
  300. package/lib/Utils/sync-action-utils.js.map +1 -0
  301. package/lib/Utils/tc-token-utils.d.ts +12 -0
  302. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  303. package/lib/Utils/tc-token-utils.js +18 -0
  304. package/lib/Utils/tc-token-utils.js.map +1 -0
  305. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  306. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  307. package/lib/Utils/use-multi-file-auth-state.js +29 -27
  308. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  309. package/lib/Utils/validate-connection.d.ts +7 -7
  310. package/lib/Utils/validate-connection.d.ts.map +1 -0
  311. package/lib/Utils/validate-connection.js +70 -99
  312. package/lib/Utils/validate-connection.js.map +1 -0
  313. package/lib/WABinary/constants.d.ts +25 -27
  314. package/lib/WABinary/constants.d.ts.map +1 -0
  315. package/lib/WABinary/constants.js +1281 -20
  316. package/lib/WABinary/constants.js.map +1 -0
  317. package/lib/WABinary/decode.d.ts +5 -5
  318. package/lib/WABinary/decode.d.ts.map +1 -0
  319. package/lib/WABinary/decode.js +52 -42
  320. package/lib/WABinary/decode.js.map +1 -0
  321. package/lib/WABinary/encode.d.ts +3 -3
  322. package/lib/WABinary/encode.d.ts.map +1 -0
  323. package/lib/WABinary/encode.js +110 -155
  324. package/lib/WABinary/encode.js.map +1 -0
  325. package/lib/WABinary/generic-utils.d.ts +8 -8
  326. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  327. package/lib/WABinary/generic-utils.js +142 -149
  328. package/lib/WABinary/generic-utils.js.map +1 -0
  329. package/lib/WABinary/index.d.ts +6 -5
  330. package/lib/WABinary/index.d.ts.map +1 -0
  331. package/lib/WABinary/index.js +6 -21
  332. package/lib/WABinary/index.js.map +1 -0
  333. package/lib/WABinary/jid-utils.d.ts +25 -8
  334. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  335. package/lib/WABinary/jid-utils.js +74 -40
  336. package/lib/WABinary/jid-utils.js.map +1 -0
  337. package/lib/WABinary/types.d.ts +2 -1
  338. package/lib/WABinary/types.d.ts.map +1 -0
  339. package/lib/WABinary/types.js +2 -2
  340. package/lib/WABinary/types.js.map +1 -0
  341. package/lib/WAM/BinaryInfo.d.ts +3 -11
  342. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  343. package/lib/WAM/BinaryInfo.js +2 -5
  344. package/lib/WAM/BinaryInfo.js.map +1 -0
  345. package/lib/WAM/constants.d.ts +5 -3
  346. package/lib/WAM/constants.d.ts.map +1 -0
  347. package/lib/WAM/constants.js +19071 -11568
  348. package/lib/WAM/constants.js.map +1 -0
  349. package/lib/WAM/encode.d.ts +2 -2
  350. package/lib/WAM/encode.d.ts.map +1 -0
  351. package/lib/WAM/encode.js +17 -22
  352. package/lib/WAM/encode.js.map +1 -0
  353. package/lib/WAM/index.d.ts +4 -3
  354. package/lib/WAM/index.d.ts.map +1 -0
  355. package/lib/WAM/index.js +4 -19
  356. package/lib/WAM/index.js.map +1 -0
  357. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +4 -3
  358. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  360. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +3 -2
  362. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  364. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +3 -2
  366. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  368. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +3 -2
  370. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  372. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +4 -3
  374. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +5 -3
  378. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/index.d.ts +5 -4
  382. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/index.js +5 -20
  384. package/lib/WAUSync/Protocols/index.js.map +1 -0
  385. package/lib/WAUSync/USyncQuery.d.ts +5 -4
  386. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  387. package/lib/WAUSync/USyncQuery.js +40 -35
  388. package/lib/WAUSync/USyncQuery.js.map +1 -0
  389. package/lib/WAUSync/USyncUser.d.ts +6 -5
  390. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncUser.js +2 -5
  392. package/lib/WAUSync/USyncUser.js.map +1 -0
  393. package/lib/WAUSync/index.d.ts +4 -3
  394. package/lib/WAUSync/index.d.ts.map +1 -0
  395. package/lib/WAUSync/index.js +4 -19
  396. package/lib/WAUSync/index.js.map +1 -0
  397. package/lib/index.d.ts +10 -9
  398. package/lib/index.d.ts.map +1 -0
  399. package/lib/index.js +12 -33
  400. package/lib/index.js.map +1 -0
  401. package/package.json +64 -105
  402. package/README.md +0 -364
  403. package/engine-requirements.js +0 -10
  404. package/lib/Defaults/baileys-version.json +0 -3
  405. package/lib/Defaults/phonenumber-mcc.json +0 -223
  406. package/lib/Signal/Group/queue-job.d.ts +0 -1
  407. package/lib/Signal/Group/queue-job.js +0 -57
  408. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  409. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  410. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  411. package/lib/Socket/Client/web-socket-client.js +0 -62
  412. package/lib/Socket/registration.d.ts +0 -267
  413. package/lib/Socket/registration.js +0 -166
  414. package/lib/Socket/usync.d.ts +0 -36
  415. package/lib/Socket/usync.js +0 -70
  416. package/lib/Store/index.d.ts +0 -3
  417. package/lib/Store/index.js +0 -10
  418. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  419. package/lib/Store/make-cache-manager-store.js +0 -83
  420. package/lib/Store/make-in-memory-store.d.ts +0 -118
  421. package/lib/Store/make-in-memory-store.js +0 -427
  422. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  423. package/lib/Store/make-ordered-dictionary.js +0 -81
  424. package/lib/Store/object-repository.d.ts +0 -10
  425. package/lib/Store/object-repository.js +0 -27
  426. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  427. package/lib/Utils/baileys-event-stream.js +0 -63
@@ -1,816 +1,1238 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.assertMediaContent = exports.downloadMediaMessage = exports.aggregateMessageKeysNotFromMe = exports.getAggregateVotesInPollMessage = exports.updateMessageWithPollUpdate = exports.updateMessageWithReaction = exports.updateMessageWithReceipt = exports.getDevice = exports.extractMessageContent = exports.normalizeMessageContent = exports.getContentType = exports.generateWAMessage = exports.generateWAMessageFromContent = exports.generateWAMessageContent = exports.generateForwardMessageContent = exports.prepareDisappearingMessageSettingContent = exports.prepareWAMessageMedia = exports.generateLinkPreviewIfRequired = exports.extractUrlFromText = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const axios_1 = __importDefault(require("axios"));
9
- const crypto_1 = require("crypto");
10
- const fs_1 = require("fs");
11
- const WAProto_1 = require("../../WAProto");
12
- const Defaults_1 = require("../Defaults");
13
- const Types_1 = require("../Types");
14
- const WABinary_1 = require("../WABinary");
15
- const crypto_2 = require("./crypto");
16
- const generics_1 = require("./generics");
17
- const messages_media_1 = require("./messages-media");
1
+ import { Boom } from "@hapi/boom";
2
+ import { randomBytes } from "crypto";
3
+ import { promises as fs } from "fs";
4
+ import {} from "stream";
5
+ import { proto } from "../../WAProto/index.js";
6
+ import {
7
+ CALL_AUDIO_PREFIX,
8
+ CALL_VIDEO_PREFIX,
9
+ MEDIA_KEYS,
10
+ URL_REGEX,
11
+ WA_DEFAULT_EPHEMERAL,
12
+ } from "../Defaults/index.js";
13
+ import { WAMessageStatus, WAProto } from "../Types/index.js";
14
+ import {
15
+ isJidGroup,
16
+ isJidNewsletter,
17
+ isJidStatusBroadcast,
18
+ jidNormalizedUser,
19
+ } from "../WABinary/index.js";
20
+ import { sha256 } from "./crypto.js";
21
+ import {
22
+ generateMessageIDV2,
23
+ getKeyAuthor,
24
+ unixTimestampSeconds,
25
+ } from "./generics.js";
26
+ import {
27
+ downloadContentFromMessage,
28
+ encryptedStream,
29
+ generateThumbnail,
30
+ getAudioDuration,
31
+ getAudioWaveform,
32
+ getRawMediaUploadData,
33
+ } from "./messages-media.js";
34
+ import { shouldIncludeReportingToken } from "./reporting-utils.js";
18
35
  const MIMETYPE_MAP = {
19
- image: 'image/jpeg',
20
- video: 'video/mp4',
21
- document: 'application/pdf',
22
- audio: 'audio/ogg; codecs=opus',
23
- sticker: 'image/webp',
24
- 'product-catalog-image': 'image/jpeg',
36
+ image: "image/jpeg",
37
+ video: "video/mp4",
38
+ document: "application/pdf",
39
+ audio: "audio/ogg; codecs=opus",
40
+ sticker: "image/webp",
41
+ "product-catalog-image": "image/jpeg",
25
42
  };
26
43
  const MessageTypeProto = {
27
- 'image': Types_1.WAProto.Message.ImageMessage,
28
- 'video': Types_1.WAProto.Message.VideoMessage,
29
- 'audio': Types_1.WAProto.Message.AudioMessage,
30
- 'sticker': Types_1.WAProto.Message.StickerMessage,
31
- 'document': Types_1.WAProto.Message.DocumentMessage,
44
+ image: WAProto.Message.ImageMessage,
45
+ video: WAProto.Message.VideoMessage,
46
+ audio: WAProto.Message.AudioMessage,
47
+ sticker: WAProto.Message.StickerMessage,
48
+ document: WAProto.Message.DocumentMessage,
32
49
  };
33
- const ButtonType = WAProto_1.proto.Message.ButtonsMessage.HeaderType;
34
50
  /**
35
51
  * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
36
52
  * @param text eg. hello https://google.com
37
53
  * @returns the URL, eg. https://google.com
38
54
  */
39
- const extractUrlFromText = (text) => { var _a; return (_a = text.match(Defaults_1.URL_REGEX)) === null || _a === void 0 ? void 0 : _a[0]; };
40
- exports.extractUrlFromText = extractUrlFromText;
41
- const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
42
- const url = (0, exports.extractUrlFromText)(text);
43
- if (!!getUrlInfo && url) {
44
- try {
45
- const urlInfo = await getUrlInfo(url);
46
- return urlInfo;
47
- }
48
- catch (error) { // ignore if fails
49
- logger === null || logger === void 0 ? void 0 : logger.warn({ trace: error.stack }, 'url generation failed');
50
- }
55
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
56
+ export const generateLinkPreviewIfRequired = async (
57
+ text,
58
+ getUrlInfo,
59
+ logger,
60
+ ) => {
61
+ const url = extractUrlFromText(text);
62
+ if (!!getUrlInfo && url) {
63
+ try {
64
+ const urlInfo = await getUrlInfo(url);
65
+ return urlInfo;
66
+ } catch (error) {
67
+ // ignore if fails
68
+ logger?.warn({ trace: error.stack }, "url generation failed");
51
69
  }
70
+ }
52
71
  };
53
- exports.generateLinkPreviewIfRequired = generateLinkPreviewIfRequired;
54
72
  const assertColor = async (color) => {
55
- let assertedColor;
56
- if (typeof color === 'number') {
57
- assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
58
- }
59
- else {
60
- let hex = color.trim().replace('#', '');
61
- if (hex.length <= 6) {
62
- hex = 'FF' + hex.padStart(6, '0');
63
- }
64
- assertedColor = parseInt(hex, 16);
65
- return assertedColor;
73
+ let assertedColor;
74
+ if (typeof color === "number") {
75
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
76
+ } else {
77
+ let hex = color.trim().replace("#", "");
78
+ if (hex.length <= 6) {
79
+ hex = "FF" + hex.padStart(6, "0");
66
80
  }
81
+ assertedColor = parseInt(hex, 16);
82
+ return assertedColor;
83
+ }
67
84
  };
68
- const prepareWAMessageMedia = async (message, options) => {
69
- const logger = options.logger;
70
- let mediaType;
71
- for (const key of Defaults_1.MEDIA_KEYS) {
72
- if (key in message) {
73
- mediaType = key;
74
- }
85
+ export const prepareWAMessageMedia = async (message, options) => {
86
+ const logger = options.logger;
87
+ let mediaType;
88
+ for (const key of MEDIA_KEYS) {
89
+ if (key in message) {
90
+ mediaType = key;
75
91
  }
76
- if (!mediaType) {
77
- throw new boom_1.Boom('Invalid media type', {
78
- statusCode: 400
79
- });
92
+ }
93
+ if (!mediaType) {
94
+ throw new Boom("Invalid media type", { statusCode: 400 });
95
+ }
96
+ const uploadData = {
97
+ ...message,
98
+ media: message[mediaType],
99
+ };
100
+ delete uploadData[mediaType];
101
+ // check if cacheable + generate cache key
102
+ const cacheableKey =
103
+ typeof uploadData.media === "object" &&
104
+ "url" in uploadData.media &&
105
+ !!uploadData.media.url &&
106
+ !!options.mediaCache &&
107
+ mediaType + ":" + uploadData.media.url.toString();
108
+ if (mediaType === "document" && !uploadData.fileName) {
109
+ uploadData.fileName = "file";
110
+ }
111
+ if (!uploadData.mimetype) {
112
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
113
+ }
114
+ if (cacheableKey) {
115
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
116
+ if (mediaBuff) {
117
+ logger?.debug({ cacheableKey }, "got media cache hit");
118
+ const obj = proto.Message.decode(mediaBuff);
119
+ const key = `${mediaType}Message`;
120
+ Object.assign(obj[key], { ...uploadData, media: undefined });
121
+ return obj;
80
122
  }
81
-
82
- const uploadData = {
83
- ...message,
84
- ...(message.annotations ? {
85
- annotations: message.annotations
86
- } : {
87
- annotations: [
88
- {
89
- polygonVertices: [
90
- {
91
- x: 60.71664810180664,
92
- y: -36.39784622192383
93
- },
94
- {
95
- x: -16.710189819335938,
96
- y: 49.263675689697266
97
- },
98
- {
99
- x: -56.585853576660156,
100
- y: 37.85963439941406
101
- },
102
- {
103
- x: 20.840980529785156,
104
- y: -47.80188751220703
105
- }
106
- ],
107
- newsletter: {
108
- newsletterJid: "120363379975415016@newsletter",
109
- serverMessageId: 0,
110
- newsletterName: "Modz Never Die",
111
- contentType: "UPDATE",
112
- }
113
- }
114
- ]
115
- }),
116
- media: message[mediaType]
117
- };
118
- delete uploadData[mediaType];
119
- const cacheableKey = typeof uploadData.media === 'object' &&
120
- ('url' in uploadData.media) &&
121
- !!uploadData.media.url &&
122
- !!options.mediaCache && (
123
- mediaType + ':' + uploadData.media.url.toString());
124
-
125
- if (mediaType === 'document' && !uploadData.fileName) {
126
- uploadData.fileName = 'file';
127
- }
128
-
129
- if (!uploadData.mimetype) {
130
- uploadData.mimetype = MIMETYPE_MAP[mediaType];
131
- }
132
-
133
- if (cacheableKey) {
134
- const mediaBuff = options.mediaCache.get(cacheableKey);
135
- if (mediaBuff) {
136
- logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'got media cache hit');
137
- const obj = Types_1.WAProto.Message.decode(mediaBuff);
138
- const key = `${mediaType}Message`;
139
- Object.assign(obj[key], { ...uploadData, media: undefined });
140
- return obj;
123
+ }
124
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
125
+ if (isNewsletter) {
126
+ logger?.info({ key: cacheableKey }, "Preparing raw media for newsletter");
127
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(
128
+ uploadData.media,
129
+ options.mediaTypeOverride || mediaType,
130
+ logger,
131
+ );
132
+ const requiresDurationComputation =
133
+ mediaType === "audio" && typeof uploadData.seconds === "undefined";
134
+ const requiresThumbnailComputation =
135
+ (mediaType === "image" || mediaType === "video") &&
136
+ typeof uploadData["jpegThumbnail"] === "undefined";
137
+ const requiresWaveformProcessing =
138
+ mediaType === "audio" &&
139
+ uploadData.ptt === true &&
140
+ typeof uploadData.waveform === "undefined";
141
+ const requiresAudioBackground =
142
+ options.backgroundColor &&
143
+ mediaType === "audio" &&
144
+ uploadData.ptt === true;
145
+ try {
146
+ if (requiresThumbnailComputation) {
147
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(
148
+ filePath,
149
+ mediaType,
150
+ options,
151
+ );
152
+ uploadData.jpegThumbnail = thumbnail;
153
+ if (!uploadData.width && originalImageDimensions) {
154
+ uploadData.width = originalImageDimensions.width;
155
+ uploadData.height = originalImageDimensions.height;
156
+ logger?.debug("set dimensions");
141
157
  }
158
+ logger?.debug("generated thumbnail");
159
+ }
160
+ if (requiresDurationComputation) {
161
+ uploadData.seconds = await getAudioDuration(filePath);
162
+ logger?.debug("computed audio duration");
163
+ }
164
+ if (requiresWaveformProcessing) {
165
+ uploadData.waveform = await getAudioWaveform(filePath, logger);
166
+ logger?.debug("processed waveform");
167
+ }
168
+ if (requiresAudioBackground) {
169
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
170
+ logger?.debug("computed backgroundColor audio status");
171
+ }
172
+ } catch (error) {
173
+ logger?.warn({ trace: error.stack }, "failed to obtain extra info");
142
174
  }
143
-
144
- const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
145
- const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
146
- (typeof uploadData['jpegThumbnail'] === 'undefined');
147
- const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
148
- const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
149
- const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
150
-
151
- const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, opusConverted } = await (options.newsletter ? messages_media_1.prepareStream : messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
152
- logger,
153
- saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
154
- opts: options.options,
155
- isPtt: uploadData.ptt,
156
- forceOpus: (mediaType === "audio" && uploadData.mimetype && uploadData.mimetype.includes('opus'))
175
+ const fileSha256B64 = fileSha256.toString("base64");
176
+ const { mediaUrl, directPath } = await options.upload(filePath, {
177
+ fileEncSha256B64: fileSha256B64,
178
+ mediaType: mediaType,
179
+ newsletter: true,
180
+ timeoutMs: options.mediaUploadTimeoutMs,
157
181
  });
158
-
159
- if (mediaType === 'audio' && opusConverted) {
160
- uploadData.mimetype = 'audio/ogg; codecs=opus';
161
- }
162
-
163
- const fileEncSha256B64 = (options.newsletter ? fileSha256 : fileEncSha256 !== null && fileEncSha256 !== void 0 ? fileEncSha256 : fileSha256).toString('base64');
164
-
165
- const [{ mediaUrl, directPath, handle }] = await Promise.all([
166
- (async () => {
167
- const result = await options.upload(encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs });
168
- logger === null || logger === void 0 ? void 0 : logger.debug({ mediaType, cacheableKey }, 'uploaded media');
169
- return result;
170
- })(),
171
- (async () => {
172
- try {
173
- if (requiresThumbnailComputation) {
174
- const { thumbnail, originalImageDimensions } = await (0, messages_media_1.generateThumbnail)(bodyPath, mediaType, options);
175
- uploadData.jpegThumbnail = thumbnail;
176
- if (!uploadData.width && originalImageDimensions) {
177
- uploadData.width = originalImageDimensions.width;
178
- uploadData.height = originalImageDimensions.height;
179
- logger === null || logger === void 0 ? void 0 : logger.debug('set dimensions');
180
- }
181
- logger === null || logger === void 0 ? void 0 : logger.debug('generated thumbnail');
182
- }
183
- if (requiresDurationComputation) {
184
- uploadData.seconds = await (0, messages_media_1.getAudioDuration)(bodyPath);
185
- logger === null || logger === void 0 ? void 0 : logger.debug('computed audio duration');
186
- }
187
- if (requiresWaveformProcessing) {
188
- uploadData.waveform = await (0, messages_media_1.getAudioWaveform)(bodyPath, logger);
189
- logger === null || logger === void 0 ? void 0 : logger.debug('processed waveform');
190
- }
191
- if (requiresAudioBackground) {
192
- uploadData.backgroundArgb = await assertColor(options.backgroundColor);
193
- logger === null || logger === void 0 ? void 0 : logger.debug('computed backgroundColor audio status');
194
- }
195
- }
196
- catch (error) {
197
- logger === null || logger === void 0 ? void 0 : logger.warn({ trace: error.stack }, 'failed to obtain extra info');
198
- }
199
- })(),
200
- ])
201
- .finally(async () => {
202
- if (!Buffer.isBuffer(encWriteStream)) {
203
- encWriteStream.destroy();
204
- }
205
-
206
- if (didSaveToTmpPath && bodyPath) {
207
- await fs_1.promises.unlink(bodyPath);
208
- logger === null || logger === void 0 ? void 0 : logger.debug('removed tmp files');
209
- }
182
+ await fs.unlink(filePath);
183
+ const obj = WAProto.Message.fromObject({
184
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
185
+ url: mediaUrl,
186
+ directPath,
187
+ fileSha256,
188
+ fileLength,
189
+ mediaKeyTimestamp: unixTimestampSeconds(),
190
+ ...uploadData,
191
+ media: undefined,
192
+ }),
210
193
  });
211
-
212
- const obj = Types_1.WAProto.Message.fromObject({
213
- [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
214
- url: handle ? undefined : mediaUrl,
215
- directPath,
216
- mediaKey: mediaKey,
217
- fileEncSha256: fileEncSha256,
218
- fileSha256,
219
- fileLength,
220
- mediaKeyTimestamp: handle ? undefined : (0, generics_1.unixTimestampSeconds)(),
221
- ...uploadData,
222
- media: undefined
223
- })
224
- });
225
-
226
194
  if (uploadData.ptv) {
227
- obj.ptvMessage = obj.videoMessage;
228
- delete obj.videoMessage;
195
+ obj.ptvMessage = obj.videoMessage;
196
+ delete obj.videoMessage;
197
+ }
198
+ if (obj.stickerMessage) {
199
+ obj.stickerMessage.stickerSentTs = Date.now();
229
200
  }
230
-
231
201
  if (cacheableKey) {
232
- logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'set cache');
233
- options.mediaCache.set(cacheableKey, Types_1.WAProto.Message.encode(obj).finish());
202
+ logger?.debug({ cacheableKey }, "set cache");
203
+ await options.mediaCache.set(
204
+ cacheableKey,
205
+ WAProto.Message.encode(obj).finish(),
206
+ );
234
207
  }
235
-
236
208
  return obj;
237
- };
238
- exports.prepareWAMessageMedia = prepareWAMessageMedia;
239
- const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
240
- ephemeralExpiration = ephemeralExpiration || 0;
241
- const content = {
242
- ephemeralMessage: {
243
- message: {
244
- protocolMessage: {
245
- type: Types_1.WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
246
- ephemeralExpiration
247
- }
209
+ }
210
+ const requiresDurationComputation =
211
+ mediaType === "audio" && typeof uploadData.seconds === "undefined";
212
+ const requiresThumbnailComputation =
213
+ (mediaType === "image" || mediaType === "video") &&
214
+ typeof uploadData["jpegThumbnail"] === "undefined";
215
+ const requiresWaveformProcessing =
216
+ mediaType === "audio" &&
217
+ uploadData.ptt === true &&
218
+ typeof uploadData.waveform === "undefined";
219
+ const requiresAudioBackground =
220
+ options.backgroundColor && mediaType === "audio" && uploadData.ptt === true;
221
+ const requiresOriginalForSomeProcessing =
222
+ requiresDurationComputation ||
223
+ requiresThumbnailComputation ||
224
+ requiresWaveformProcessing;
225
+ const {
226
+ mediaKey,
227
+ encWriteStream,
228
+ bodyPath,
229
+ fileEncSha256,
230
+ fileSha256,
231
+ fileLength,
232
+ didSaveToTmpPath,
233
+ } = await encryptedStream(
234
+ uploadData.media,
235
+ options.mediaTypeOverride || mediaType,
236
+ {
237
+ logger,
238
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
239
+ opts: options.options,
240
+ },
241
+ );
242
+ const fileEncSha256B64 = fileEncSha256.toString("base64");
243
+ const [{ mediaUrl, directPath }] = await Promise.all([
244
+ (async () => {
245
+ const result = await options.upload(encWriteStream, {
246
+ fileEncSha256B64,
247
+ mediaType,
248
+ timeoutMs: options.mediaUploadTimeoutMs,
249
+ });
250
+ logger?.debug({ mediaType, cacheableKey }, "uploaded media");
251
+ return result;
252
+ })(),
253
+ (async () => {
254
+ try {
255
+ if (requiresThumbnailComputation) {
256
+ const { thumbnail, originalImageDimensions } =
257
+ await generateThumbnail(bodyPath, mediaType, options);
258
+ uploadData.jpegThumbnail = thumbnail;
259
+ if (!uploadData.width && originalImageDimensions) {
260
+ uploadData.width = originalImageDimensions.width;
261
+ uploadData.height = originalImageDimensions.height;
262
+ logger?.debug("set dimensions");
263
+ }
264
+ logger?.debug("generated thumbnail");
265
+ }
266
+ if (requiresDurationComputation) {
267
+ try {
268
+ if (bodyPath) {
269
+ uploadData.seconds = await getAudioDuration(bodyPath);
248
270
  }
271
+ } catch (err) {
272
+ uploadData.seconds = 0;
273
+ }
274
+ if (
275
+ typeof uploadData.seconds !== "number" ||
276
+ isNaN(uploadData.seconds)
277
+ ) {
278
+ uploadData.seconds = 0;
279
+ }
280
+ logger?.debug("computed audio duration");
249
281
  }
250
- };
251
- return Types_1.WAProto.Message.fromObject(content);
282
+ if (requiresWaveformProcessing) {
283
+ try {
284
+ uploadData.waveform = await getAudioWaveform(bodyPath, logger);
285
+ } catch (err) {}
286
+ if (!uploadData.waveform) {
287
+ uploadData.waveform = new Uint8Array([
288
+ 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0,
289
+ 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99,
290
+ ]);
291
+ }
292
+ logger?.debug("processed waveform");
293
+ }
294
+ if (requiresAudioBackground) {
295
+ uploadData.backgroundArgb = await assertColor(
296
+ options.backgroundColor,
297
+ );
298
+ logger?.debug("computed backgroundColor audio status");
299
+ }
300
+ } catch (error) {
301
+ logger?.warn({ trace: error.stack }, "failed to obtain extra info");
302
+ }
303
+ })(),
304
+ ]).finally(async () => {
305
+ try {
306
+ if (!Buffer.isBuffer(encWriteStream)) {
307
+ encWriteStream.destroy?.();
308
+ }
309
+ if (didSaveToTmpPath && bodyPath) {
310
+ await fs.unlink(bodyPath).catch(() => {});
311
+ }
312
+ } catch (error) {
313
+ logger?.warn("failed to remove tmp file");
314
+ }
315
+ });
316
+ const obj = WAProto.Message.fromObject({
317
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
318
+ url: mediaUrl,
319
+ directPath,
320
+ mediaKey,
321
+ fileEncSha256,
322
+ fileSha256,
323
+ fileLength,
324
+ mediaKeyTimestamp: unixTimestampSeconds(),
325
+ ...uploadData,
326
+ media: undefined,
327
+ }),
328
+ });
329
+ if (uploadData.ptv) {
330
+ obj.ptvMessage = obj.videoMessage;
331
+ delete obj.videoMessage;
332
+ }
333
+ if (obj.stickerMessage) {
334
+ obj.stickerMessage.stickerSentTs = Date.now();
335
+ }
336
+ if (cacheableKey) {
337
+ logger?.debug({ cacheableKey }, "set cache");
338
+ await options.mediaCache.set(
339
+ cacheableKey,
340
+ WAProto.Message.encode(obj).finish(),
341
+ );
342
+ }
343
+ return obj;
344
+ };
345
+ export const prepareDisappearingMessageSettingContent = (
346
+ ephemeralExpiration,
347
+ ) => {
348
+ ephemeralExpiration = ephemeralExpiration || 0;
349
+ const content = {
350
+ ephemeralMessage: {
351
+ message: {
352
+ protocolMessage: {
353
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
354
+ ephemeralExpiration,
355
+ },
356
+ },
357
+ },
358
+ };
359
+ return WAProto.Message.fromObject(content);
252
360
  };
253
- exports.prepareDisappearingMessageSettingContent = prepareDisappearingMessageSettingContent;
254
361
  /**
255
362
  * Generate forwarded message content like WA does
256
363
  * @param message the message to forward
257
364
  * @param options.forceForward will show the message as forwarded even if it is from you
258
365
  */
259
- const generateForwardMessageContent = (message, forceForward) => {
260
- var _a;
261
- let content = message.message;
262
- if (!content) {
263
- throw new boom_1.Boom('no content in message', { statusCode: 400 });
264
- }
265
- // hacky copy
266
- content = (0, exports.normalizeMessageContent)(content);
267
- content = WAProto_1.proto.Message.decode(WAProto_1.proto.Message.encode(content).finish());
268
- let key = Object.keys(content)[0];
269
- let score = ((_a = content[key].contextInfo) === null || _a === void 0 ? void 0 : _a.forwardingScore) || 0;
270
- score += message.key.fromMe && !forceForward ? 0 : 1;
271
- if (key === 'conversation') {
272
- content.extendedTextMessage = { text: content[key] };
273
- delete content.conversation;
274
- key = 'extendedTextMessage';
275
- }
276
- if (score > 0) {
277
- content[key].contextInfo = { forwardingScore: score, isForwarded: true };
278
- }
279
- else {
280
- content[key].contextInfo = {};
281
- }
282
- return content;
366
+ export const generateForwardMessageContent = (message, forceForward) => {
367
+ let content = message.message;
368
+ if (!content) {
369
+ throw new Boom("no content in message", { statusCode: 400 });
370
+ }
371
+ // hacky copy
372
+ content = normalizeMessageContent(content);
373
+ content = proto.Message.decode(proto.Message.encode(content).finish());
374
+ let key = Object.keys(content)[0];
375
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
376
+ score += message.key.fromMe && !forceForward ? 0 : 1;
377
+ if (key === "conversation") {
378
+ content.extendedTextMessage = { text: content[key] };
379
+ delete content.conversation;
380
+ key = "extendedTextMessage";
381
+ }
382
+ const key_ = content?.[key];
383
+ if (score > 0) {
384
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
385
+ } else {
386
+ key_.contextInfo = {};
387
+ }
388
+ return content;
283
389
  };
284
- exports.generateForwardMessageContent = generateForwardMessageContent;
285
- const generateWAMessageContent = async (message, options) => {
286
- var _a;
287
- var _b;
288
- let m = {};
289
- if ('text' in message) {
290
- const extContent = { text: message.text };
291
- let urlInfo = message.linkPreview;
292
- if (typeof urlInfo === 'undefined') {
293
- urlInfo = await (0, exports.generateLinkPreviewIfRequired)(message.text, options.getUrlInfo, options.logger);
294
- }
295
- if (urlInfo) {
296
- extContent.canonicalUrl = urlInfo['canonical-url'];
297
- extContent.matchedText = urlInfo['matched-text'];
298
- extContent.jpegThumbnail = urlInfo.jpegThumbnail;
299
- extContent.description = urlInfo.description;
300
- extContent.title = urlInfo.title;
301
- extContent.previewType = 0;
302
- const img = urlInfo.highQualityThumbnail;
303
- if (img) {
304
- extContent.thumbnailDirectPath = img.directPath;
305
- extContent.mediaKey = img.mediaKey;
306
- extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
307
- extContent.thumbnailWidth = img.width;
308
- extContent.thumbnailHeight = img.height;
309
- extContent.thumbnailSha256 = img.fileSha256;
310
- extContent.thumbnailEncSha256 = img.fileEncSha256;
311
- }
312
- }
313
- if (options.backgroundColor) {
314
- extContent.backgroundArgb = await assertColor(options.backgroundColor);
315
- }
316
- if (options.font) {
317
- extContent.font = options.font;
318
- }
319
- m.extendedTextMessage = extContent;
390
+ export const hasNonNullishProperty = (message, key) => {
391
+ return (
392
+ typeof message === "object" &&
393
+ message !== null &&
394
+ key in message &&
395
+ message[key] !== null &&
396
+ message[key] !== undefined
397
+ );
398
+ };
399
+ function hasOptionalProperty(obj, key) {
400
+ return (
401
+ typeof obj === "object" && obj !== null && key in obj && obj[key] !== null
402
+ );
403
+ }
404
+ export const generateWAMessageContent = async (message, options) => {
405
+ var _a, _b;
406
+ let m = {};
407
+ if (hasNonNullishProperty(message, "text")) {
408
+ const extContent = { text: message.text };
409
+ let urlInfo = message.linkPreview;
410
+ if (typeof urlInfo === "undefined") {
411
+ urlInfo = await generateLinkPreviewIfRequired(
412
+ message.text,
413
+ options.getUrlInfo,
414
+ options.logger,
415
+ );
320
416
  }
321
- else if ('contacts' in message) {
322
- const contactLen = message.contacts.contacts.length;
323
- if (!contactLen) {
324
- throw new boom_1.Boom('require atleast 1 contact', { statusCode: 400 });
325
- }
326
- if (contactLen === 1) {
327
- m.contactMessage = Types_1.WAProto.Message.ContactMessage.fromObject(message.contacts.contacts[0]);
328
- }
329
- else {
330
- m.contactsArrayMessage = Types_1.WAProto.Message.ContactsArrayMessage.fromObject(message.contacts);
331
- }
417
+ if (urlInfo) {
418
+ extContent.matchedText = urlInfo["matched-text"];
419
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
420
+ extContent.description = urlInfo.description;
421
+ extContent.title = urlInfo.title;
422
+ extContent.previewType = 0;
423
+ const img = urlInfo.highQualityThumbnail;
424
+ if (img) {
425
+ extContent.thumbnailDirectPath = img.directPath;
426
+ extContent.mediaKey = img.mediaKey;
427
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
428
+ extContent.thumbnailWidth = img.width;
429
+ extContent.thumbnailHeight = img.height;
430
+ extContent.thumbnailSha256 = img.fileSha256;
431
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
432
+ }
332
433
  }
333
- else if ('location' in message) {
334
- m.locationMessage = Types_1.WAProto.Message.LocationMessage.fromObject(message.location);
434
+ if (options.backgroundColor) {
435
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
335
436
  }
336
- else if ('react' in message) {
337
- if (!message.react.senderTimestampMs) {
338
- message.react.senderTimestampMs = Date.now();
339
- }
340
- m.reactionMessage = Types_1.WAProto.Message.ReactionMessage.fromObject(message.react);
437
+ if (options.textColor) {
438
+ extContent.textArgb = await assertColor(options.textColor);
341
439
  }
342
- else if ('delete' in message) {
343
- m.protocolMessage = {
344
- key: message.delete,
345
- type: Types_1.WAProto.Message.ProtocolMessage.Type.REVOKE
346
- };
440
+ if (options.font) {
441
+ extContent.font = options.font;
347
442
  }
348
- else if ('forward' in message) {
349
- m = (0, exports.generateForwardMessageContent)(message.forward, message.force);
350
- }
351
- else if ('disappearingMessagesInChat' in message) {
352
- const exp = typeof message.disappearingMessagesInChat === 'boolean' ?
353
- (message.disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
354
- message.disappearingMessagesInChat;
355
- m = (0, exports.prepareDisappearingMessageSettingContent)(exp);
356
- }
357
- else if ('buttonReply' in message) {
358
- switch (message.type) {
359
- case 'template':
360
- m.templateButtonReplyMessage = {
361
- selectedDisplayText: message.buttonReply.displayText,
362
- selectedId: message.buttonReply.id,
363
- selectedIndex: message.buttonReply.index,
364
- };
365
- break;
366
- case 'plain':
367
- m.buttonsResponseMessage = {
368
- selectedButtonId: message.buttonReply.id,
369
- selectedDisplayText: message.buttonReply.displayText,
370
- type: WAProto_1.proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
371
- };
372
- break;
373
- }
443
+ m.extendedTextMessage = extContent;
444
+ } else if (hasNonNullishProperty(message, "contacts")) {
445
+ const contactLen = message.contacts.contacts.length;
446
+ if (!contactLen) {
447
+ throw new Boom("require atleast 1 contact", { statusCode: 400 });
374
448
  }
375
- else if ('product' in message) {
376
- const { imageMessage } = await (0, exports.prepareWAMessageMedia)({ image: message.product.productImage }, options);
377
- m.productMessage = Types_1.WAProto.Message.ProductMessage.fromObject({
378
- ...message,
379
- product: {
380
- ...message.product,
381
- productImage: imageMessage,
382
- }
383
- });
449
+ if (contactLen === 1) {
450
+ m.contactMessage = WAProto.Message.ContactMessage.create(
451
+ message.contacts.contacts[0],
452
+ );
453
+ } else {
454
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(
455
+ message.contacts,
456
+ );
384
457
  }
385
- else if ('listReply' in message) {
386
- m.listResponseMessage = { ...message.listReply };
458
+ } else if (hasNonNullishProperty(message, "location")) {
459
+ m.locationMessage = WAProto.Message.LocationMessage.create(
460
+ message.location,
461
+ );
462
+ } else if (hasNonNullishProperty(message, "react")) {
463
+ if (!message.react.senderTimestampMs) {
464
+ message.react.senderTimestampMs = Date.now();
387
465
  }
388
- else if ('poll' in message) {
389
- (_b = message.poll).selectableCount || (_b.selectableCount = 0);
390
- if (!Array.isArray(message.poll.values)) {
391
- throw new boom_1.Boom('Invalid poll values', { statusCode: 400 });
392
- }
393
- if (message.poll.selectableCount < 0
394
- || message.poll.selectableCount > message.poll.values.length) {
395
- throw new boom_1.Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, { statusCode: 400 });
466
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
467
+ } else if (hasNonNullishProperty(message, "delete")) {
468
+ m.protocolMessage = {
469
+ key: message.delete,
470
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE,
471
+ };
472
+ } else if (hasNonNullishProperty(message, "forward")) {
473
+ m = generateForwardMessageContent(message.forward, message.force);
474
+ } else if (hasNonNullishProperty(message, "disappearingMessagesInChat")) {
475
+ const exp =
476
+ typeof message.disappearingMessagesInChat === "boolean"
477
+ ? message.disappearingMessagesInChat
478
+ ? WA_DEFAULT_EPHEMERAL
479
+ : 0
480
+ : message.disappearingMessagesInChat;
481
+ m = prepareDisappearingMessageSettingContent(exp);
482
+ } else if (hasNonNullishProperty(message, "groupInvite")) {
483
+ m.groupInviteMessage = {};
484
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
485
+ m.groupInviteMessage.inviteExpiration =
486
+ message.groupInvite.inviteExpiration;
487
+ m.groupInviteMessage.caption = message.groupInvite.text;
488
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
489
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
490
+ //TODO: use built-in interface and get disappearing mode info etc.
491
+ //TODO: cache / use store!?
492
+ if (options.getProfilePicUrl) {
493
+ const pfpUrl = await options.getProfilePicUrl(
494
+ message.groupInvite.jid,
495
+ "preview",
496
+ );
497
+ if (pfpUrl) {
498
+ const resp = await fetch(pfpUrl, {
499
+ method: "GET",
500
+ dispatcher: options?.options?.dispatcher,
501
+ });
502
+ if (resp.ok) {
503
+ const buf = Buffer.from(await resp.arrayBuffer());
504
+ m.groupInviteMessage.jpegThumbnail = buf;
396
505
  }
397
- m.messageContextInfo = {
398
- // encKey
399
- messageSecret: message.poll.messageSecret || (0, crypto_1.randomBytes)(32),
506
+ }
507
+ }
508
+ } else if (hasNonNullishProperty(message, "pin")) {
509
+ m.pinInChatMessage = {};
510
+ m.messageContextInfo = {};
511
+ m.pinInChatMessage.key = message.pin;
512
+ m.pinInChatMessage.type = message.type;
513
+ m.pinInChatMessage.senderTimestampMs = Date.now();
514
+ m.messageContextInfo.messageAddOnDurationInSecs =
515
+ message.type === 1 ? message.time || 86400 : 0;
516
+ } else if (hasNonNullishProperty(message, "buttonReply")) {
517
+ switch (message.type) {
518
+ case "template":
519
+ m.templateButtonReplyMessage = {
520
+ selectedDisplayText: message.buttonReply.displayText,
521
+ selectedId: message.buttonReply.id,
522
+ selectedIndex: message.buttonReply.index,
400
523
  };
401
- m.pollCreationMessage = {
402
- name: message.poll.name,
403
- selectableOptionsCount: message.poll.selectableCount,
404
- options: message.poll.values.map(optionName => ({ optionName })),
524
+ break;
525
+ case "plain":
526
+ m.buttonsResponseMessage = {
527
+ selectedButtonId: message.buttonReply.id,
528
+ selectedDisplayText: message.buttonReply.displayText,
529
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
405
530
  };
531
+ break;
406
532
  }
407
- else if ('sharePhoneNumber' in message) {
408
- m.protocolMessage = {
409
- type: WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
410
- };
533
+ } else if (hasOptionalProperty(message, "ptv") && message.ptv) {
534
+ const { videoMessage } = await prepareWAMessageMedia(
535
+ { video: message.video },
536
+ options,
537
+ );
538
+ m.ptvMessage = videoMessage;
539
+ } else if (hasNonNullishProperty(message, "product")) {
540
+ const { imageMessage } = await prepareWAMessageMedia(
541
+ { image: message.product.productImage },
542
+ options,
543
+ );
544
+ m.productMessage = WAProto.Message.ProductMessage.create({
545
+ ...message,
546
+ product: {
547
+ ...message.product,
548
+ productImage: imageMessage,
549
+ },
550
+ });
551
+ } else if (hasNonNullishProperty(message, "listReply")) {
552
+ m.listResponseMessage = { ...message.listReply };
553
+ } else if (hasNonNullishProperty(message, "event")) {
554
+ m.eventMessage = {};
555
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
556
+ if (message.event.call && options.getCallLink) {
557
+ const token = await options.getCallLink(message.event.call, {
558
+ startTime,
559
+ });
560
+ m.eventMessage.joinLink =
561
+ (message.event.call === "audio"
562
+ ? CALL_AUDIO_PREFIX
563
+ : CALL_VIDEO_PREFIX) + token;
411
564
  }
412
- else if ('requestPhoneNumber' in message) {
413
- m.requestPhoneNumberMessage = {};
565
+ m.messageContextInfo = {
566
+ // encKey
567
+ messageSecret: message.event.messageSecret || randomBytes(32),
568
+ };
569
+ m.eventMessage.name = message.event.name;
570
+ m.eventMessage.description = message.event.description;
571
+ m.eventMessage.startTime = startTime;
572
+ m.eventMessage.endTime = message.event.endDate
573
+ ? message.event.endDate.getTime() / 1000
574
+ : undefined;
575
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
576
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
577
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
578
+ m.eventMessage.location = message.event.location;
579
+ } else if (hasNonNullishProperty(message, "poll")) {
580
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
581
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
582
+ if (!Array.isArray(message.poll.values)) {
583
+ throw new Boom("Invalid poll values", { statusCode: 400 });
414
584
  }
415
- else {
416
- m = await (0, exports.prepareWAMessageMedia)(message, options);
585
+ if (
586
+ message.poll.selectableCount < 0 ||
587
+ message.poll.selectableCount > message.poll.values.length
588
+ ) {
589
+ throw new Boom(
590
+ `poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`,
591
+ {
592
+ statusCode: 400,
593
+ },
594
+ );
417
595
  }
418
- if ('buttons' in message && !!message.buttons) {
419
- const buttonsMessage = {
420
- buttons: message.buttons.map(b => ({ ...b, type: WAProto_1.proto.Message.ButtonsMessage.Button.Type.RESPONSE }))
421
- };
422
- if ('text' in message) {
423
- buttonsMessage.contentText = message.text;
424
- buttonsMessage.headerType = ButtonType.EMPTY;
425
- }
426
- else {
427
- if ('caption' in message) {
428
- buttonsMessage.contentText = message.caption;
429
- }
430
- const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
431
- buttonsMessage.headerType = ButtonType[type];
432
- Object.assign(buttonsMessage, m);
433
- }
434
- if ('footer' in message && !!message.footer) {
435
- buttonsMessage.footerText = message.footer;
436
- }
437
- m = { buttonsMessage };
596
+ m.messageContextInfo = {
597
+ // encKey
598
+ messageSecret: message.poll.messageSecret || randomBytes(32),
599
+ };
600
+ const pollCreationMessage = {
601
+ name: message.poll.name,
602
+ selectableOptionsCount: message.poll.selectableCount,
603
+ options: message.poll.values.map((optionName) => ({ optionName })),
604
+ };
605
+ if (message.poll.toAnnouncementGroup) {
606
+ // poll v2 is for community announcement groups (single select and multiple)
607
+ m.pollCreationMessageV2 = pollCreationMessage;
608
+ } else {
609
+ if (message.poll.selectableCount === 1) {
610
+ //poll v3 is for single select polls
611
+ m.pollCreationMessageV3 = pollCreationMessage;
612
+ } else {
613
+ // poll for multiple choice polls
614
+ m.pollCreationMessage = pollCreationMessage;
615
+ }
438
616
  }
439
- else if ('templateButtons' in message && !!message.templateButtons) {
440
- const msg = {
441
- hydratedButtons: message.templateButtons
442
- };
443
- if ('text' in message) {
444
- msg.hydratedContentText = message.text;
445
- }
446
- else {
447
- if ('caption' in message) {
448
- msg.hydratedContentText = message.caption;
449
- }
450
- Object.assign(msg, m);
451
- }
452
- if ('footer' in message && !!message.footer) {
453
- msg.hydratedFooterText = message.footer;
617
+ } else if (hasNonNullishProperty(message, "sharePhoneNumber")) {
618
+ m.protocolMessage = {
619
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER,
620
+ };
621
+ } else if (hasNonNullishProperty(message, "requestPhoneNumber")) {
622
+ m.requestPhoneNumberMessage = {};
623
+ } else if (hasNonNullishProperty(message, "limitSharing")) {
624
+ m.protocolMessage = {
625
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
626
+ limitSharing: {
627
+ sharingLimited: message.limitSharing === true,
628
+ trigger: 1,
629
+ limitSharingSettingTimestamp: Date.now(),
630
+ initiatedByMe: true,
631
+ },
632
+ };
633
+ } else if (hasNonNullishProperty(message, "stickerPack")) {
634
+ const { zip } = await import("fflate").then((m) => m);
635
+ const { stickers, cover, name, publisher, packId, description } =
636
+ message.stickerPack;
637
+ if (!stickers?.length)
638
+ throw new Boom("Sticker pack must contain at least one sticker", {
639
+ statusCode: 400,
640
+ });
641
+ if (stickers.length > 60)
642
+ throw new Boom("Sticker pack exceeds the maximum limit of 60 stickers", {
643
+ statusCode: 400,
644
+ });
645
+ const stickerPackId = packId || generateMessageIDV2();
646
+ const [_sharp] = await Promise.all([import("sharp").catch(() => null)]);
647
+ if (!_sharp)
648
+ throw new Boom("sharp is required for sticker pack generation");
649
+ const sharpLib = _sharp.default || _sharp;
650
+ const isWebP = (buf) =>
651
+ buf.length >= 12 &&
652
+ buf[0] === 0x52 &&
653
+ buf[1] === 0x49 &&
654
+ buf[2] === 0x46 &&
655
+ buf[3] === 0x46 &&
656
+ buf[8] === 0x57 &&
657
+ buf[9] === 0x45 &&
658
+ buf[10] === 0x42 &&
659
+ buf[11] === 0x50;
660
+ const isAnimatedWebP = (buf) => {
661
+ if (!isWebP(buf)) return false;
662
+ let o = 12;
663
+ while (o < buf.length - 8) {
664
+ const tag = buf.toString("ascii", o, o + 4);
665
+ const sz = buf.readUInt32LE(o + 4);
666
+ if (tag === "VP8X" && buf[o + 8] & 0x02) return true;
667
+ if (tag === "ANIM" || tag === "ANMF") return true;
668
+ o += 8 + sz + (sz % 2);
669
+ }
670
+ return false;
671
+ };
672
+ const { Readable } = await import("stream");
673
+ const toReadable = (buf) => {
674
+ const r = new Readable({ read: () => {} });
675
+ r.push(buf);
676
+ r.push(null);
677
+ return r;
678
+ };
679
+ const toBuffer = async (stream) => {
680
+ const c = [];
681
+ for await (const ch of stream) c.push(ch);
682
+ return Buffer.concat(c);
683
+ };
684
+ const getStreamBuf = async (item) => {
685
+ if (Buffer.isBuffer(item)) return item;
686
+ if (item?.stream) return toBuffer(item.stream);
687
+ const u = item?.url?.toString?.() || item?.url;
688
+ if (u?.startsWith("data:")) return Buffer.from(u.split(",")[1], "base64");
689
+ const resp = await fetch(u);
690
+ return Buffer.from(await resp.arrayBuffer());
691
+ };
692
+ const zipData = {};
693
+ const stickerMeta = await Promise.all(
694
+ stickers.map(async (s, i) => {
695
+ const raw = await getStreamBuf(s.data || s.sticker);
696
+ let webp;
697
+ let animated = false;
698
+ if (isWebP(raw)) {
699
+ webp = raw;
700
+ animated = isAnimatedWebP(raw);
701
+ } else {
702
+ webp = await sharpLib(raw).webp().toBuffer();
454
703
  }
455
- m = {
456
- templateMessage: {
457
- fourRowTemplate: msg,
458
- hydratedTemplate: msg
459
- }
704
+ if (webp.length > 1024 * 1024)
705
+ throw new Boom(`Sticker ${i} exceeds 1MB`);
706
+ const hash = sha256(webp).toString("base64").replace(/\//g, "-");
707
+ const fname = `${hash}.webp`;
708
+ zipData[fname] = [new Uint8Array(webp), { level: 0 }];
709
+ return {
710
+ fileName: fname,
711
+ mimetype: "image/webp",
712
+ isAnimated: animated,
713
+ emojis: s.emojis || [],
714
+ accessibilityLabel: s.accessibilityLabel || "",
460
715
  };
716
+ }),
717
+ );
718
+ const coverRaw = await getStreamBuf(cover);
719
+ const coverWebp = isWebP(coverRaw)
720
+ ? coverRaw
721
+ : await sharpLib(coverRaw).webp().toBuffer();
722
+ const trayIconFileName = `${stickerPackId}.webp`;
723
+ zipData[trayIconFileName] = [new Uint8Array(coverWebp), { level: 0 }];
724
+ const zipBuffer = await new Promise((res, rej) =>
725
+ zip(zipData, (e, d) => (e ? rej(e) : res(Buffer.from(d)))),
726
+ );
727
+ const stickerPackUpload = await encryptedStream(zipBuffer, "sticker-pack", {
728
+ logger: options.logger,
729
+ opts: options.options,
730
+ });
731
+ const stickerPackResult = await options.upload(
732
+ stickerPackUpload.encWriteStream,
733
+ {
734
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString("base64"),
735
+ mediaType: "sticker-pack",
736
+ timeoutMs: options.mediaUploadTimeoutMs,
737
+ },
738
+ );
739
+ m.stickerPackMessage = {
740
+ name,
741
+ publisher,
742
+ stickerPackId,
743
+ packDescription: description,
744
+ stickerPackOrigin:
745
+ WAProto.Message.StickerPackMessage.StickerPackOrigin.THIRD_PARTY,
746
+ stickerPackSize: zipBuffer.length,
747
+ stickers: stickerMeta,
748
+ fileSha256: stickerPackUpload.fileSha256,
749
+ fileEncSha256: stickerPackUpload.fileEncSha256,
750
+ mediaKey: stickerPackUpload.mediaKey,
751
+ directPath: stickerPackResult.directPath,
752
+ fileLength: stickerPackUpload.fileLength,
753
+ mediaKeyTimestamp: unixTimestampSeconds(),
754
+ trayIconFileName,
755
+ };
756
+ try {
757
+ const thumbBuf = await sharpLib(coverRaw)
758
+ .resize(252, 252)
759
+ .jpeg()
760
+ .toBuffer();
761
+ const thumbUpload = await encryptedStream(
762
+ thumbBuf,
763
+ "thumbnail-sticker-pack",
764
+ {
765
+ logger: options.logger,
766
+ opts: options.options,
767
+ mediaKey: stickerPackUpload.mediaKey,
768
+ },
769
+ );
770
+ const thumbResult = await options.upload(thumbUpload.encWriteStream, {
771
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString("base64"),
772
+ mediaType: "thumbnail-sticker-pack",
773
+ timeoutMs: options.mediaUploadTimeoutMs,
774
+ });
775
+ Object.assign(m.stickerPackMessage, {
776
+ thumbnailDirectPath: thumbResult.directPath,
777
+ thumbnailSha256: thumbUpload.fileSha256,
778
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
779
+ thumbnailHeight: 252,
780
+ thumbnailWidth: 252,
781
+ imageDataHash: sha256(thumbBuf).toString("base64"),
782
+ });
783
+ } catch (e) {
784
+ options.logger?.warn?.(`Sticker pack thumbnail failed: ${e?.message}`);
461
785
  }
462
- if ('sections' in message && !!message.sections) {
463
- const listMessage = {
464
- sections: message.sections,
465
- buttonText: message.buttonText,
466
- title: message.title,
467
- footerText: message.footer,
468
- description: message.text,
469
- listType: WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT
470
- };
471
- m = { listMessage };
472
- }
473
- if ('viewOnce' in message && !!message.viewOnce) {
474
- m = { viewOnceMessage: { message: m } };
475
- }
476
- if ('mentions' in message && ((_a = message.mentions) === null || _a === void 0 ? void 0 : _a.length)) {
477
- const [messageType] = Object.keys(m);
478
- m[messageType].contextInfo = m[messageType] || {};
479
- m[messageType].contextInfo.mentionedJid = message.mentions;
480
- }
481
- if ('edit' in message) {
482
- m = {
483
- protocolMessage: {
484
- key: message.edit,
485
- editedMessage: m,
486
- timestampMs: Date.now(),
487
- type: Types_1.WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
488
- }
489
- };
786
+ m.stickerPackMessage.contextInfo = {
787
+ ...(message.contextInfo || {}),
788
+ ...(message.mentions ? { mentionedJid: message.mentions } : {}),
789
+ };
790
+ } else {
791
+ m = await prepareWAMessageMedia(message, options);
792
+ }
793
+ if (hasOptionalProperty(message, "viewOnce") && !!message.viewOnce) {
794
+ m = { viewOnceMessage: { message: m } };
795
+ }
796
+ if (
797
+ (hasOptionalProperty(message, "mentions") && message.mentions?.length) ||
798
+ (hasOptionalProperty(message, "mentionAll") && message.mentionAll)
799
+ ) {
800
+ const messageType = Object.keys(m)[0];
801
+ const key = m[messageType];
802
+ if (key && "contextInfo" in key) {
803
+ key.contextInfo = key.contextInfo || {};
804
+ if (message.mentions?.length) {
805
+ key.contextInfo.mentionedJid = message.mentions;
806
+ }
807
+ if (message.mentionAll) {
808
+ key.contextInfo.nonJidMentions = 1;
809
+ }
810
+ } else if (key) {
811
+ key.contextInfo = {
812
+ mentionedJid: message.mentions,
813
+ nonJidMentions: message.mentionAll ? 1 : 0,
814
+ };
815
+ }
816
+ }
817
+ if (hasOptionalProperty(message, "edit")) {
818
+ m = {
819
+ protocolMessage: {
820
+ key: message.edit,
821
+ editedMessage: m,
822
+ timestampMs: Date.now(),
823
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
824
+ },
825
+ };
826
+ }
827
+ if (hasOptionalProperty(message, "contextInfo") && !!message.contextInfo) {
828
+ const messageType = Object.keys(m)[0];
829
+ const key = m[messageType];
830
+ if ("contextInfo" in key && !!key.contextInfo) {
831
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
832
+ } else if (key) {
833
+ key.contextInfo = message.contextInfo;
490
834
  }
491
- if ('contextInfo' in message && !!message.contextInfo) {
492
- const [messageType] = Object.keys(m);
493
- m[messageType] = m[messageType] || {};
494
- m[messageType].contextInfo = message.contextInfo;
835
+ }
836
+ if (shouldIncludeReportingToken(m)) {
837
+ m.messageContextInfo = m.messageContextInfo || {};
838
+ if (!m.messageContextInfo.messageSecret) {
839
+ m.messageContextInfo.messageSecret = randomBytes(32);
495
840
  }
496
- return Types_1.WAProto.Message.fromObject(m);
841
+ }
842
+ return WAProto.Message.create(m);
497
843
  };
498
- exports.generateWAMessageContent = generateWAMessageContent;
499
- const generateWAMessageFromContent = (jid, message, options) => {
500
- // set timestamp to now
501
- // if not specified
502
- if (!options.timestamp) {
503
- options.timestamp = new Date();
504
- }
505
- const innerMessage = (0, exports.normalizeMessageContent)(message);
506
- const key = (0, exports.getContentType)(innerMessage);
507
- const timestamp = (0, generics_1.unixTimestampSeconds)(options.timestamp);
508
- const { quoted, userJid } = options;
509
- if (quoted && !(0, WABinary_1.isJidNewsLetter)(jid)) {
510
- const participant = quoted.key.fromMe ? userJid : (quoted.participant || quoted.key.participant || quoted.key.remoteJid);
511
- let quotedMsg = (0, exports.normalizeMessageContent)(quoted.message);
512
- const msgType = (0, exports.getContentType)(quotedMsg);
513
- // strip any redundant properties
514
- quotedMsg = WAProto_1.proto.Message.fromObject({ [msgType]: quotedMsg[msgType] });
515
- const quotedContent = quotedMsg[msgType];
516
- if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
517
- delete quotedContent.contextInfo;
518
- }
519
- const contextInfo = innerMessage[key].contextInfo || {};
520
- contextInfo.participant = (0, WABinary_1.jidNormalizedUser)(participant);
521
- contextInfo.stanzaId = quoted.key.id;
522
- contextInfo.quotedMessage = quotedMsg;
523
- // if a participant is quoted, then it must be a group
524
- // hence, remoteJid of group must also be entered
525
- if (jid !== quoted.key.remoteJid) {
526
- contextInfo.remoteJid = quoted.key.remoteJid;
527
- }
528
- innerMessage[key].contextInfo = contextInfo;
529
- }
844
+ export const generateWAMessageFromContent = (jid, message, options) => {
845
+ // set timestamp to now
846
+ // if not specified
847
+ if (!options.timestamp) {
848
+ options.timestamp = new Date();
849
+ }
850
+ const innerMessage = normalizeMessageContent(message);
851
+ const key = getContentType(innerMessage);
852
+ const timestamp = unixTimestampSeconds(options.timestamp);
853
+ const { quoted, userJid } = options;
854
+ if (quoted && !isJidNewsletter(jid)) {
855
+ const participant = quoted.key.fromMe
856
+ ? userJid // TODO: Add support for LIDs
857
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
858
+ let quotedMsg = normalizeMessageContent(quoted.message);
859
+ const msgType = getContentType(quotedMsg);
860
+ // strip any redundant properties
861
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
862
+ const quotedContent = quotedMsg[msgType];
530
863
  if (
531
- // if we want to send a disappearing message
532
- !!(options === null || options === void 0 ? void 0 : options.ephemeralExpiration) &&
533
- // and it's not a protocol message -- delete, toggle disappear message
534
- key !== 'protocolMessage' &&
535
- // already not converted to disappearing message
536
- key !== 'ephemeralMessage' &&
537
- // newsletter not accept disappearing messages
538
- !(0, WABinary_1.isJidNewsLetter)(jid)) {
539
- innerMessage[key].contextInfo = {
540
- ...(innerMessage[key].contextInfo || {}),
541
- expiration: options.ephemeralExpiration || Defaults_1.WA_DEFAULT_EPHEMERAL,
542
- //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
543
- };
864
+ typeof quotedContent === "object" &&
865
+ quotedContent &&
866
+ "contextInfo" in quotedContent
867
+ ) {
868
+ delete quotedContent.contextInfo;
544
869
  }
545
- message = Types_1.WAProto.Message.fromObject(message);
546
- const messageJSON = {
547
- key: {
548
- remoteJid: jid,
549
- fromMe: true,
550
- id: (options === null || options === void 0 ? void 0 : options.messageId) || (0, generics_1.generateMessageID)(),
551
- },
552
- message: message,
553
- messageTimestamp: timestamp,
554
- messageStubParameters: [],
555
- participant: (0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidStatusBroadcast)(jid) ? userJid : undefined,
556
- status: Types_1.WAMessageStatus.PENDING
870
+ const contextInfo =
871
+ ("contextInfo" in innerMessage[key] && innerMessage[key]?.contextInfo) ||
872
+ {};
873
+ contextInfo.participant = jidNormalizedUser(participant);
874
+ contextInfo.stanzaId = quoted.key.id;
875
+ contextInfo.quotedMessage = quotedMsg;
876
+ // if a participant is quoted, then it must be a group
877
+ // hence, remoteJid of group must also be entered
878
+ if (jid !== quoted.key.remoteJid) {
879
+ contextInfo.remoteJid = quoted.key.remoteJid;
880
+ }
881
+ if (contextInfo && innerMessage[key]) {
882
+ /* @ts-ignore */
883
+ innerMessage[key].contextInfo = contextInfo;
884
+ }
885
+ }
886
+ if (
887
+ // if we want to send a disappearing message
888
+ !!options?.ephemeralExpiration &&
889
+ // and it's not a protocol message -- delete, toggle disappear message
890
+ key !== "protocolMessage" &&
891
+ // already not converted to disappearing message
892
+ key !== "ephemeralMessage" &&
893
+ // newsletters don't support ephemeral messages
894
+ !isJidNewsletter(jid)
895
+ ) {
896
+ /* @ts-ignore */
897
+ innerMessage[key].contextInfo = {
898
+ ...(innerMessage[key].contextInfo || {}),
899
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL,
900
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
557
901
  };
558
- return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
902
+ }
903
+ message = WAProto.Message.create(message);
904
+ const messageJSON = {
905
+ key: {
906
+ remoteJid: jid,
907
+ fromMe: true,
908
+ id: options?.messageId || generateMessageIDV2(),
909
+ },
910
+ message: message,
911
+ messageTimestamp: timestamp,
912
+ messageStubParameters: [],
913
+ participant:
914
+ isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
915
+ status: WAMessageStatus.PENDING,
916
+ };
917
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
559
918
  };
560
- exports.generateWAMessageFromContent = generateWAMessageFromContent;
561
- const generateWAMessage = async (jid, content, options) => {
562
- var _a;
563
- // ensure msg ID is with every log
564
- options.logger = (_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.child({ msgId: options.messageId });
565
- return (0, exports.generateWAMessageFromContent)(jid, await (0, exports.generateWAMessageContent)(content, { newsletter: (0, WABinary_1.isJidNewsLetter)(jid), ...options }), options);
919
+ export const generateWAMessage = async (jid, content, options) => {
920
+ // ensure msg ID is with every log
921
+ options.logger = options?.logger?.child({ msgId: options.messageId });
922
+ // Pass jid in the options to generateWAMessageContent
923
+ return generateWAMessageFromContent(
924
+ jid,
925
+ await generateWAMessageContent(content, { ...options, jid }),
926
+ options,
927
+ );
566
928
  };
567
- exports.generateWAMessage = generateWAMessage;
568
929
  /** Get the key to access the true type of content */
569
- const getContentType = (content) => {
570
- if (content) {
571
- const keys = Object.keys(content);
572
- const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
573
- return key;
574
- }
930
+ export const getContentType = (content) => {
931
+ if (content) {
932
+ const keys = Object.keys(content);
933
+ const key = keys.find(
934
+ (k) =>
935
+ (k === "conversation" || k.includes("Message")) &&
936
+ k !== "senderKeyDistributionMessage",
937
+ );
938
+ return key;
939
+ }
575
940
  };
576
- exports.getContentType = getContentType;
577
941
  /**
578
942
  * Normalizes ephemeral, view once messages to regular message content
579
943
  * Eg. image messages in ephemeral messages, in view once messages etc.
580
944
  * @param content
581
945
  * @returns
582
946
  */
583
- const normalizeMessageContent = (content) => {
584
- if (!content) {
585
- return undefined;
586
- }
587
- // set max iterations to prevent an infinite loop
588
- for (let i = 0; i < 5; i++) {
589
- const inner = getFutureProofMessage(content);
590
- if (!inner) {
591
- break;
592
- }
593
- content = inner.message;
594
- }
595
- return content;
596
- function getFutureProofMessage(message) {
597
- return ((message === null || message === void 0 ? void 0 : message.ephemeralMessage)
598
- || (message === null || message === void 0 ? void 0 : message.viewOnceMessage)
599
- || (message === null || message === void 0 ? void 0 : message.documentWithCaptionMessage)
600
- || (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2)
601
- || (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension)
602
- || (message === null || message === void 0 ? void 0 : message.editedMessage));
947
+ export const normalizeMessageContent = (content) => {
948
+ if (!content) {
949
+ return undefined;
950
+ }
951
+ // set max iterations to prevent an infinite loop
952
+ for (let i = 0; i < 5; i++) {
953
+ const inner = getFutureProofMessage(content);
954
+ if (!inner) {
955
+ break;
603
956
  }
957
+ content = inner.message;
958
+ }
959
+ return content;
960
+ function getFutureProofMessage(message) {
961
+ return (
962
+ message?.ephemeralMessage ||
963
+ message?.viewOnceMessage ||
964
+ message?.documentWithCaptionMessage ||
965
+ message?.viewOnceMessageV2 ||
966
+ message?.viewOnceMessageV2Extension ||
967
+ message?.editedMessage ||
968
+ message?.associatedChildMessage ||
969
+ message?.groupStatusMessage ||
970
+ message?.groupStatusMessageV2
971
+ );
972
+ }
604
973
  };
605
- exports.normalizeMessageContent = normalizeMessageContent;
606
974
  /**
607
975
  * Extract the true message content from a message
608
976
  * Eg. extracts the inner message from a disappearing message/view once message
609
977
  */
610
- const extractMessageContent = (content) => {
611
- var _a, _b, _c, _d, _e, _f;
612
- const extractFromTemplateMessage = (msg) => {
613
- if (msg.imageMessage) {
614
- return { imageMessage: msg.imageMessage };
615
- }
616
- else if (msg.documentMessage) {
617
- return { documentMessage: msg.documentMessage };
618
- }
619
- else if (msg.videoMessage) {
620
- return { videoMessage: msg.videoMessage };
621
- }
622
- else if (msg.locationMessage) {
623
- return { locationMessage: msg.locationMessage };
624
- }
625
- else {
626
- return {
627
- conversation: 'contentText' in msg
628
- ? msg.contentText
629
- : ('hydratedContentText' in msg ? msg.hydratedContentText : '')
630
- };
631
- }
632
- };
633
- content = (0, exports.normalizeMessageContent)(content);
634
- if (content === null || content === void 0 ? void 0 : content.buttonsMessage) {
635
- return extractFromTemplateMessage(content.buttonsMessage);
636
- }
637
- if ((_a = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _a === void 0 ? void 0 : _a.hydratedFourRowTemplate) {
638
- return extractFromTemplateMessage((_b = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _b === void 0 ? void 0 : _b.hydratedFourRowTemplate);
978
+ export const extractMessageContent = (content) => {
979
+ const extractFromTemplateMessage = (msg) => {
980
+ if (msg.imageMessage) {
981
+ return { imageMessage: msg.imageMessage };
982
+ } else if (msg.documentMessage) {
983
+ return { documentMessage: msg.documentMessage };
984
+ } else if (msg.videoMessage) {
985
+ return { videoMessage: msg.videoMessage };
986
+ } else if (msg.locationMessage) {
987
+ return { locationMessage: msg.locationMessage };
988
+ } else {
989
+ return {
990
+ conversation:
991
+ "contentText" in msg
992
+ ? msg.contentText
993
+ : "hydratedContentText" in msg
994
+ ? msg.hydratedContentText
995
+ : "",
996
+ };
639
997
  }
640
- if ((_c = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _c === void 0 ? void 0 : _c.hydratedTemplate) {
641
- return extractFromTemplateMessage((_d = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _d === void 0 ? void 0 : _d.hydratedTemplate);
642
- }
643
- if ((_e = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _e === void 0 ? void 0 : _e.fourRowTemplate) {
644
- return extractFromTemplateMessage((_f = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _f === void 0 ? void 0 : _f.fourRowTemplate);
645
- }
646
- return content;
998
+ };
999
+ content = normalizeMessageContent(content);
1000
+ if (content?.buttonsMessage) {
1001
+ return extractFromTemplateMessage(content.buttonsMessage);
1002
+ }
1003
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1004
+ return extractFromTemplateMessage(
1005
+ content?.templateMessage?.hydratedFourRowTemplate,
1006
+ );
1007
+ }
1008
+ if (content?.templateMessage?.hydratedTemplate) {
1009
+ return extractFromTemplateMessage(
1010
+ content?.templateMessage?.hydratedTemplate,
1011
+ );
1012
+ }
1013
+ if (content?.templateMessage?.fourRowTemplate) {
1014
+ return extractFromTemplateMessage(
1015
+ content?.templateMessage?.fourRowTemplate,
1016
+ );
1017
+ }
1018
+ return content;
647
1019
  };
648
- exports.extractMessageContent = extractMessageContent;
649
1020
  /**
650
1021
  * Returns the device predicted by message ID
651
1022
  */
652
- const getDevice = (id) => /^3A.{18}$/.test(id) ? 'ios' : /^3E.{20}$/.test(id) ? 'web' : /^(.{21}|.{32})$/.test(id) ? 'android' : /^.{18}$/.test(id) ? 'desktop' : 'unknown';
653
- exports.getDevice = getDevice;
1023
+ export const getDevice = (id) =>
1024
+ /^3A.{18}$/.test(id)
1025
+ ? "ios"
1026
+ : /^3E.{20}$/.test(id)
1027
+ ? "web"
1028
+ : /^(.{21}|.{32})$/.test(id)
1029
+ ? "android"
1030
+ : /^(3F|.{18}$)/.test(id)
1031
+ ? "desktop"
1032
+ : "unknown";
654
1033
  /** Upserts a receipt in the message */
655
- const updateMessageWithReceipt = (msg, receipt) => {
656
- msg.userReceipt = msg.userReceipt || [];
657
- const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
658
- if (recp) {
659
- Object.assign(recp, receipt);
660
- }
661
- else {
662
- msg.userReceipt.push(receipt);
663
- }
1034
+ export const updateMessageWithReceipt = (msg, receipt) => {
1035
+ msg.userReceipt = msg.userReceipt || [];
1036
+ const recp = msg.userReceipt.find((m) => m.userJid === receipt.userJid);
1037
+ if (recp) {
1038
+ Object.assign(recp, receipt);
1039
+ } else {
1040
+ msg.userReceipt.push(receipt);
1041
+ }
664
1042
  };
665
- exports.updateMessageWithReceipt = updateMessageWithReceipt;
666
1043
  /** Update the message with a new reaction */
667
- const updateMessageWithReaction = (msg, reaction) => {
668
- const authorID = (0, generics_1.getKeyAuthor)(reaction.key);
669
- const reactions = (msg.reactions || [])
670
- .filter(r => (0, generics_1.getKeyAuthor)(r.key) !== authorID);
671
- if (reaction.text) {
672
- reactions.push(reaction);
673
- }
674
- msg.reactions = reactions;
1044
+ export const updateMessageWithReaction = (msg, reaction) => {
1045
+ const authorID = getKeyAuthor(reaction.key);
1046
+ const reactions = (msg.reactions || []).filter(
1047
+ (r) => getKeyAuthor(r.key) !== authorID,
1048
+ );
1049
+ reaction.text = reaction.text || "";
1050
+ reactions.push(reaction);
1051
+ msg.reactions = reactions;
675
1052
  };
676
- exports.updateMessageWithReaction = updateMessageWithReaction;
677
1053
  /** Update the message with a new poll update */
678
- const updateMessageWithPollUpdate = (msg, update) => {
679
- var _a, _b;
680
- const authorID = (0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey);
681
- const reactions = (msg.pollUpdates || [])
682
- .filter(r => (0, generics_1.getKeyAuthor)(r.pollUpdateMessageKey) !== authorID);
683
- if ((_b = (_a = update.vote) === null || _a === void 0 ? void 0 : _a.selectedOptions) === null || _b === void 0 ? void 0 : _b.length) {
684
- reactions.push(update);
685
- }
686
- msg.pollUpdates = reactions;
1054
+ export const updateMessageWithPollUpdate = (msg, update) => {
1055
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1056
+ const reactions = (msg.pollUpdates || []).filter(
1057
+ (r) => getKeyAuthor(r.pollUpdateMessageKey) !== authorID,
1058
+ );
1059
+ if (update.vote?.selectedOptions?.length) {
1060
+ reactions.push(update);
1061
+ }
1062
+ msg.pollUpdates = reactions;
1063
+ };
1064
+ /** Update the message with a new event response */
1065
+ export const updateMessageWithEventResponse = (msg, update) => {
1066
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1067
+ const responses = (msg.eventResponses || []).filter(
1068
+ (r) => getKeyAuthor(r.eventResponseMessageKey) !== authorID,
1069
+ );
1070
+ responses.push(update);
1071
+ msg.eventResponses = responses;
687
1072
  };
688
- exports.updateMessageWithPollUpdate = updateMessageWithPollUpdate;
689
1073
  /**
690
1074
  * Aggregates all poll updates in a poll.
691
1075
  * @param msg the poll creation message
692
1076
  * @param meId your jid
693
1077
  * @returns A list of options & their voters
694
1078
  */
695
- function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
696
- var _a, _b, _c;
697
- const opts = ((_a = message === null || message === void 0 ? void 0 : message.pollCreationMessage) === null || _a === void 0 ? void 0 : _a.options) || ((_b = message === null || message === void 0 ? void 0 : message.pollCreationMessageV2) === null || _b === void 0 ? void 0 : _b.options) || ((_c = message === null || message === void 0 ? void 0 : message.pollCreationMessageV3) === null || _c === void 0 ? void 0 : _c.options) || [];
698
- const voteHashMap = opts.reduce((acc, opt) => {
699
- const hash = (0, crypto_2.sha256)(Buffer.from(opt.optionName || '')).toString();
700
- acc[hash] = {
701
- name: opt.optionName || '',
702
- voters: []
1079
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1080
+ const opts =
1081
+ message?.pollCreationMessage?.options ||
1082
+ message?.pollCreationMessageV2?.options ||
1083
+ message?.pollCreationMessageV3?.options ||
1084
+ [];
1085
+ const voteHashMap = opts.reduce((acc, opt) => {
1086
+ const hash = sha256(Buffer.from(opt.optionName || "")).toString();
1087
+ acc[hash] = {
1088
+ name: opt.optionName || "",
1089
+ voters: [],
1090
+ };
1091
+ return acc;
1092
+ }, {});
1093
+ for (const update of pollUpdates || []) {
1094
+ const { vote } = update;
1095
+ if (!vote) {
1096
+ continue;
1097
+ }
1098
+ for (const option of vote.selectedOptions || []) {
1099
+ const hash = option.toString();
1100
+ let data = voteHashMap[hash];
1101
+ if (!data) {
1102
+ voteHashMap[hash] = {
1103
+ name: "Unknown",
1104
+ voters: [],
703
1105
  };
704
- return acc;
705
- }, {});
706
- for (const update of pollUpdates || []) {
707
- const { vote } = update;
708
- if (!vote) {
709
- continue;
710
- }
711
- for (const option of vote.selectedOptions || []) {
712
- const hash = option.toString();
713
- let data = voteHashMap[hash];
714
- if (!data) {
715
- voteHashMap[hash] = {
716
- name: 'Unknown',
717
- voters: []
718
- };
719
- data = voteHashMap[hash];
720
- }
721
- voteHashMap[hash].voters.push((0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey, meId));
722
- }
1106
+ data = voteHashMap[hash];
1107
+ }
1108
+ voteHashMap[hash].voters.push(
1109
+ getKeyAuthor(update.pollUpdateMessageKey, meId),
1110
+ );
1111
+ }
1112
+ }
1113
+ return Object.values(voteHashMap);
1114
+ }
1115
+ /**
1116
+ * Aggregates all event responses in an event message.
1117
+ * @param msg the event creation message
1118
+ * @param meId your jid
1119
+ * @returns A list of response types & their responders
1120
+ */
1121
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1122
+ const responseTypes = ["GOING", "NOT_GOING", "MAYBE"];
1123
+ const responseMap = {};
1124
+ for (const type of responseTypes) {
1125
+ responseMap[type] = {
1126
+ response: type,
1127
+ responders: [],
1128
+ };
1129
+ }
1130
+ for (const update of eventResponses || []) {
1131
+ const responseType = update.eventResponse || "UNKNOWN";
1132
+ if (responseType !== "UNKNOWN" && responseMap[responseType]) {
1133
+ responseMap[responseType].responders.push(
1134
+ getKeyAuthor(update.eventResponseMessageKey, meId),
1135
+ );
723
1136
  }
724
- return Object.values(voteHashMap);
1137
+ }
1138
+ return Object.values(responseMap);
725
1139
  }
726
- exports.getAggregateVotesInPollMessage = getAggregateVotesInPollMessage;
727
1140
  /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
728
- const aggregateMessageKeysNotFromMe = (keys) => {
729
- const keyMap = {};
730
- for (const { remoteJid, id, participant, fromMe } of keys) {
731
- if (!fromMe) {
732
- const uqKey = `${remoteJid}:${participant || ''}`;
733
- if (!keyMap[uqKey]) {
734
- keyMap[uqKey] = {
735
- jid: remoteJid,
736
- participant: participant,
737
- messageIds: []
738
- };
739
- }
740
- keyMap[uqKey].messageIds.push(id);
741
- }
1141
+ export const aggregateMessageKeysNotFromMe = (keys) => {
1142
+ const keyMap = {};
1143
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1144
+ if (!fromMe) {
1145
+ const uqKey = `${remoteJid}:${participant || ""}`;
1146
+ if (!keyMap[uqKey]) {
1147
+ keyMap[uqKey] = {
1148
+ jid: remoteJid,
1149
+ participant: participant,
1150
+ messageIds: [],
1151
+ };
1152
+ }
1153
+ keyMap[uqKey].messageIds.push(id);
742
1154
  }
743
- return Object.values(keyMap);
1155
+ }
1156
+ return Object.values(keyMap);
744
1157
  };
745
- exports.aggregateMessageKeysNotFromMe = aggregateMessageKeysNotFromMe;
746
1158
  const REUPLOAD_REQUIRED_STATUS = [410, 404];
747
1159
  /**
748
1160
  * Downloads the given message. Throws an error if it's not a media message
749
1161
  */
750
- const downloadMediaMessage = async (message, type, options, ctx) => {
751
- const result = await downloadMsg()
752
- .catch(async (error) => {
753
- var _a;
754
- if (ctx) {
755
- if (axios_1.default.isAxiosError(error)) {
756
- // check if the message requires a reupload
757
- if (REUPLOAD_REQUIRED_STATUS.includes((_a = error.response) === null || _a === void 0 ? void 0 : _a.status)) {
758
- ctx.logger.info({ key: message.key }, 'sending reupload media request...');
759
- // request reupload
760
- message = await ctx.reuploadRequest(message);
761
- const result = await downloadMsg();
762
- return result;
763
- }
764
- }
765
- }
766
- throw error;
767
- });
768
- return result;
769
- async function downloadMsg() {
770
- const mContent = (0, exports.extractMessageContent)(message.message);
771
- if (!mContent) {
772
- throw new boom_1.Boom('No message present', { statusCode: 400, data: message });
773
- }
774
- const contentType = (0, exports.getContentType)(mContent);
775
- let mediaType = contentType === null || contentType === void 0 ? void 0 : contentType.replace('Message', '');
776
- const media = mContent[contentType];
777
- if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
778
- throw new boom_1.Boom(`"${contentType}" message is not a media message`);
779
- }
780
- let download;
781
- if ('thumbnailDirectPath' in media && !('url' in media)) {
782
- download = {
783
- directPath: media.thumbnailDirectPath,
784
- mediaKey: media.mediaKey
785
- };
786
- mediaType = 'thumbnail-link';
787
- }
788
- else {
789
- download = media;
790
- }
791
- const stream = await (0, messages_media_1.downloadContentFromMessage)(download, mediaType, options);
792
- if (type === 'buffer') {
793
- const bufferArray = [];
794
- for await (const chunk of stream) {
795
- bufferArray.push(chunk);
796
- }
797
- return Buffer.concat(bufferArray);
798
- }
799
- return stream;
1162
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
1163
+ const result = await downloadMsg().catch(async (error) => {
1164
+ if (
1165
+ ctx &&
1166
+ typeof error?.status === "number" && // treat errors with status as HTTP failures requiring reupload
1167
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)
1168
+ ) {
1169
+ ctx.logger.info(
1170
+ { key: message.key },
1171
+ "sending reupload media request...",
1172
+ );
1173
+ // request reupload
1174
+ message = await ctx.reuploadRequest(message);
1175
+ const result = await downloadMsg();
1176
+ return result;
1177
+ }
1178
+ throw error;
1179
+ });
1180
+ return result;
1181
+ async function downloadMsg() {
1182
+ const mContent = extractMessageContent(message.message);
1183
+ if (!mContent) {
1184
+ throw new Boom("No message present", { statusCode: 400, data: message });
1185
+ }
1186
+ const contentType = getContentType(mContent);
1187
+ let mediaType = contentType?.replace("Message", "");
1188
+ const media = mContent[contentType];
1189
+ if (
1190
+ !media ||
1191
+ typeof media !== "object" ||
1192
+ (!("url" in media) && !("thumbnailDirectPath" in media))
1193
+ ) {
1194
+ throw new Boom(`"${contentType}" message is not a media message`);
800
1195
  }
1196
+ let download;
1197
+ if ("thumbnailDirectPath" in media && !("url" in media)) {
1198
+ download = {
1199
+ directPath: media.thumbnailDirectPath,
1200
+ mediaKey: media.mediaKey,
1201
+ };
1202
+ mediaType = "thumbnail-link";
1203
+ } else {
1204
+ download = media;
1205
+ }
1206
+ const stream = await downloadContentFromMessage(
1207
+ download,
1208
+ mediaType,
1209
+ options,
1210
+ );
1211
+ if (type === "buffer") {
1212
+ const bufferArray = [];
1213
+ for await (const chunk of stream) {
1214
+ bufferArray.push(chunk);
1215
+ }
1216
+ return Buffer.concat(bufferArray);
1217
+ }
1218
+ return stream;
1219
+ }
801
1220
  };
802
- exports.downloadMediaMessage = downloadMediaMessage;
803
1221
  /** Checks whether the given message is a media message; if it is returns the inner content */
804
- const assertMediaContent = (content) => {
805
- content = (0, exports.extractMessageContent)(content);
806
- const mediaContent = (content === null || content === void 0 ? void 0 : content.documentMessage)
807
- || (content === null || content === void 0 ? void 0 : content.imageMessage)
808
- || (content === null || content === void 0 ? void 0 : content.videoMessage)
809
- || (content === null || content === void 0 ? void 0 : content.audioMessage)
810
- || (content === null || content === void 0 ? void 0 : content.stickerMessage);
811
- if (!mediaContent) {
812
- throw new boom_1.Boom('given message is not a media message', { statusCode: 400, data: content });
813
- }
814
- return mediaContent;
1222
+ export const assertMediaContent = (content) => {
1223
+ content = extractMessageContent(content);
1224
+ const mediaContent =
1225
+ content?.documentMessage ||
1226
+ content?.imageMessage ||
1227
+ content?.videoMessage ||
1228
+ content?.audioMessage ||
1229
+ content?.stickerMessage;
1230
+ if (!mediaContent) {
1231
+ throw new Boom("given message is not a media message", {
1232
+ statusCode: 400,
1233
+ data: content,
1234
+ });
1235
+ }
1236
+ return mediaContent;
815
1237
  };
816
- exports.assertMediaContent = assertMediaContent;
1238
+ //# sourceMappingURL=messages.js.map