surabails 1.5.0

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 (369) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +394 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +29 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97650 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +62 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +115 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +82 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +26 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +342 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +171 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +50 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +190 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +376 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +100 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +964 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +246 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +431 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +139 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +327 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +233 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +18 -0
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +175 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1292 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +171 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1324 -0
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +3 -0
  110. package/lib/Socket/mex.d.ts.map +1 -0
  111. package/lib/Socket/mex.js +42 -0
  112. package/lib/Socket/mex.js.map +1 -0
  113. package/lib/Socket/newsletter.d.ts +149 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +351 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/socket.d.ts +53 -0
  118. package/lib/Socket/socket.d.ts.map +1 -0
  119. package/lib/Socket/socket.js +900 -0
  120. package/lib/Socket/socket.js.map +1 -0
  121. package/lib/Types/Auth.d.ts +115 -0
  122. package/lib/Types/Auth.d.ts.map +1 -0
  123. package/lib/Types/Auth.js +2 -0
  124. package/lib/Types/Auth.js.map +1 -0
  125. package/lib/Types/Bussines.d.ts +25 -0
  126. package/lib/Types/Bussines.d.ts.map +1 -0
  127. package/lib/Types/Bussines.js +2 -0
  128. package/lib/Types/Bussines.js.map +1 -0
  129. package/lib/Types/Call.d.ts +14 -0
  130. package/lib/Types/Call.d.ts.map +1 -0
  131. package/lib/Types/Call.js +2 -0
  132. package/lib/Types/Call.js.map +1 -0
  133. package/lib/Types/Chat.d.ts +123 -0
  134. package/lib/Types/Chat.d.ts.map +1 -0
  135. package/lib/Types/Chat.js +8 -0
  136. package/lib/Types/Chat.js.map +1 -0
  137. package/lib/Types/Contact.d.ts +24 -0
  138. package/lib/Types/Contact.d.ts.map +1 -0
  139. package/lib/Types/Contact.js +2 -0
  140. package/lib/Types/Contact.js.map +1 -0
  141. package/lib/Types/Events.d.ts +202 -0
  142. package/lib/Types/Events.d.ts.map +1 -0
  143. package/lib/Types/Events.js +2 -0
  144. package/lib/Types/Events.js.map +1 -0
  145. package/lib/Types/GroupMetadata.d.ts +67 -0
  146. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  147. package/lib/Types/GroupMetadata.js +2 -0
  148. package/lib/Types/GroupMetadata.js.map +1 -0
  149. package/lib/Types/Label.d.ts +47 -0
  150. package/lib/Types/Label.d.ts.map +1 -0
  151. package/lib/Types/Label.js +25 -0
  152. package/lib/Types/Label.js.map +1 -0
  153. package/lib/Types/LabelAssociation.d.ts +30 -0
  154. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  155. package/lib/Types/LabelAssociation.js +7 -0
  156. package/lib/Types/LabelAssociation.js.map +1 -0
  157. package/lib/Types/Message.d.ts +342 -0
  158. package/lib/Types/Message.d.ts.map +1 -0
  159. package/lib/Types/Message.js +11 -0
  160. package/lib/Types/Message.js.map +1 -0
  161. package/lib/Types/Newsletter.d.ts +135 -0
  162. package/lib/Types/Newsletter.d.ts.map +1 -0
  163. package/lib/Types/Newsletter.js +31 -0
  164. package/lib/Types/Newsletter.js.map +1 -0
  165. package/lib/Types/Product.d.ts +79 -0
  166. package/lib/Types/Product.d.ts.map +1 -0
  167. package/lib/Types/Product.js +2 -0
  168. package/lib/Types/Product.js.map +1 -0
  169. package/lib/Types/Signal.d.ts +76 -0
  170. package/lib/Types/Signal.d.ts.map +1 -0
  171. package/lib/Types/Signal.js +2 -0
  172. package/lib/Types/Signal.js.map +1 -0
  173. package/lib/Types/Socket.d.ts +133 -0
  174. package/lib/Types/Socket.d.ts.map +1 -0
  175. package/lib/Types/Socket.js +3 -0
  176. package/lib/Types/Socket.js.map +1 -0
  177. package/lib/Types/State.d.ts +39 -0
  178. package/lib/Types/State.d.ts.map +1 -0
  179. package/lib/Types/State.js +13 -0
  180. package/lib/Types/State.js.map +1 -0
  181. package/lib/Types/USync.d.ts +26 -0
  182. package/lib/Types/USync.d.ts.map +1 -0
  183. package/lib/Types/USync.js +2 -0
  184. package/lib/Types/USync.js.map +1 -0
  185. package/lib/Types/index.d.ts +65 -0
  186. package/lib/Types/index.d.ts.map +1 -0
  187. package/lib/Types/index.js +26 -0
  188. package/lib/Types/index.js.map +1 -0
  189. package/lib/Utils/auth-utils.d.ts +19 -0
  190. package/lib/Utils/auth-utils.d.ts.map +1 -0
  191. package/lib/Utils/auth-utils.js +257 -0
  192. package/lib/Utils/auth-utils.js.map +1 -0
  193. package/lib/Utils/browser-utils.d.ts +4 -0
  194. package/lib/Utils/browser-utils.d.ts.map +1 -0
  195. package/lib/Utils/browser-utils.js +28 -0
  196. package/lib/Utils/browser-utils.js.map +1 -0
  197. package/lib/Utils/business.d.ts +23 -0
  198. package/lib/Utils/business.d.ts.map +1 -0
  199. package/lib/Utils/business.js +231 -0
  200. package/lib/Utils/business.js.map +1 -0
  201. package/lib/Utils/chat-utils.d.ts +70 -0
  202. package/lib/Utils/chat-utils.d.ts.map +1 -0
  203. package/lib/Utils/chat-utils.js +763 -0
  204. package/lib/Utils/chat-utils.js.map +1 -0
  205. package/lib/Utils/crypto.d.ts +41 -0
  206. package/lib/Utils/crypto.d.ts.map +1 -0
  207. package/lib/Utils/crypto.js +142 -0
  208. package/lib/Utils/crypto.js.map +1 -0
  209. package/lib/Utils/decode-wa-message.d.ts +48 -0
  210. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  211. package/lib/Utils/decode-wa-message.js +283 -0
  212. package/lib/Utils/decode-wa-message.js.map +1 -0
  213. package/lib/Utils/event-buffer.d.ts +34 -0
  214. package/lib/Utils/event-buffer.d.ts.map +1 -0
  215. package/lib/Utils/event-buffer.js +548 -0
  216. package/lib/Utils/event-buffer.js.map +1 -0
  217. package/lib/Utils/generics.d.ts +90 -0
  218. package/lib/Utils/generics.d.ts.map +1 -0
  219. package/lib/Utils/generics.js +381 -0
  220. package/lib/Utils/generics.js.map +1 -0
  221. package/lib/Utils/history.d.ts +19 -0
  222. package/lib/Utils/history.d.ts.map +1 -0
  223. package/lib/Utils/history.js +90 -0
  224. package/lib/Utils/history.js.map +1 -0
  225. package/lib/Utils/index.d.ts +19 -0
  226. package/lib/Utils/index.d.ts.map +1 -0
  227. package/lib/Utils/index.js +19 -0
  228. package/lib/Utils/index.js.map +1 -0
  229. package/lib/Utils/link-preview.d.ts +21 -0
  230. package/lib/Utils/link-preview.d.ts.map +1 -0
  231. package/lib/Utils/link-preview.js +85 -0
  232. package/lib/Utils/link-preview.js.map +1 -0
  233. package/lib/Utils/logger.d.ts +12 -0
  234. package/lib/Utils/logger.d.ts.map +1 -0
  235. package/lib/Utils/logger.js +3 -0
  236. package/lib/Utils/logger.js.map +1 -0
  237. package/lib/Utils/lt-hash.d.ts +13 -0
  238. package/lib/Utils/lt-hash.d.ts.map +1 -0
  239. package/lib/Utils/lt-hash.js +48 -0
  240. package/lib/Utils/lt-hash.js.map +1 -0
  241. package/lib/Utils/make-mutex.d.ts +8 -0
  242. package/lib/Utils/make-mutex.d.ts.map +1 -0
  243. package/lib/Utils/make-mutex.js +40 -0
  244. package/lib/Utils/make-mutex.js.map +1 -0
  245. package/lib/Utils/message-retry-manager.d.ts +82 -0
  246. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  247. package/lib/Utils/message-retry-manager.js +172 -0
  248. package/lib/Utils/message-retry-manager.js.map +1 -0
  249. package/lib/Utils/messages-media.d.ts +114 -0
  250. package/lib/Utils/messages-media.d.ts.map +1 -0
  251. package/lib/Utils/messages-media.js +667 -0
  252. package/lib/Utils/messages-media.js.map +1 -0
  253. package/lib/Utils/messages.d.ts +89 -0
  254. package/lib/Utils/messages.d.ts.map +1 -0
  255. package/lib/Utils/messages.js +1132 -0
  256. package/lib/Utils/messages.js.map +1 -0
  257. package/lib/Utils/noise-handler.d.ts +20 -0
  258. package/lib/Utils/noise-handler.d.ts.map +1 -0
  259. package/lib/Utils/noise-handler.js +147 -0
  260. package/lib/Utils/noise-handler.js.map +1 -0
  261. package/lib/Utils/pre-key-manager.d.ts +28 -0
  262. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  263. package/lib/Utils/pre-key-manager.js +106 -0
  264. package/lib/Utils/pre-key-manager.js.map +1 -0
  265. package/lib/Utils/process-message.d.ts +60 -0
  266. package/lib/Utils/process-message.d.ts.map +1 -0
  267. package/lib/Utils/process-message.js +485 -0
  268. package/lib/Utils/process-message.js.map +1 -0
  269. package/lib/Utils/signal.d.ts +34 -0
  270. package/lib/Utils/signal.d.ts.map +1 -0
  271. package/lib/Utils/signal.js +159 -0
  272. package/lib/Utils/signal.js.map +1 -0
  273. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  274. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  275. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  276. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  277. package/lib/Utils/validate-connection.d.ts +11 -0
  278. package/lib/Utils/validate-connection.d.ts.map +1 -0
  279. package/lib/Utils/validate-connection.js +200 -0
  280. package/lib/Utils/validate-connection.js.map +1 -0
  281. package/lib/WABinary/constants.d.ts +28 -0
  282. package/lib/WABinary/constants.d.ts.map +1 -0
  283. package/lib/WABinary/constants.js +1301 -0
  284. package/lib/WABinary/constants.js.map +1 -0
  285. package/lib/WABinary/decode.d.ts +7 -0
  286. package/lib/WABinary/decode.d.ts.map +1 -0
  287. package/lib/WABinary/decode.js +238 -0
  288. package/lib/WABinary/decode.js.map +1 -0
  289. package/lib/WABinary/encode.d.ts +3 -0
  290. package/lib/WABinary/encode.d.ts.map +1 -0
  291. package/lib/WABinary/encode.js +216 -0
  292. package/lib/WABinary/encode.js.map +1 -0
  293. package/lib/WABinary/generic-utils.d.ts +17 -0
  294. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  295. package/lib/WABinary/generic-utils.js +233 -0
  296. package/lib/WABinary/generic-utils.js.map +1 -0
  297. package/lib/WABinary/index.d.ts +6 -0
  298. package/lib/WABinary/index.d.ts.map +1 -0
  299. package/lib/WABinary/index.js +6 -0
  300. package/lib/WABinary/index.js.map +1 -0
  301. package/lib/WABinary/jid-utils.d.ts +48 -0
  302. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  303. package/lib/WABinary/jid-utils.js +96 -0
  304. package/lib/WABinary/jid-utils.js.map +1 -0
  305. package/lib/WABinary/types.d.ts +19 -0
  306. package/lib/WABinary/types.d.ts.map +1 -0
  307. package/lib/WABinary/types.js +2 -0
  308. package/lib/WABinary/types.js.map +1 -0
  309. package/lib/WAM/BinaryInfo.d.ts +9 -0
  310. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  311. package/lib/WAM/BinaryInfo.js +10 -0
  312. package/lib/WAM/BinaryInfo.js.map +1 -0
  313. package/lib/WAM/constants.d.ts +40 -0
  314. package/lib/WAM/constants.d.ts.map +1 -0
  315. package/lib/WAM/constants.js +22853 -0
  316. package/lib/WAM/constants.js.map +1 -0
  317. package/lib/WAM/encode.d.ts +3 -0
  318. package/lib/WAM/encode.d.ts.map +1 -0
  319. package/lib/WAM/encode.js +150 -0
  320. package/lib/WAM/encode.js.map +1 -0
  321. package/lib/WAM/index.d.ts +4 -0
  322. package/lib/WAM/index.d.ts.map +1 -0
  323. package/lib/WAM/index.js +4 -0
  324. package/lib/WAM/index.js.map +1 -0
  325. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  326. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  327. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  328. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  329. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  330. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  331. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  332. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  333. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  334. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  335. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  336. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  337. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  338. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  339. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  340. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  341. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  342. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  343. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  344. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  345. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  346. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  347. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  348. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  349. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  350. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  351. package/lib/WAUSync/Protocols/index.js +5 -0
  352. package/lib/WAUSync/Protocols/index.js.map +1 -0
  353. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  354. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  355. package/lib/WAUSync/USyncQuery.js +94 -0
  356. package/lib/WAUSync/USyncQuery.js.map +1 -0
  357. package/lib/WAUSync/USyncUser.d.ts +13 -0
  358. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  359. package/lib/WAUSync/USyncUser.js +23 -0
  360. package/lib/WAUSync/USyncUser.js.map +1 -0
  361. package/lib/WAUSync/index.d.ts +4 -0
  362. package/lib/WAUSync/index.d.ts.map +1 -0
  363. package/lib/WAUSync/index.js +4 -0
  364. package/lib/WAUSync/index.js.map +1 -0
  365. package/lib/index.d.ts +12 -0
  366. package/lib/index.d.ts.map +1 -0
  367. package/lib/index.js +11 -0
  368. package/lib/index.js.map +1 -0
  369. package/package.json +119 -0
@@ -0,0 +1,1324 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import * as crypto from 'crypto';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageID, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageContent, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { getUrlInfo } from '../Utils/link-preview.js';
8
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
9
+ import { areJidsSameUser, getAdditionalNode, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
10
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
11
+ import { makeNewsletterSocket } from './newsletter.js';
12
+ export const makeMessagesSocket = (config) => {
13
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
14
+ const sock = makeNewsletterSocket(config);
15
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
16
+ const userDevicesCache = config.userDevicesCache ||
17
+ new NodeCache({
18
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
19
+ useClones: false
20
+ });
21
+ const peerSessionsCache = new NodeCache({
22
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
23
+ useClones: false
24
+ });
25
+ // Initialize message retry manager if enabled
26
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
27
+ // Prevent race conditions in Signal session encryption by user
28
+ const encryptionMutex = makeKeyedMutex();
29
+ let mediaConn;
30
+ const refreshMediaConn = async (forceGet = false) => {
31
+ const media = await mediaConn;
32
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
33
+ mediaConn = (async () => {
34
+ const result = await query({
35
+ tag: 'iq',
36
+ attrs: {
37
+ type: 'set',
38
+ xmlns: 'w:m',
39
+ to: S_WHATSAPP_NET
40
+ },
41
+ content: [{ tag: 'media_conn', attrs: {} }]
42
+ });
43
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
44
+ // TODO: explore full length of data that whatsapp provides
45
+ const node = {
46
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
47
+ hostname: attrs.hostname,
48
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
49
+ })),
50
+ auth: mediaConnNode.attrs.auth,
51
+ ttl: +mediaConnNode.attrs.ttl,
52
+ fetchDate: new Date()
53
+ };
54
+ logger.debug('fetched media conn');
55
+ return node;
56
+ })();
57
+ }
58
+ return mediaConn;
59
+ };
60
+ /**
61
+ * generic send receipt function
62
+ * used for receipts of phone call, read, delivery etc.
63
+ * */
64
+ const sendReceipt = async (jid, participant, messageIds, type) => {
65
+ if (!messageIds || messageIds.length === 0) {
66
+ throw new Boom('missing ids in receipt');
67
+ }
68
+ const node = {
69
+ tag: 'receipt',
70
+ attrs: {
71
+ id: messageIds[0]
72
+ }
73
+ };
74
+ const isReadReceipt = type === 'read' || type === 'read-self';
75
+ if (isReadReceipt) {
76
+ node.attrs.t = unixTimestampSeconds().toString();
77
+ }
78
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
79
+ node.attrs.recipient = jid;
80
+ node.attrs.to = participant;
81
+ }
82
+ else {
83
+ node.attrs.to = jid;
84
+ if (participant) {
85
+ node.attrs.participant = participant;
86
+ }
87
+ }
88
+ if (type) {
89
+ node.attrs.type = type;
90
+ }
91
+ const remainingMessageIds = messageIds.slice(1);
92
+ if (remainingMessageIds.length) {
93
+ node.content = [
94
+ {
95
+ tag: 'list',
96
+ attrs: {},
97
+ content: remainingMessageIds.map(id => ({
98
+ tag: 'item',
99
+ attrs: { id }
100
+ }))
101
+ }
102
+ ];
103
+ }
104
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
105
+ await sendNode(node);
106
+ };
107
+ /** Correctly bulk send receipts to multiple chats, participants */
108
+ const sendReceipts = async (keys, type) => {
109
+ const recps = aggregateMessageKeysNotFromMe(keys);
110
+ for (const { jid, participant, messageIds } of recps) {
111
+ await sendReceipt(jid, participant, messageIds, type);
112
+ }
113
+ };
114
+ /** Bulk read messages. Keys can be from different chats & participants */
115
+ const readMessages = async (keys) => {
116
+ const privacySettings = await fetchPrivacySettings();
117
+ // based on privacy settings, we have to change the read type
118
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
119
+ await sendReceipts(keys, readType);
120
+ };
121
+ /** Fetch all the devices we've to send a message to */
122
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
123
+ const deviceResults = [];
124
+ if (!useCache) {
125
+ logger.debug('not using cache for devices');
126
+ }
127
+ const toFetch = [];
128
+ const jidsWithUser = jids
129
+ .map(jid => {
130
+ const decoded = jidDecode(jid);
131
+ const user = decoded?.user;
132
+ const device = decoded?.device;
133
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
134
+ if (isExplicitDevice && user) {
135
+ deviceResults.push({
136
+ user,
137
+ device,
138
+ jid
139
+ });
140
+ return null;
141
+ }
142
+ jid = jidNormalizedUser(jid);
143
+ return { jid, user };
144
+ })
145
+ .filter(jid => jid !== null);
146
+ let mgetDevices;
147
+ if (useCache && userDevicesCache.mget) {
148
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
149
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
150
+ }
151
+ for (const { jid, user } of jidsWithUser) {
152
+ if (useCache) {
153
+ const devices = mgetDevices?.[user] ||
154
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
155
+ if (devices) {
156
+ const devicesWithJid = devices.map(d => ({
157
+ ...d,
158
+ jid: jidEncode(d.user, d.server, d.device)
159
+ }));
160
+ deviceResults.push(...devicesWithJid);
161
+ logger.trace({ user }, 'using cache for devices');
162
+ }
163
+ else {
164
+ toFetch.push(jid);
165
+ }
166
+ }
167
+ else {
168
+ toFetch.push(jid);
169
+ }
170
+ }
171
+ if (!toFetch.length) {
172
+ return deviceResults;
173
+ }
174
+ const requestedLidUsers = new Set();
175
+ for (const jid of toFetch) {
176
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
177
+ const user = jidDecode(jid)?.user;
178
+ if (user)
179
+ requestedLidUsers.add(user);
180
+ }
181
+ }
182
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
183
+ for (const jid of toFetch) {
184
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
185
+ }
186
+ const result = await sock.executeUSyncQuery(query);
187
+ if (result) {
188
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
189
+ const lidResults = result.list.filter(a => !!a.lid);
190
+ if (lidResults.length > 0) {
191
+ logger.trace('Storing LID maps from device call');
192
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
193
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
194
+ try {
195
+ const lids = lidResults.map(a => a.lid);
196
+ if (lids.length) {
197
+ await assertSessions(lids, true);
198
+ }
199
+ }
200
+ catch (e) {
201
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
202
+ }
203
+ }
204
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
205
+ const deviceMap = {};
206
+ for (const item of extracted) {
207
+ deviceMap[item.user] = deviceMap[item.user] || [];
208
+ deviceMap[item.user]?.push(item);
209
+ }
210
+ // Process each user's devices as a group for bulk LID migration
211
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
212
+ const isLidUser = requestedLidUsers.has(user);
213
+ // Process all devices for this user
214
+ for (const item of userDevices) {
215
+ const finalJid = isLidUser
216
+ ? jidEncode(user, item.server, item.device)
217
+ : jidEncode(item.user, item.server, item.device);
218
+ deviceResults.push({
219
+ ...item,
220
+ jid: finalJid
221
+ });
222
+ logger.debug({
223
+ user: item.user,
224
+ device: item.device,
225
+ finalJid,
226
+ usedLid: isLidUser
227
+ }, 'Processed device with LID priority');
228
+ }
229
+ }
230
+ if (userDevicesCache.mset) {
231
+ // if the cache supports mset, we can set all devices in one go
232
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
233
+ }
234
+ else {
235
+ for (const key in deviceMap) {
236
+ if (deviceMap[key])
237
+ await userDevicesCache.set(key, deviceMap[key]);
238
+ }
239
+ }
240
+ const userDeviceUpdates = {};
241
+ for (const [userId, devices] of Object.entries(deviceMap)) {
242
+ if (devices && devices.length > 0) {
243
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
244
+ }
245
+ }
246
+ if (Object.keys(userDeviceUpdates).length > 0) {
247
+ try {
248
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
249
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
250
+ }
251
+ catch (error) {
252
+ logger.warn({ error }, 'failed to store user device lists');
253
+ }
254
+ }
255
+ }
256
+ return deviceResults;
257
+ };
258
+ const assertSessions = async (jids, force) => {
259
+ let didFetchNewSession = false;
260
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
261
+ const jidsRequiringFetch = [];
262
+ logger.debug({ jids }, 'assertSessions call with jids');
263
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
264
+ for (const jid of uniqueJids) {
265
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
266
+ const cachedSession = peerSessionsCache.get(signalId);
267
+ if (cachedSession !== undefined) {
268
+ if (cachedSession && !force) {
269
+ continue; // Session exists in cache
270
+ }
271
+ }
272
+ else {
273
+ const sessionValidation = await signalRepository.validateSession(jid);
274
+ const hasSession = sessionValidation.exists;
275
+ peerSessionsCache.set(signalId, hasSession);
276
+ if (hasSession && !force) {
277
+ continue;
278
+ }
279
+ }
280
+ jidsRequiringFetch.push(jid);
281
+ }
282
+ if (jidsRequiringFetch.length) {
283
+ // LID if mapped, otherwise original
284
+ const wireJids = [
285
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
286
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
287
+ ];
288
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
289
+ const result = await query({
290
+ tag: 'iq',
291
+ attrs: {
292
+ xmlns: 'encrypt',
293
+ type: 'get',
294
+ to: S_WHATSAPP_NET
295
+ },
296
+ content: [
297
+ {
298
+ tag: 'key',
299
+ attrs: {},
300
+ content: wireJids.map(jid => {
301
+ const attrs = { jid };
302
+ if (force)
303
+ attrs.reason = 'identity';
304
+ return { tag: 'user', attrs };
305
+ })
306
+ }
307
+ ]
308
+ });
309
+ await parseAndInjectE2ESessions(result, signalRepository);
310
+ didFetchNewSession = true;
311
+ // Cache fetched sessions using wire JIDs
312
+ for (const wireJid of wireJids) {
313
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
314
+ peerSessionsCache.set(signalId, true);
315
+ }
316
+ }
317
+ return didFetchNewSession;
318
+ };
319
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
320
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
321
+ if (!authState.creds.me?.id) {
322
+ throw new Boom('Not authenticated');
323
+ }
324
+ const protocolMessage = {
325
+ protocolMessage: {
326
+ peerDataOperationRequestMessage: pdoMessage,
327
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
328
+ }
329
+ };
330
+ const meJid = jidNormalizedUser(authState.creds.me.id);
331
+ const msgId = await relayMessage(meJid, protocolMessage, {
332
+ additionalAttributes: {
333
+ category: 'peer',
334
+ push_priority: 'high_force'
335
+ },
336
+ additionalNodes: [
337
+ {
338
+ tag: 'meta',
339
+ attrs: { appdata: 'default' }
340
+ }
341
+ ]
342
+ });
343
+ return msgId;
344
+ };
345
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
346
+ if (!recipientJids.length) {
347
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
348
+ }
349
+ const patched = await patchMessageBeforeSending(message, recipientJids);
350
+ const patchedMessages = Array.isArray(patched)
351
+ ? patched
352
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
353
+ let shouldIncludeDeviceIdentity = false;
354
+ const meId = authState.creds.me.id;
355
+ const meLid = authState.creds.me?.lid;
356
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
357
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
358
+ if (!jid)
359
+ return null;
360
+ let msgToEncrypt = patchedMessage;
361
+ if (dsmMessage) {
362
+ const { user: targetUser } = jidDecode(jid);
363
+ const { user: ownPnUser } = jidDecode(meId);
364
+ const ownLidUser = meLidUser;
365
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
366
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
367
+ if (isOwnUser && !isExactSenderDevice) {
368
+ msgToEncrypt = dsmMessage;
369
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
370
+ }
371
+ }
372
+ const bytes = encodeWAMessage(msgToEncrypt);
373
+ const mutexKey = jid;
374
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
375
+ const { type, ciphertext } = await signalRepository.encryptMessage({
376
+ jid,
377
+ data: bytes
378
+ });
379
+ if (type === 'pkmsg') {
380
+ shouldIncludeDeviceIdentity = true;
381
+ }
382
+ return {
383
+ tag: 'to',
384
+ attrs: { jid },
385
+ content: [
386
+ {
387
+ tag: 'enc',
388
+ attrs: {
389
+ v: '2',
390
+ type,
391
+ ...(extraAttrs || {})
392
+ },
393
+ content: ciphertext
394
+ }
395
+ ]
396
+ };
397
+ });
398
+ return node;
399
+ });
400
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
401
+ return { nodes, shouldIncludeDeviceIdentity };
402
+ };
403
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = true, includeBizNode = false }) => {
404
+ const meId = authState.creds.me.id;
405
+ const meLid = authState.creds.me?.lid;
406
+ const isRetryResend = Boolean(participant?.jid);
407
+ let shouldIncludeDeviceIdentity = isRetryResend;
408
+ const statusJid = 'status@broadcast';
409
+ const { user, server } = jidDecode(jid);
410
+ const isGroup = server === 'g.us';
411
+ const isStatus = jid === statusJid;
412
+ const isLid = server === 'lid';
413
+ const isPrivate = server === 's.whatsapp.net' || isLid;
414
+ const isNewsletter = server === 'newsletter';
415
+ const isGroupOrStatus = isGroup || isStatus;
416
+ const finalJid = jid;
417
+ msgId = msgId || generateMessageIDV2(meId);
418
+ useUserDevicesCache = useUserDevicesCache !== false;
419
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
420
+ const participants = [];
421
+ const destinationJid = !isStatus ? finalJid : statusJid;
422
+ const binaryNodeContent = [];
423
+ const devices = [];
424
+ const meMsg = {
425
+ deviceSentMessage: {
426
+ destinationJid,
427
+ message
428
+ },
429
+ messageContextInfo: message.messageContextInfo
430
+ };
431
+ const extraAttrs = {};
432
+ const normalizedMessage = normalizeMessageContent(message);
433
+ const buttonType = getButtonType(normalizedMessage);
434
+ if (participant) {
435
+ if (!isGroup && !isStatus) {
436
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
437
+ }
438
+ const { user, device } = jidDecode(participant.jid);
439
+ devices.push({
440
+ user,
441
+ device,
442
+ jid: participant.jid
443
+ });
444
+ }
445
+ await authState.keys.transaction(async () => {
446
+ const mediaType = getMediaType(message);
447
+ if (mediaType) {
448
+ extraAttrs['mediatype'] = mediaType;
449
+ }
450
+ if (isNewsletter) {
451
+ if (message?.protocolMessage?.editedMessage) {
452
+ msgId = message.protocolMessage.key?.id || msgId;
453
+ message = message.protocolMessage.editedMessage;
454
+ }
455
+ if (message?.protocolMessage?.type === proto.Message.ProtocolMessage.Type.REVOKE) {
456
+ msgId = message.protocolMessage.key?.id || msgId;
457
+ message = {};
458
+ }
459
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
460
+ const bytes = encodeNewsletterMessage(patched);
461
+ const normalizedMediaType = mediaType === 'ptt' ? 'audio' : mediaType;
462
+ binaryNodeContent.push({
463
+ tag: 'plaintext',
464
+ attrs: normalizedMediaType ? { mediatype: normalizedMediaType } : {},
465
+ content: bytes
466
+ });
467
+ const stanza = {
468
+ tag: 'message',
469
+ attrs: {
470
+ to: jid,
471
+ id: msgId,
472
+ type: getTypeMessage(message),
473
+ ...(additionalAttributes || {})
474
+ },
475
+ content: binaryNodeContent
476
+ };
477
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
478
+ await sendNode(stanza);
479
+ return;
480
+ }
481
+ if (normalizeMessageContent(message)?.pinInChatMessage) {
482
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
483
+ }
484
+ if (isGroupOrStatus && !isRetryResend) {
485
+ const [groupData, senderKeyMap] = await Promise.all([
486
+ (async () => {
487
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
488
+ if (groupData && Array.isArray(groupData?.participants)) {
489
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
490
+ }
491
+ else if (!isStatus) {
492
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
493
+ }
494
+ return groupData;
495
+ })(),
496
+ (async () => {
497
+ if (!participant && !isStatus) {
498
+ // what if sender memory is less accurate than the cached metadata
499
+ // on participant change in group, we should do sender memory manipulation
500
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
501
+ return result[jid] || {};
502
+ }
503
+ return {};
504
+ })()
505
+ ]);
506
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
507
+ // do not inject stanza-level expiration automatically.
508
+ if (isStatus && statusJidList) {
509
+ participantsList.push(...statusJidList);
510
+ }
511
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
512
+ devices.push(...additionalDevices);
513
+ if (isGroup) {
514
+ additionalAttributes = {
515
+ ...additionalAttributes,
516
+ addressing_mode: groupData?.addressingMode || 'lid'
517
+ };
518
+ }
519
+ const patched = await patchMessageBeforeSending(message);
520
+ if (Array.isArray(patched)) {
521
+ throw new Boom('Per-jid patching is not supported in groups');
522
+ }
523
+ const bytes = encodeWAMessage(patched);
524
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
525
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
526
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
527
+ group: destinationJid,
528
+ data: bytes,
529
+ meId: groupSenderIdentity
530
+ });
531
+ const senderKeyRecipients = [];
532
+ for (const device of devices) {
533
+ const deviceJid = device.jid;
534
+ const hasKey = !!senderKeyMap[deviceJid];
535
+ if ((!hasKey || !!participant) &&
536
+ !isHostedLidUser(deviceJid) &&
537
+ !isHostedPnUser(deviceJid) &&
538
+ device.device !== 99) {
539
+ //todo: revamp all this logic
540
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
541
+ senderKeyRecipients.push(deviceJid);
542
+ senderKeyMap[deviceJid] = true;
543
+ }
544
+ }
545
+ if (senderKeyRecipients.length) {
546
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
547
+ const senderKeyMsg = {
548
+ senderKeyDistributionMessage: {
549
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
550
+ groupId: destinationJid
551
+ }
552
+ };
553
+ const senderKeySessionTargets = senderKeyRecipients;
554
+ await assertSessions(senderKeySessionTargets);
555
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
556
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
557
+ participants.push(...result.nodes);
558
+ }
559
+ binaryNodeContent.push({
560
+ tag: 'enc',
561
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
562
+ content: ciphertext
563
+ });
564
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
565
+ }
566
+ else {
567
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
568
+ // TODO: investigate if this is true
569
+ let ownId = meId;
570
+ if (isLid && meLid) {
571
+ ownId = meLid;
572
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
573
+ }
574
+ else {
575
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
576
+ }
577
+ const { user: ownUser } = jidDecode(ownId);
578
+ if (!isRetryResend) {
579
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
580
+ devices.push({
581
+ user,
582
+ device: 0,
583
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
584
+ });
585
+ if (user !== ownUser) {
586
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
587
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
588
+ devices.push({
589
+ user: ownUserForAddressing,
590
+ device: 0,
591
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
592
+ });
593
+ }
594
+ if (additionalAttributes?.['category'] !== 'peer') {
595
+ // Clear placeholders and enumerate actual devices
596
+ devices.length = 0;
597
+ // Use conversation-appropriate sender identity
598
+ const senderIdentity = isLid && meLid
599
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
600
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
601
+ // Enumerate devices for sender and target with consistent addressing
602
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
603
+ devices.push(...sessionDevices);
604
+ logger.debug({
605
+ deviceCount: devices.length,
606
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
607
+ }, 'Device enumeration complete with unified addressing');
608
+ }
609
+ }
610
+ const allRecipients = [];
611
+ const meRecipients = [];
612
+ const otherRecipients = [];
613
+ const { user: mePnUser } = jidDecode(meId);
614
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
615
+ for (const { user, jid } of devices) {
616
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
617
+ if (isExactSenderDevice) {
618
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
619
+ continue;
620
+ }
621
+ // Check if this is our device (could match either PN or LID user)
622
+ const isMe = user === mePnUser || user === meLidUser;
623
+ if (isMe) {
624
+ meRecipients.push(jid);
625
+ }
626
+ else {
627
+ otherRecipients.push(jid);
628
+ }
629
+ allRecipients.push(jid);
630
+ }
631
+ await assertSessions(allRecipients);
632
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
633
+ // For own devices: use DSM if available (1:1 chats only)
634
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
635
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
636
+ ]);
637
+ participants.push(...meNodes);
638
+ participants.push(...otherNodes);
639
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
640
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
641
+ }
642
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
643
+ }
644
+ if (isRetryResend) {
645
+ const isParticipantLid = isLidUser(participant.jid);
646
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
647
+ const encodedMessageToSend = isMe
648
+ ? encodeWAMessage({
649
+ deviceSentMessage: {
650
+ destinationJid,
651
+ message
652
+ }
653
+ })
654
+ : encodeWAMessage(message);
655
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
656
+ data: encodedMessageToSend,
657
+ jid: participant.jid
658
+ });
659
+ binaryNodeContent.push({
660
+ tag: 'enc',
661
+ attrs: {
662
+ v: '2',
663
+ type,
664
+ count: participant.count.toString()
665
+ },
666
+ content: encryptedContent
667
+ });
668
+ }
669
+ if (participants.length) {
670
+ if (additionalAttributes?.['category'] === 'peer') {
671
+ const peerNode = participants[0]?.content?.[0];
672
+ if (peerNode) {
673
+ binaryNodeContent.push(peerNode); // push only enc
674
+ }
675
+ }
676
+ else {
677
+ binaryNodeContent.push({
678
+ tag: 'participants',
679
+ attrs: {},
680
+ content: participants
681
+ });
682
+ }
683
+ }
684
+ const stanza = {
685
+ tag: 'message',
686
+ attrs: {
687
+ id: msgId,
688
+ to: destinationJid,
689
+ type: getMessageType(message),
690
+ ...(additionalAttributes || {})
691
+ },
692
+ content: binaryNodeContent
693
+ };
694
+ // if the participant to send to is explicitly specified (generally retry recp)
695
+ // ensure the message is only sent to that person
696
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
697
+ if (participant) {
698
+ if (isJidGroup(destinationJid)) {
699
+ stanza.attrs.to = destinationJid;
700
+ stanza.attrs.participant = participant.jid;
701
+ }
702
+ else if (areJidsSameUser(participant.jid, meId)) {
703
+ stanza.attrs.to = participant.jid;
704
+ stanza.attrs.recipient = destinationJid;
705
+ }
706
+ else {
707
+ stanza.attrs.to = participant.jid;
708
+ }
709
+ }
710
+ else {
711
+ stanza.attrs.to = destinationJid;
712
+ }
713
+ if (shouldIncludeDeviceIdentity) {
714
+ ;
715
+ stanza.content.push({
716
+ tag: 'device-identity',
717
+ attrs: {},
718
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
719
+ });
720
+ logger.debug({ jid }, 'adding device identity');
721
+ }
722
+ const contactTcTokenData = !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {};
723
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
724
+ if (tcTokenBuffer) {
725
+ ;
726
+ stanza.content.push({
727
+ tag: 'tctoken',
728
+ attrs: {},
729
+ content: tcTokenBuffer
730
+ });
731
+ }
732
+ const nodes = Array.isArray(additionalNodes) ? additionalNodes : [];
733
+ const hasBizNode = nodes.some(n => n?.tag === 'biz' || n?.tag === 'hsm');
734
+ const hasBotNode = nodes.some(n => n?.tag === 'bot' && n?.attrs?.biz_bot === '1');
735
+ // Interactive/list/button payloads require the biz stanza metadata.
736
+ // Keep explicit override, but restore auto-injection when buttonType exists.
737
+ if ((includeBizNode || !!buttonType) && !isNewsletter && !hasBizNode) {
738
+ stanza.content.push(...getAdditionalNode(buttonType));
739
+ }
740
+ // AI label injection disabled by local patch.
741
+ if (nodes.length > 0) {
742
+ stanza.content.push(...nodes);
743
+ }
744
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
745
+ await sendNode(stanza);
746
+ // Add message to retry cache if enabled
747
+ if (messageRetryManager && !participant) {
748
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
749
+ }
750
+ }, meId);
751
+ return msgId;
752
+ };
753
+
754
+ // used to decide which "biz" stanza to add.
755
+ const getButtonType = (message) => {
756
+ if (!message)
757
+ return;
758
+ if (message.listMessage) {
759
+ return 'list';
760
+ }
761
+ else if (message.buttonsMessage) {
762
+ return 'buttons';
763
+ }
764
+ else if (message.interactiveMessage && !message.interactiveMessage?.nativeFlowMessage) {
765
+ return 'interactive';
766
+ }
767
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
768
+ return 'review_and_pay';
769
+ }
770
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
771
+ return 'review_order';
772
+ }
773
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
774
+ return 'payment_info';
775
+ }
776
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
777
+ return 'payment_status';
778
+ }
779
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
780
+ return 'payment_method';
781
+ }
782
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
783
+ return 'interactive';
784
+ }
785
+ else if (message.interactiveMessage?.nativeFlowMessage) {
786
+ return 'native_flow';
787
+ }
788
+ };
789
+
790
+ // send an album stub message, then send each media message
791
+ // with association info pointing to the parent album message.
792
+ const sendAlbumMessage = async (jid, content, quoted) => {
793
+ const array = content.albumMessage;
794
+ const album = await generateWAMessageFromContent(jid, {
795
+ messageContextInfo: {
796
+ messageSecret: crypto.randomBytes(32)
797
+ },
798
+ albumMessage: {
799
+ expectedImageCount: array.filter((a) => Object.prototype.hasOwnProperty.call(a, 'image')).length,
800
+ expectedVideoCount: array.filter((a) => Object.prototype.hasOwnProperty.call(a, 'video')).length
801
+ }
802
+ }, {
803
+ userJid: generateMessageID().split('@')[0] + '@s.whatsapp.net',
804
+ quoted,
805
+ upload: async (readStream, opts) => waUploadToServer(readStream, { ...opts, newsletter: isJidNewsletter(jid) })
806
+ });
807
+ await relayMessage(jid, album.message, {
808
+ messageId: album.key.id
809
+ });
810
+ for (const mediaContent of array) {
811
+ const img = await generateWAMessage(jid, mediaContent, {
812
+ upload: async (readStream, opts) => waUploadToServer(readStream, { ...opts, newsletter: isJidNewsletter(jid) })
813
+ });
814
+ img.message.messageContextInfo = {
815
+ messageSecret: crypto.randomBytes(32),
816
+ messageAssociation: {
817
+ associationType: 1,
818
+ parentMessageKey: album.key
819
+ },
820
+ participant: '0@s.whatsapp.net',
821
+ remoteJid: 'status@broadcast',
822
+ forwardingScore: 99999,
823
+ isForwarded: true,
824
+ mentionedJid: [jid],
825
+ starred: true,
826
+ labels: ['Y', 'Important'],
827
+ isHighlighted: true,
828
+ businessMessageForwardInfo: {
829
+ businessOwnerJid: jid
830
+ },
831
+ dataSharingContext: {
832
+ showMmDisclosure: true
833
+ }
834
+ };
835
+ img.message.forwardedNewsletterMessageInfo = {
836
+ newsletterJid: '0@newsletter',
837
+ serverMessageId: 1,
838
+ newsletterName: 'WhatsApp',
839
+ contentType: 1,
840
+ timestamp: new Date().toISOString(),
841
+ senderName: 'kikyy dugonggg',
842
+ content: 'Text Message',
843
+ priority: 'high',
844
+ status: 'sent'
845
+ };
846
+ img.message.disappearingMode = {
847
+ initiator: 3,
848
+ trigger: 4,
849
+ initiatorDeviceJid: jid,
850
+ initiatedByExternalService: true,
851
+ initiatedByUserDevice: true,
852
+ initiatedBySystem: true,
853
+ initiatedByServer: true,
854
+ initiatedByAdmin: true,
855
+ initiatedByUser: true,
856
+ initiatedByApp: true,
857
+ initiatedByBot: true,
858
+ initiatedByMe: true
859
+ };
860
+ await relayMessage(jid, img.message, {
861
+ messageId: img.key.id,
862
+ // This is ignored by relayMessage()
863
+ quoted: {
864
+ key: {
865
+ remoteJid: album.key.remoteJid,
866
+ id: album.key.id,
867
+ fromMe: true,
868
+ participant: generateMessageID().split('@')[0] + '@s.whatsapp.net'
869
+ },
870
+ message: album.message
871
+ }
872
+ });
873
+ }
874
+ return album;
875
+ };
876
+
877
+ // handleEvent()
878
+ const sendEventMessage = async (jid, content, quoted) => {
879
+ const eventData = content.eventMessage;
880
+ const msg = await generateWAMessageFromContent(jid, {
881
+ viewOnceMessage: {
882
+ message: {
883
+ messageContextInfo: {
884
+ deviceListMetadata: {},
885
+ deviceListMetadataVersion: 2,
886
+ messageSecret: crypto.randomBytes(32),
887
+ supportPayload: JSON.stringify({
888
+ version: 2,
889
+ is_ai_message: true,
890
+ should_show_system_message: true,
891
+ ticket_id: crypto.randomBytes(16).toString('hex')
892
+ })
893
+ },
894
+ eventMessage: {
895
+ contextInfo: {
896
+ mentionedJid: [jid],
897
+ participant: jid,
898
+ remoteJid: 'status@broadcast',
899
+ forwardedNewsletterMessageInfo: {
900
+ newsletterName: 'shenvn.',
901
+ newsletterJid: '120363297591152843@newsletter',
902
+ serverMessageId: 1
903
+ }
904
+ },
905
+ isCanceled: eventData.isCanceled || false,
906
+ name: eventData.name,
907
+ description: eventData.description,
908
+ location: eventData.location || {
909
+ degreesLatitude: 0,
910
+ degreesLongitude: 0,
911
+ name: 'Location'
912
+ },
913
+ joinLink: eventData.joinLink || '',
914
+ startTime: typeof eventData.startTime === 'string'
915
+ ? parseInt(eventData.startTime)
916
+ : (eventData.startTime || Date.now()),
917
+ endTime: typeof eventData.endTime === 'string'
918
+ ? parseInt(eventData.endTime)
919
+ : (eventData.endTime || Date.now() + 3600000),
920
+ extraGuestsAllowed: eventData.extraGuestsAllowed !== false
921
+ }
922
+ }
923
+ }
924
+ }, { quoted });
925
+ await relayMessage(jid, msg.message, {
926
+ messageId: msg.key.id
927
+ });
928
+ return msg;
929
+ };
930
+
931
+ // handlePollResult()
932
+ const sendPollResultMessage = async (jid, content, quoted) => {
933
+ const pollData = content.pollResultMessage;
934
+ const msg = await generateWAMessageFromContent(jid, {
935
+ pollResultSnapshotMessage: {
936
+ name: pollData.name,
937
+ pollVotes: pollData.pollVotes.map(vote => ({
938
+ optionName: vote.optionName,
939
+ optionVoteCount: typeof vote.optionVoteCount === 'number'
940
+ ? vote.optionVoteCount.toString()
941
+ : vote.optionVoteCount
942
+ }))
943
+ }
944
+ }, {
945
+ userJid: generateMessageID().split('@')[0] + '@s.whatsapp.net',
946
+ quoted
947
+ });
948
+ await relayMessage(jid, msg.message, {
949
+ messageId: msg.key.id
950
+ });
951
+ return msg;
952
+ };
953
+
954
+ // handleProduct()
955
+ const sendProductMessage = async (jid, content, quoted) => {
956
+ const { title, description, thumbnail, productId, retailerId, url, body = "", footer = "", buttons = [], priceAmount1000 = null, currencyCode = "IDR" } = content.productMessage;
957
+ let productImage;
958
+ if (Buffer.isBuffer(thumbnail)) {
959
+ const { imageMessage } = await generateWAMessageContent({ image: thumbnail }, { upload: waUploadToServer });
960
+ productImage = imageMessage;
961
+ }
962
+ else if (typeof thumbnail === 'object' && thumbnail?.url) {
963
+ const { imageMessage } = await generateWAMessageContent({ image: { url: thumbnail.url } }, { upload: waUploadToServer });
964
+ productImage = imageMessage;
965
+ }
966
+ const productContent = {
967
+ viewOnceMessage: {
968
+ message: {
969
+ interactiveMessage: {
970
+ body: { text: body },
971
+ footer: { text: footer },
972
+ header: {
973
+ title,
974
+ hasMediaAttachment: true,
975
+ productMessage: {
976
+ product: {
977
+ productImage,
978
+ productId,
979
+ title,
980
+ description,
981
+ currencyCode,
982
+ priceAmount1000,
983
+ retailerId,
984
+ url,
985
+ productImageCount: 1
986
+ },
987
+ businessOwnerJid: "0@s.whatsapp.net"
988
+ }
989
+ },
990
+ nativeFlowMessage: { buttons }
991
+ }
992
+ }
993
+ }
994
+ };
995
+ const msg = await generateWAMessageFromContent(jid, productContent, { quoted });
996
+ await relayMessage(jid, msg.message, {
997
+ messageId: msg.key.id
998
+ });
999
+ return msg;
1000
+ };
1001
+
1002
+ // handleGroupStory() flow (groupStatusMessage -> groupStatusMessageV2).
1003
+ const sendGroupStatusMessage = async (jid, content, quoted) => {
1004
+ const storyData = content.groupStatusMessage;
1005
+ let waMsgContent;
1006
+ if (storyData?.message) {
1007
+ waMsgContent = storyData;
1008
+ }
1009
+ else {
1010
+ waMsgContent = await generateWAMessageContent(storyData, {
1011
+ upload: waUploadToServer
1012
+ });
1013
+ }
1014
+ const msg = {
1015
+ message: {
1016
+ groupStatusMessageV2: {
1017
+ message: waMsgContent.message || waMsgContent
1018
+ }
1019
+ }
1020
+ };
1021
+ return await relayMessage(jid, msg.message, {
1022
+ messageId: generateMessageID()
1023
+ });
1024
+ };
1025
+
1026
+ const getTypeMessage = (msg) => {
1027
+ if (msg?.viewOnceMessage) {
1028
+ return getTypeMessage(msg.viewOnceMessage.message);
1029
+ }
1030
+ else if (msg?.viewOnceMessageV2) {
1031
+ return getTypeMessage(msg.viewOnceMessageV2.message);
1032
+ }
1033
+ else if (msg?.viewOnceMessageV2Extension) {
1034
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
1035
+ }
1036
+ else if (msg?.ephemeralMessage) {
1037
+ return getTypeMessage(msg.ephemeralMessage.message);
1038
+ }
1039
+ else if (msg?.documentWithCaptionMessage) {
1040
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
1041
+ }
1042
+ else if (msg?.reactionMessage) {
1043
+ return 'reaction';
1044
+ }
1045
+ else if (msg?.pollCreationMessage || msg?.pollCreationMessageV2 || msg?.pollCreationMessageV3 || msg?.pollUpdateMessage) {
1046
+ return 'poll';
1047
+ }
1048
+ else if (getMediaType(msg) !== '') {
1049
+ return 'media';
1050
+ }
1051
+ return 'text';
1052
+ };
1053
+ const getMessageType = (message) => {
1054
+ if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
1055
+ return 'poll';
1056
+ }
1057
+ if (message.eventMessage) {
1058
+ return 'event';
1059
+ }
1060
+ if (getMediaType(message) !== '') {
1061
+ return 'media';
1062
+ }
1063
+ return 'text';
1064
+ };
1065
+ const getMediaType = (message) => {
1066
+ if (message.imageMessage) {
1067
+ return 'image';
1068
+ }
1069
+ else if (message.videoMessage) {
1070
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1071
+ }
1072
+ else if (message.audioMessage) {
1073
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1074
+ }
1075
+ else if (message.contactMessage) {
1076
+ return 'vcard';
1077
+ }
1078
+ else if (message.documentMessage) {
1079
+ return 'document';
1080
+ }
1081
+ else if (message.contactsArrayMessage) {
1082
+ return 'contact_array';
1083
+ }
1084
+ else if (message.liveLocationMessage) {
1085
+ return 'livelocation';
1086
+ }
1087
+ else if (message.stickerMessage) {
1088
+ return 'sticker';
1089
+ }
1090
+ else if (message.listMessage) {
1091
+ return 'list';
1092
+ }
1093
+ else if (message.listResponseMessage) {
1094
+ return 'list_response';
1095
+ }
1096
+ else if (message.buttonsResponseMessage) {
1097
+ return 'buttons_response';
1098
+ }
1099
+ else if (message.orderMessage) {
1100
+ return 'order';
1101
+ }
1102
+ else if (message.productMessage) {
1103
+ return 'product';
1104
+ }
1105
+ else if (message.interactiveResponseMessage) {
1106
+ return 'native_flow_response';
1107
+ }
1108
+ else if (message.groupInviteMessage) {
1109
+ return 'url';
1110
+ }
1111
+ return '';
1112
+ };
1113
+ const getPrivacyTokens = async (jids) => {
1114
+ const t = unixTimestampSeconds().toString();
1115
+ const result = await query({
1116
+ tag: 'iq',
1117
+ attrs: {
1118
+ to: S_WHATSAPP_NET,
1119
+ type: 'set',
1120
+ xmlns: 'privacy'
1121
+ },
1122
+ content: [
1123
+ {
1124
+ tag: 'tokens',
1125
+ attrs: {},
1126
+ content: jids.map(jid => ({
1127
+ tag: 'token',
1128
+ attrs: {
1129
+ jid: jidNormalizedUser(jid),
1130
+ t,
1131
+ type: 'trusted_contact'
1132
+ }
1133
+ }))
1134
+ }
1135
+ ]
1136
+ });
1137
+ return result;
1138
+ };
1139
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1140
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1141
+ return {
1142
+ ...sock,
1143
+ getPrivacyTokens,
1144
+ assertSessions,
1145
+ relayMessage,
1146
+ sendReceipt,
1147
+ sendReceipts,
1148
+ readMessages,
1149
+ refreshMediaConn,
1150
+ waUploadToServer,
1151
+ fetchPrivacySettings,
1152
+ sendPeerDataOperationMessage,
1153
+ createParticipantNodes,
1154
+ getUSyncDevices,
1155
+ messageRetryManager,
1156
+ updateMediaMessage: async (message) => {
1157
+ const content = assertMediaContent(message.message);
1158
+ const mediaKey = content.mediaKey;
1159
+ const meId = authState.creds.me.id;
1160
+ const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
1161
+ let error = undefined;
1162
+ await Promise.all([
1163
+ sendNode(node),
1164
+ waitForMsgMediaUpdate(async (update) => {
1165
+ const result = update.find(c => c.key.id === message.key.id);
1166
+ if (result) {
1167
+ if (result.error) {
1168
+ error = result.error;
1169
+ }
1170
+ else {
1171
+ try {
1172
+ const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
1173
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1174
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1175
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1176
+ data: media,
1177
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1178
+ });
1179
+ }
1180
+ content.directPath = media.directPath;
1181
+ content.url = getUrlFromDirectPath(content.directPath);
1182
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1183
+ }
1184
+ catch (err) {
1185
+ error = err;
1186
+ }
1187
+ }
1188
+ return true;
1189
+ }
1190
+ })
1191
+ ]);
1192
+ if (error) {
1193
+ throw error;
1194
+ }
1195
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1196
+ return message;
1197
+ },
1198
+ sendMessage: async (jid, content, options = {}) => {
1199
+ const userJid = authState.creds.me.id;
1200
+ // do not allow per-message ephemeralExpiration overrides here.
1201
+ // (Ephemeral/disappearing settings are handled via protocol/group toggle flows.)
1202
+ delete options.ephemeralExpiration;
1203
+ if (typeof content === 'object' &&
1204
+ 'disappearingMessagesInChat' in content &&
1205
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1206
+ isJidGroup(jid)) {
1207
+ const { disappearingMessagesInChat } = content;
1208
+ const value = typeof disappearingMessagesInChat === 'boolean'
1209
+ ? disappearingMessagesInChat
1210
+ ? WA_DEFAULT_EPHEMERAL
1211
+ : 0
1212
+ : disappearingMessagesInChat;
1213
+ await groupToggleEphemeral(jid, value);
1214
+ }
1215
+ else {
1216
+ if (typeof content === 'object' && content && 'albumMessage' in content && Array.isArray(content.albumMessage)) {
1217
+ return await sendAlbumMessage(jid, content, options.quoted);
1218
+ }
1219
+ if (typeof content === 'object' && content && 'eventMessage' in content && content.eventMessage) {
1220
+ return await sendEventMessage(jid, content, options.quoted);
1221
+ }
1222
+ if (typeof content === 'object' && content && 'pollResultMessage' in content && content.pollResultMessage) {
1223
+ return await sendPollResultMessage(jid, content, options.quoted);
1224
+ }
1225
+ if (typeof content === 'object' && content && 'productMessage' in content && content.productMessage) {
1226
+ return await sendProductMessage(jid, content, options.quoted);
1227
+ }
1228
+ if (typeof content === 'object' && content && 'groupStatusMessage' in content && content.groupStatusMessage) {
1229
+ return await sendGroupStatusMessage(jid, content, options.quoted);
1230
+ }
1231
+ let mediaHandle;
1232
+ const fullMsg = await generateWAMessage(jid, content, {
1233
+ logger,
1234
+ userJid,
1235
+ getUrlInfo: text => getUrlInfo(text, {
1236
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1237
+ fetchOpts: {
1238
+ timeout: 3000,
1239
+ ...(httpRequestOptions || {})
1240
+ },
1241
+ logger,
1242
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1243
+ }),
1244
+ //TODO: CACHE
1245
+ getProfilePicUrl: sock.profilePictureUrl,
1246
+ getCallLink: sock.createCallLink,
1247
+ upload: async (readStream, opts) => {
1248
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: isJidNewsletter(jid) });
1249
+ mediaHandle = up.handle;
1250
+ return up;
1251
+ },
1252
+ mediaCache: config.mediaCache,
1253
+ options: config.options,
1254
+ messageId: generateMessageIDV2(sock.user?.id),
1255
+ ...options
1256
+ });
1257
+ const isEventMsg = 'event' in content && !!content.event;
1258
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1259
+ const isEditMsg = 'edit' in content && !!content.edit;
1260
+ const isPinMsg = 'pin' in content && !!content.pin;
1261
+ const isKeepMsg = 'keep' in content && !!content.keep;
1262
+ const isPollMessage = 'poll' in content && !!content.poll;
1263
+ const isAiMsg = 'ai' in content && !!content.ai;
1264
+ const includeBizNode = (options.includeBizNode === true) || ('biz' in content && !!content.biz);
1265
+ const additionalAttributes = {};
1266
+ const additionalNodes = [];
1267
+ // required for delete
1268
+ if (isDeleteMsg) {
1269
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1270
+ if ((isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) || isJidNewsletter(jid)) {
1271
+ additionalAttributes.edit = '8';
1272
+ }
1273
+ else {
1274
+ additionalAttributes.edit = '7';
1275
+ }
1276
+ }
1277
+ else if (isEditMsg) {
1278
+ additionalAttributes.edit = isJidNewsletter(jid) ? '3' : '1';
1279
+ }
1280
+ else if (isPinMsg) {
1281
+ additionalAttributes.edit = '2';
1282
+ }
1283
+ else if (isKeepMsg) {
1284
+ additionalAttributes.edit = '6';
1285
+ }
1286
+ else if (isPollMessage) {
1287
+ additionalNodes.push({
1288
+ tag: 'meta',
1289
+ attrs: {
1290
+ polltype: 'creation'
1291
+ }
1292
+ });
1293
+ }
1294
+ else if (isEventMsg) {
1295
+ additionalNodes.push({
1296
+ tag: 'meta',
1297
+ attrs: {
1298
+ event_type: 'creation'
1299
+ }
1300
+ });
1301
+ }
1302
+ if (mediaHandle) {
1303
+ additionalAttributes.media_id = mediaHandle;
1304
+ }
1305
+ // AI label injection disabled by local patch.
1306
+ await relayMessage(jid, fullMsg.message, {
1307
+ messageId: fullMsg.key.id,
1308
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1309
+ additionalAttributes,
1310
+ statusJidList: options.statusJidList,
1311
+ additionalNodes,
1312
+ includeBizNode
1313
+ });
1314
+ if (config.emitOwnEvents) {
1315
+ process.nextTick(async () => {
1316
+ await processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1317
+ });
1318
+ }
1319
+ return fullMsg;
1320
+ }
1321
+ }
1322
+ };
1323
+ };
1324
+ //# sourceMappingURL=messages-send.js.map