@itsonlyzenn/baileys 1.1.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 (423) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1312 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +129 -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 +431 -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 +277 -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 +54 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +217 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +379 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +124 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1193 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +273 -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 +161 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +364 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +260 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +12 -0
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +203 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1772 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +199 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1145 -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 +170 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +181 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/socket.d.ts +59 -0
  118. package/lib/Socket/socket.d.ts.map +1 -0
  119. package/lib/Socket/socket.js +967 -0
  120. package/lib/Socket/socket.js.map +1 -0
  121. package/lib/Types/Auth.d.ts +117 -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 +15 -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 +124 -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 +26 -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 +256 -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 +71 -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 +320 -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/Mex.d.ts +141 -0
  162. package/lib/Types/Mex.d.ts.map +1 -0
  163. package/lib/Types/Mex.js +37 -0
  164. package/lib/Types/Mex.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 +87 -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 +136 -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 +97 -0
  178. package/lib/Types/State.d.ts.map +1 -0
  179. package/lib/Types/State.js +56 -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 +24 -0
  190. package/lib/Utils/auth-utils.d.ts.map +1 -0
  191. package/lib/Utils/auth-utils.js +302 -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 +100 -0
  202. package/lib/Utils/chat-utils.d.ts.map +1 -0
  203. package/lib/Utils/chat-utils.js +872 -0
  204. package/lib/Utils/chat-utils.js.map +1 -0
  205. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  206. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  207. package/lib/Utils/companion-reg-client-utils.js +35 -0
  208. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  209. package/lib/Utils/crypto.d.ts +37 -0
  210. package/lib/Utils/crypto.d.ts.map +1 -0
  211. package/lib/Utils/crypto.js +118 -0
  212. package/lib/Utils/crypto.js.map +1 -0
  213. package/lib/Utils/decode-wa-message.d.ts +66 -0
  214. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  215. package/lib/Utils/decode-wa-message.js +311 -0
  216. package/lib/Utils/decode-wa-message.js.map +1 -0
  217. package/lib/Utils/event-buffer.d.ts +36 -0
  218. package/lib/Utils/event-buffer.d.ts.map +1 -0
  219. package/lib/Utils/event-buffer.js +622 -0
  220. package/lib/Utils/event-buffer.js.map +1 -0
  221. package/lib/Utils/generics.d.ts +91 -0
  222. package/lib/Utils/generics.d.ts.map +1 -0
  223. package/lib/Utils/generics.js +393 -0
  224. package/lib/Utils/generics.js.map +1 -0
  225. package/lib/Utils/history.d.ts +24 -0
  226. package/lib/Utils/history.d.ts.map +1 -0
  227. package/lib/Utils/history.js +134 -0
  228. package/lib/Utils/history.js.map +1 -0
  229. package/lib/Utils/identity-change-handler.d.ts +44 -0
  230. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  231. package/lib/Utils/identity-change-handler.js +50 -0
  232. package/lib/Utils/identity-change-handler.js.map +1 -0
  233. package/lib/Utils/index.d.ts +22 -0
  234. package/lib/Utils/index.d.ts.map +1 -0
  235. package/lib/Utils/index.js +22 -0
  236. package/lib/Utils/index.js.map +1 -0
  237. package/lib/Utils/link-preview.d.ts +21 -0
  238. package/lib/Utils/link-preview.d.ts.map +1 -0
  239. package/lib/Utils/link-preview.js +85 -0
  240. package/lib/Utils/link-preview.js.map +1 -0
  241. package/lib/Utils/logger.d.ts +13 -0
  242. package/lib/Utils/logger.d.ts.map +1 -0
  243. package/lib/Utils/logger.js +3 -0
  244. package/lib/Utils/logger.js.map +1 -0
  245. package/lib/Utils/lt-hash.d.ts +8 -0
  246. package/lib/Utils/lt-hash.d.ts.map +1 -0
  247. package/lib/Utils/lt-hash.js +8 -0
  248. package/lib/Utils/lt-hash.js.map +1 -0
  249. package/lib/Utils/make-mutex.d.ts +9 -0
  250. package/lib/Utils/make-mutex.d.ts.map +1 -0
  251. package/lib/Utils/make-mutex.js +33 -0
  252. package/lib/Utils/make-mutex.js.map +1 -0
  253. package/lib/Utils/message-retry-manager.d.ts +115 -0
  254. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  255. package/lib/Utils/message-retry-manager.js +265 -0
  256. package/lib/Utils/message-retry-manager.js.map +1 -0
  257. package/lib/Utils/messages-media.d.ts +133 -0
  258. package/lib/Utils/messages-media.d.ts.map +1 -0
  259. package/lib/Utils/messages-media.js +786 -0
  260. package/lib/Utils/messages-media.js.map +1 -0
  261. package/lib/Utils/messages.d.ts +91 -0
  262. package/lib/Utils/messages.d.ts.map +1 -0
  263. package/lib/Utils/messages.js +893 -0
  264. package/lib/Utils/messages.js.map +1 -0
  265. package/lib/Utils/noise-handler.d.ts +20 -0
  266. package/lib/Utils/noise-handler.d.ts.map +1 -0
  267. package/lib/Utils/noise-handler.js +201 -0
  268. package/lib/Utils/noise-handler.js.map +1 -0
  269. package/lib/Utils/offline-node-processor.d.ts +17 -0
  270. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  271. package/lib/Utils/offline-node-processor.js +40 -0
  272. package/lib/Utils/offline-node-processor.js.map +1 -0
  273. package/lib/Utils/pre-key-manager.d.ts +28 -0
  274. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  275. package/lib/Utils/pre-key-manager.js +106 -0
  276. package/lib/Utils/pre-key-manager.js.map +1 -0
  277. package/lib/Utils/process-message.d.ts +60 -0
  278. package/lib/Utils/process-message.d.ts.map +1 -0
  279. package/lib/Utils/process-message.js +597 -0
  280. package/lib/Utils/process-message.js.map +1 -0
  281. package/lib/Utils/reporting-utils.d.ts +11 -0
  282. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  283. package/lib/Utils/reporting-utils.js +258 -0
  284. package/lib/Utils/reporting-utils.js.map +1 -0
  285. package/lib/Utils/signal.d.ts +47 -0
  286. package/lib/Utils/signal.d.ts.map +1 -0
  287. package/lib/Utils/signal.js +201 -0
  288. package/lib/Utils/signal.js.map +1 -0
  289. package/lib/Utils/stanza-ack.d.ts +11 -0
  290. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  291. package/lib/Utils/stanza-ack.js +38 -0
  292. package/lib/Utils/stanza-ack.js.map +1 -0
  293. package/lib/Utils/sync-action-utils.d.ts +19 -0
  294. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  295. package/lib/Utils/sync-action-utils.js +49 -0
  296. package/lib/Utils/sync-action-utils.js.map +1 -0
  297. package/lib/Utils/tc-token-utils.d.ts +37 -0
  298. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  299. package/lib/Utils/tc-token-utils.js +163 -0
  300. package/lib/Utils/tc-token-utils.js.map +1 -0
  301. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  302. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  303. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  304. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  305. package/lib/Utils/validate-connection.d.ts +11 -0
  306. package/lib/Utils/validate-connection.d.ts.map +1 -0
  307. package/lib/Utils/validate-connection.js +203 -0
  308. package/lib/Utils/validate-connection.js.map +1 -0
  309. package/lib/WABinary/constants.d.ts +28 -0
  310. package/lib/WABinary/constants.d.ts.map +1 -0
  311. package/lib/WABinary/constants.js +1301 -0
  312. package/lib/WABinary/constants.js.map +1 -0
  313. package/lib/WABinary/decode.d.ts +7 -0
  314. package/lib/WABinary/decode.d.ts.map +1 -0
  315. package/lib/WABinary/decode.js +262 -0
  316. package/lib/WABinary/decode.js.map +1 -0
  317. package/lib/WABinary/encode.d.ts +3 -0
  318. package/lib/WABinary/encode.d.ts.map +1 -0
  319. package/lib/WABinary/encode.js +220 -0
  320. package/lib/WABinary/encode.js.map +1 -0
  321. package/lib/WABinary/generic-utils.d.ts +15 -0
  322. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  323. package/lib/WABinary/generic-utils.js +113 -0
  324. package/lib/WABinary/generic-utils.js.map +1 -0
  325. package/lib/WABinary/index.d.ts +6 -0
  326. package/lib/WABinary/index.d.ts.map +1 -0
  327. package/lib/WABinary/index.js +6 -0
  328. package/lib/WABinary/index.js.map +1 -0
  329. package/lib/WABinary/jid-utils.d.ts +48 -0
  330. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  331. package/lib/WABinary/jid-utils.js +96 -0
  332. package/lib/WABinary/jid-utils.js.map +1 -0
  333. package/lib/WABinary/types.d.ts +19 -0
  334. package/lib/WABinary/types.d.ts.map +1 -0
  335. package/lib/WABinary/types.js +2 -0
  336. package/lib/WABinary/types.js.map +1 -0
  337. package/lib/WAM/BinaryInfo.d.ts +9 -0
  338. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  339. package/lib/WAM/BinaryInfo.js +10 -0
  340. package/lib/WAM/BinaryInfo.js.map +1 -0
  341. package/lib/WAM/constants.d.ts +40 -0
  342. package/lib/WAM/constants.d.ts.map +1 -0
  343. package/lib/WAM/constants.js +22853 -0
  344. package/lib/WAM/constants.js.map +1 -0
  345. package/lib/WAM/encode.d.ts +3 -0
  346. package/lib/WAM/encode.d.ts.map +1 -0
  347. package/lib/WAM/encode.js +150 -0
  348. package/lib/WAM/encode.js.map +1 -0
  349. package/lib/WAM/index.d.ts +4 -0
  350. package/lib/WAM/index.d.ts.map +1 -0
  351. package/lib/WAM/index.js +4 -0
  352. package/lib/WAM/index.js.map +1 -0
  353. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  354. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  355. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  356. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  357. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  358. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  360. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  362. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  364. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  366. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  368. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  370. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  372. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  374. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  378. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  382. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/index.js +6 -0
  384. package/lib/WAUSync/Protocols/index.js.map +1 -0
  385. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  386. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  387. package/lib/WAUSync/USyncQuery.js +98 -0
  388. package/lib/WAUSync/USyncQuery.js.map +1 -0
  389. package/lib/WAUSync/USyncUser.d.ts +17 -0
  390. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncUser.js +31 -0
  392. package/lib/WAUSync/USyncUser.js.map +1 -0
  393. package/lib/WAUSync/index.d.ts +4 -0
  394. package/lib/WAUSync/index.d.ts.map +1 -0
  395. package/lib/WAUSync/index.js +4 -0
  396. package/lib/WAUSync/index.js.map +1 -0
  397. package/lib/index.d.ts +12 -0
  398. package/lib/index.d.ts.map +1 -0
  399. package/lib/index.js +17 -0
  400. package/lib/index.js.map +1 -0
  401. package/lib/libsignal-patched/LICENSE +621 -0
  402. package/lib/libsignal-patched/README.md +64 -0
  403. package/lib/libsignal-patched/index.d.ts +55 -0
  404. package/lib/libsignal-patched/index.js +8 -0
  405. package/lib/libsignal-patched/package.json +34 -0
  406. package/lib/libsignal-patched/src/.eslintrc.json +31 -0
  407. package/lib/libsignal-patched/src/WhisperTextProtocol.js +933 -0
  408. package/lib/libsignal-patched/src/base_key_type.js +7 -0
  409. package/lib/libsignal-patched/src/chain_type.js +6 -0
  410. package/lib/libsignal-patched/src/crypto.d.ts +19 -0
  411. package/lib/libsignal-patched/src/crypto.js +98 -0
  412. package/lib/libsignal-patched/src/curve.d.ts +22 -0
  413. package/lib/libsignal-patched/src/curve.js +142 -0
  414. package/lib/libsignal-patched/src/errors.js +33 -0
  415. package/lib/libsignal-patched/src/keyhelper.js +45 -0
  416. package/lib/libsignal-patched/src/numeric_fingerprint.js +72 -0
  417. package/lib/libsignal-patched/src/protobufs.js +10 -0
  418. package/lib/libsignal-patched/src/protocol_address.js +40 -0
  419. package/lib/libsignal-patched/src/queue_job.js +69 -0
  420. package/lib/libsignal-patched/src/session_builder.js +164 -0
  421. package/lib/libsignal-patched/src/session_cipher.js +336 -0
  422. package/lib/libsignal-patched/src/session_record.js +315 -0
  423. package/package.json +138 -0
@@ -0,0 +1,1145 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
6
+ import { getUrlInfo } from '../Utils/link-preview.js';
7
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
+ import { makeNewsletterSocket } from './newsletter.js';
13
+ export const makeMessagesSocket = (config) => {
14
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
15
+ const sock = makeNewsletterSocket(config);
16
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
17
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
+ /**
19
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
20
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
21
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
22
+ */
23
+ const inFlightTcTokenIssuance = new Set();
24
+ const userDevicesCache = config.userDevicesCache ||
25
+ new NodeCache({
26
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
27
+ useClones: false
28
+ });
29
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
30
+ const devicesMutex = makeMutex();
31
+ // Initialize message retry manager if enabled
32
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
+ // Prevent race conditions in Signal session encryption by user
34
+ const encryptionMutex = makeKeyedMutex();
35
+ let mediaConn;
36
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
37
+ let mediaHost = DEF_MEDIA_HOST;
38
+ const refreshMediaConn = async (forceGet = false) => {
39
+ const media = await mediaConn;
40
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
41
+ mediaConn = (async () => {
42
+ const result = await query({
43
+ tag: 'iq',
44
+ attrs: {
45
+ type: 'set',
46
+ xmlns: 'w:m',
47
+ to: S_WHATSAPP_NET
48
+ },
49
+ content: [{ tag: 'media_conn', attrs: {} }]
50
+ });
51
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
52
+ // TODO: explore full length of data that whatsapp provides
53
+ const node = {
54
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
55
+ hostname: attrs.hostname,
56
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
57
+ })),
58
+ auth: mediaConnNode.attrs.auth,
59
+ ttl: +mediaConnNode.attrs.ttl,
60
+ fetchDate: new Date()
61
+ };
62
+ logger.debug('fetched media conn');
63
+ if (node.hosts[0]) {
64
+ mediaHost = node.hosts[0].hostname;
65
+ }
66
+ return node;
67
+ })();
68
+ }
69
+ return mediaConn;
70
+ };
71
+ /**
72
+ * generic send receipt function
73
+ * used for receipts of phone call, read, delivery etc.
74
+ * */
75
+ const sendReceipt = async (jid, participant, messageIds, type) => {
76
+ if (!messageIds || messageIds.length === 0) {
77
+ throw new Boom('missing ids in receipt');
78
+ }
79
+ const node = {
80
+ tag: 'receipt',
81
+ attrs: {
82
+ id: messageIds[0]
83
+ }
84
+ };
85
+ const isReadReceipt = type === 'read' || type === 'read-self';
86
+ if (isReadReceipt) {
87
+ node.attrs.t = unixTimestampSeconds().toString();
88
+ }
89
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
90
+ node.attrs.recipient = jid;
91
+ node.attrs.to = participant;
92
+ }
93
+ else {
94
+ node.attrs.to = jid;
95
+ if (participant) {
96
+ node.attrs.participant = participant;
97
+ }
98
+ }
99
+ if (type) {
100
+ node.attrs.type = type;
101
+ }
102
+ const remainingMessageIds = messageIds.slice(1);
103
+ if (remainingMessageIds.length) {
104
+ node.content = [
105
+ {
106
+ tag: 'list',
107
+ attrs: {},
108
+ content: remainingMessageIds.map(id => ({
109
+ tag: 'item',
110
+ attrs: { id }
111
+ }))
112
+ }
113
+ ];
114
+ }
115
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
116
+ await sendNode(node);
117
+ };
118
+ /** Correctly bulk send receipts to multiple chats, participants */
119
+ const sendReceipts = async (keys, type) => {
120
+ const recps = aggregateMessageKeysNotFromMe(keys);
121
+ for (const { jid, participant, messageIds } of recps) {
122
+ await sendReceipt(jid, participant, messageIds, type);
123
+ }
124
+ };
125
+ /** Bulk read messages. Keys can be from different chats & participants */
126
+ const readMessages = async (keys) => {
127
+ const privacySettings = await fetchPrivacySettings();
128
+ // based on privacy settings, we have to change the read type
129
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
130
+ await sendReceipts(keys, readType);
131
+ };
132
+ /** Fetch all the devices we've to send a message to */
133
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
134
+ const deviceResults = [];
135
+ if (!useCache) {
136
+ logger.debug('not using cache for devices');
137
+ }
138
+ const toFetch = [];
139
+ const jidsWithUser = jids
140
+ .map(jid => {
141
+ const decoded = jidDecode(jid);
142
+ const user = decoded?.user;
143
+ const device = decoded?.device;
144
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
145
+ if (isExplicitDevice && user) {
146
+ deviceResults.push({
147
+ user,
148
+ device,
149
+ jid
150
+ });
151
+ return null;
152
+ }
153
+ jid = jidNormalizedUser(jid);
154
+ return { jid, user };
155
+ })
156
+ .filter(jid => jid !== null);
157
+ let mgetDevices;
158
+ if (useCache && userDevicesCache.mget) {
159
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
160
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
161
+ }
162
+ for (const { jid, user } of jidsWithUser) {
163
+ if (useCache) {
164
+ const devices = mgetDevices?.[user] ||
165
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
166
+ if (devices) {
167
+ const devicesWithJid = devices.map(d => ({
168
+ ...d,
169
+ jid: jidEncode(d.user, d.server, d.device)
170
+ }));
171
+ deviceResults.push(...devicesWithJid);
172
+ logger.trace({ user }, 'using cache for devices');
173
+ }
174
+ else {
175
+ toFetch.push(jid);
176
+ }
177
+ }
178
+ else {
179
+ toFetch.push(jid);
180
+ }
181
+ }
182
+ if (!toFetch.length) {
183
+ return deviceResults;
184
+ }
185
+ const requestedLidUsers = new Set();
186
+ for (const jid of toFetch) {
187
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
188
+ const user = jidDecode(jid)?.user;
189
+ if (user)
190
+ requestedLidUsers.add(user);
191
+ }
192
+ }
193
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
194
+ for (const jid of toFetch) {
195
+ 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
196
+ }
197
+ const result = await sock.executeUSyncQuery(query);
198
+ if (result) {
199
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
200
+ const lidResults = result.list.filter(a => !!a.lid);
201
+ if (lidResults.length > 0) {
202
+ logger.trace('Storing LID maps from device call');
203
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
204
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
205
+ try {
206
+ const lids = lidResults.map(a => a.lid);
207
+ if (lids.length) {
208
+ await assertSessions(lids, true);
209
+ }
210
+ }
211
+ catch (e) {
212
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
213
+ }
214
+ }
215
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
216
+ const deviceMap = {};
217
+ for (const item of extracted) {
218
+ deviceMap[item.user] = deviceMap[item.user] || [];
219
+ deviceMap[item.user]?.push(item);
220
+ }
221
+ // Process each user's devices as a group for bulk LID migration
222
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
223
+ const isLidUser = requestedLidUsers.has(user);
224
+ // Process all devices for this user
225
+ for (const item of userDevices) {
226
+ const finalJid = isLidUser
227
+ ? jidEncode(user, item.server, item.device)
228
+ : jidEncode(item.user, item.server, item.device);
229
+ deviceResults.push({
230
+ ...item,
231
+ jid: finalJid
232
+ });
233
+ logger.debug({
234
+ user: item.user,
235
+ device: item.device,
236
+ finalJid,
237
+ usedLid: isLidUser
238
+ }, 'Processed device with LID priority');
239
+ }
240
+ }
241
+ await devicesMutex.mutex(async () => {
242
+ if (userDevicesCache.mset) {
243
+ // if the cache supports mset, we can set all devices in one go
244
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
245
+ }
246
+ else {
247
+ for (const key in deviceMap) {
248
+ if (deviceMap[key])
249
+ await userDevicesCache.set(key, deviceMap[key]);
250
+ }
251
+ }
252
+ });
253
+ const userDeviceUpdates = {};
254
+ for (const [userId, devices] of Object.entries(deviceMap)) {
255
+ if (devices && devices.length > 0) {
256
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
257
+ }
258
+ }
259
+ if (Object.keys(userDeviceUpdates).length > 0) {
260
+ try {
261
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
262
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
263
+ }
264
+ catch (error) {
265
+ logger.warn({ error }, 'failed to store user device lists');
266
+ }
267
+ }
268
+ }
269
+ return deviceResults;
270
+ };
271
+ /**
272
+ * Update Member Label
273
+ */
274
+ const updateMemberLabel = (jid, memberLabel) => {
275
+ return relayMessage(jid, {
276
+ protocolMessage: {
277
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
278
+ memberLabel: {
279
+ label: memberLabel?.slice(0, 30),
280
+ labelTimestamp: unixTimestampSeconds()
281
+ }
282
+ }
283
+ }, {
284
+ additionalNodes: [
285
+ {
286
+ tag: 'meta',
287
+ attrs: {
288
+ tag_reason: 'user_update',
289
+ appdata: 'member_tag'
290
+ },
291
+ content: undefined
292
+ }
293
+ ]
294
+ });
295
+ };
296
+ const assertSessions = async (jids, force) => {
297
+ let didFetchNewSession = false;
298
+ const uniqueJids = [...new Set(jids)];
299
+ const jidsRequiringFetch = [];
300
+ logger.debug({ jids }, 'assertSessions call with jids');
301
+ for (const jid of uniqueJids) {
302
+ if (!force) {
303
+ const sessionValidation = await signalRepository.validateSession(jid);
304
+ if (sessionValidation.exists) {
305
+ continue;
306
+ }
307
+ }
308
+ jidsRequiringFetch.push(jid);
309
+ }
310
+ if (jidsRequiringFetch.length) {
311
+ // LID if mapped, otherwise original
312
+ const wireJids = [
313
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
314
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
315
+ ];
316
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
317
+ const result = await query({
318
+ tag: 'iq',
319
+ attrs: {
320
+ xmlns: 'encrypt',
321
+ type: 'get',
322
+ to: S_WHATSAPP_NET
323
+ },
324
+ content: [
325
+ {
326
+ tag: 'key',
327
+ attrs: {},
328
+ content: wireJids.map(jid => {
329
+ const attrs = { jid };
330
+ if (force)
331
+ attrs.reason = 'identity';
332
+ return { tag: 'user', attrs };
333
+ })
334
+ }
335
+ ]
336
+ });
337
+ await parseAndInjectE2ESessions(result, signalRepository);
338
+ didFetchNewSession = true;
339
+ }
340
+ return didFetchNewSession;
341
+ };
342
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
343
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
344
+ if (!authState.creds.me?.id) {
345
+ throw new Boom('Not authenticated');
346
+ }
347
+ const protocolMessage = {
348
+ protocolMessage: {
349
+ peerDataOperationRequestMessage: pdoMessage,
350
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
351
+ }
352
+ };
353
+ const meJid = jidNormalizedUser(authState.creds.me.id);
354
+ const msgId = await relayMessage(meJid, protocolMessage, {
355
+ additionalAttributes: {
356
+ category: 'peer',
357
+ push_priority: 'high_force'
358
+ },
359
+ additionalNodes: [
360
+ {
361
+ tag: 'meta',
362
+ attrs: { appdata: 'default' }
363
+ }
364
+ ]
365
+ });
366
+ return msgId;
367
+ };
368
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
369
+ if (!recipientJids.length) {
370
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
371
+ }
372
+ const patched = await patchMessageBeforeSending(message, recipientJids);
373
+ const patchedMessages = Array.isArray(patched)
374
+ ? patched
375
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
376
+ let shouldIncludeDeviceIdentity = false;
377
+ const meId = authState.creds.me.id;
378
+ const meLid = authState.creds.me?.lid;
379
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
380
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
381
+ try {
382
+ if (!jid)
383
+ return null;
384
+ let msgToEncrypt = patchedMessage;
385
+ if (dsmMessage) {
386
+ const { user: targetUser } = jidDecode(jid);
387
+ const { user: ownPnUser } = jidDecode(meId);
388
+ const ownLidUser = meLidUser;
389
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
390
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
391
+ if (isOwnUser && !isExactSenderDevice) {
392
+ msgToEncrypt = dsmMessage;
393
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
394
+ }
395
+ }
396
+ const bytes = encodeWAMessage(msgToEncrypt);
397
+ const mutexKey = jid;
398
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
399
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
400
+ if (type === 'pkmsg') {
401
+ shouldIncludeDeviceIdentity = true;
402
+ }
403
+ return {
404
+ tag: 'to',
405
+ attrs: { jid },
406
+ content: [
407
+ {
408
+ tag: 'enc',
409
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
410
+ content: ciphertext
411
+ }
412
+ ]
413
+ };
414
+ });
415
+ return node;
416
+ }
417
+ catch (err) {
418
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
419
+ return null;
420
+ }
421
+ });
422
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
423
+ if (recipientJids.length > 0 && nodes.length === 0) {
424
+ throw new Boom('All encryptions failed', { statusCode: 500 });
425
+ }
426
+ return { nodes, shouldIncludeDeviceIdentity };
427
+ };
428
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
429
+ const meId = assertMeId(authState.creds);
430
+ const meLid = authState.creds.me?.lid;
431
+ const isRetryResend = Boolean(participant?.jid);
432
+ let shouldIncludeDeviceIdentity = isRetryResend;
433
+ const statusJid = 'status@broadcast';
434
+ const { user, server } = jidDecode(jid);
435
+ const isGroup = server === 'g.us';
436
+ const isStatus = jid === statusJid;
437
+ const isLid = server === 'lid';
438
+ const isNewsletter = server === 'newsletter';
439
+ const isGroupOrStatus = isGroup || isStatus;
440
+ const finalJid = jid;
441
+ msgId = msgId || generateMessageIDV2(meId);
442
+ useUserDevicesCache = useUserDevicesCache !== false;
443
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
444
+ const participants = [];
445
+ const destinationJid = !isStatus ? finalJid : statusJid;
446
+ const binaryNodeContent = [];
447
+ const devices = [];
448
+ let reportingMessage;
449
+ const meMsg = {
450
+ deviceSentMessage: {
451
+ destinationJid,
452
+ message
453
+ },
454
+ messageContextInfo: message.messageContextInfo
455
+ };
456
+ const extraAttrs = {};
457
+ if (participant) {
458
+ if (!isGroup && !isStatus) {
459
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
460
+ }
461
+ const { user, device } = jidDecode(participant.jid);
462
+ devices.push({
463
+ user,
464
+ device,
465
+ jid: participant.jid
466
+ });
467
+ }
468
+ await authState.keys.transaction(async () => {
469
+ const mediaType = getMediaType(message);
470
+ if (mediaType) {
471
+ extraAttrs['mediatype'] = mediaType;
472
+ }
473
+ if (isNewsletter) {
474
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
475
+ const bytes = encodeNewsletterMessage(patched);
476
+ binaryNodeContent.push({
477
+ tag: 'plaintext',
478
+ attrs: {},
479
+ content: bytes
480
+ });
481
+ const stanza = {
482
+ tag: 'message',
483
+ attrs: {
484
+ to: jid,
485
+ id: msgId,
486
+ type: getMessageType(message),
487
+ ...(additionalAttributes || {})
488
+ },
489
+ content: binaryNodeContent
490
+ };
491
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
492
+ await sendNode(stanza);
493
+ return;
494
+ }
495
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
496
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
497
+ }
498
+ if (isGroupOrStatus && !isRetryResend) {
499
+ const [groupData, senderKeyMap] = await Promise.all([
500
+ (async () => {
501
+ 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?
502
+ if (groupData && Array.isArray(groupData?.participants)) {
503
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
504
+ }
505
+ else if (!isStatus) {
506
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
507
+ }
508
+ return groupData;
509
+ })(),
510
+ (async () => {
511
+ if (!participant && !isStatus) {
512
+ // what if sender memory is less accurate than the cached metadata
513
+ // on participant change in group, we should do sender memory manipulation
514
+ 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?
515
+ return result[jid] || {};
516
+ }
517
+ return {};
518
+ })()
519
+ ]);
520
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
521
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
522
+ additionalAttributes = {
523
+ ...additionalAttributes,
524
+ expiration: groupData.ephemeralDuration.toString()
525
+ };
526
+ }
527
+ if (isStatus && statusJidList) {
528
+ participantsList.push(...statusJidList);
529
+ }
530
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
531
+ devices.push(...additionalDevices);
532
+ if (isGroup) {
533
+ additionalAttributes = {
534
+ ...additionalAttributes,
535
+ addressing_mode: groupData?.addressingMode || 'lid'
536
+ };
537
+ }
538
+ const patched = await patchMessageBeforeSending(message);
539
+ if (Array.isArray(patched)) {
540
+ throw new Boom('Per-jid patching is not supported in groups');
541
+ }
542
+ const bytes = encodeWAMessage(patched);
543
+ reportingMessage = patched;
544
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
545
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
546
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
547
+ group: destinationJid,
548
+ data: bytes,
549
+ meId: groupSenderIdentity
550
+ });
551
+ const senderKeyRecipients = [];
552
+ for (const device of devices) {
553
+ const deviceJid = device.jid;
554
+ const hasKey = !!senderKeyMap[deviceJid];
555
+ if ((!hasKey || !!participant) &&
556
+ !isHostedLidUser(deviceJid) &&
557
+ !isHostedPnUser(deviceJid) &&
558
+ device.device !== 99) {
559
+ //todo: revamp all this logic
560
+ // 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
561
+ senderKeyRecipients.push(deviceJid);
562
+ senderKeyMap[deviceJid] = true;
563
+ }
564
+ }
565
+ if (senderKeyRecipients.length) {
566
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
567
+ const senderKeyMsg = {
568
+ senderKeyDistributionMessage: {
569
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
570
+ groupId: destinationJid
571
+ }
572
+ };
573
+ const senderKeySessionTargets = senderKeyRecipients;
574
+ await assertSessions(senderKeySessionTargets);
575
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
576
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
577
+ participants.push(...result.nodes);
578
+ }
579
+ binaryNodeContent.push({
580
+ tag: 'enc',
581
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
582
+ content: ciphertext
583
+ });
584
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
585
+ }
586
+ else {
587
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
588
+ // TODO: investigate if this is true
589
+ let ownId = meId;
590
+ if (isLid && meLid) {
591
+ ownId = meLid;
592
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
593
+ }
594
+ else {
595
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
596
+ }
597
+ const { user: ownUser } = jidDecode(ownId);
598
+ if (!participant) {
599
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
600
+ reportingMessage = Array.isArray(patchedForReporting)
601
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
602
+ : patchedForReporting;
603
+ }
604
+ if (!isRetryResend) {
605
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
606
+ devices.push({
607
+ user,
608
+ device: 0,
609
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
610
+ });
611
+ if (user !== ownUser) {
612
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
613
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
614
+ devices.push({
615
+ user: ownUserForAddressing,
616
+ device: 0,
617
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
618
+ });
619
+ }
620
+ if (additionalAttributes?.['category'] !== 'peer') {
621
+ // Clear placeholders and enumerate actual devices
622
+ devices.length = 0;
623
+ // Use conversation-appropriate sender identity
624
+ const senderIdentity = isLid && meLid
625
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
626
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
627
+ // Enumerate devices for sender and target with consistent addressing
628
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
629
+ devices.push(...sessionDevices);
630
+ logger.debug({
631
+ deviceCount: devices.length,
632
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
633
+ }, 'Device enumeration complete with unified addressing');
634
+ }
635
+ }
636
+ const allRecipients = [];
637
+ const meRecipients = [];
638
+ const otherRecipients = [];
639
+ const { user: mePnUser } = jidDecode(meId);
640
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
641
+ for (const { user, jid } of devices) {
642
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
643
+ if (isExactSenderDevice) {
644
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
645
+ continue;
646
+ }
647
+ // Check if this is our device (could match either PN or LID user)
648
+ const isMe = user === mePnUser || user === meLidUser;
649
+ if (isMe) {
650
+ meRecipients.push(jid);
651
+ }
652
+ else {
653
+ otherRecipients.push(jid);
654
+ }
655
+ allRecipients.push(jid);
656
+ }
657
+ await assertSessions(allRecipients);
658
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
659
+ // For own devices: use DSM if available (1:1 chats only)
660
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
661
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
662
+ ]);
663
+ participants.push(...meNodes);
664
+ participants.push(...otherNodes);
665
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
666
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
667
+ }
668
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
669
+ }
670
+ if (isRetryResend) {
671
+ const isParticipantLid = isLidUser(participant.jid);
672
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
673
+ let messageToSend = message;
674
+ if (isGroupOrStatus) {
675
+ let groupSenderIdentity;
676
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
677
+ groupSenderIdentity = meLid;
678
+ }
679
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
680
+ groupSenderIdentity = meId;
681
+ }
682
+ if (groupSenderIdentity) {
683
+ try {
684
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
685
+ group: destinationJid,
686
+ meId: groupSenderIdentity
687
+ });
688
+ messageToSend = {
689
+ ...message,
690
+ senderKeyDistributionMessage: {
691
+ groupId: destinationJid,
692
+ axolotlSenderKeyDistributionMessage: skdm
693
+ }
694
+ };
695
+ }
696
+ catch (err) {
697
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
698
+ }
699
+ }
700
+ }
701
+ const encodedMessageToSend = isMe
702
+ ? encodeWAMessage({
703
+ deviceSentMessage: {
704
+ destinationJid,
705
+ message: messageToSend
706
+ }
707
+ })
708
+ : encodeWAMessage(messageToSend);
709
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
710
+ data: encodedMessageToSend,
711
+ jid: participant.jid
712
+ });
713
+ binaryNodeContent.push({
714
+ tag: 'enc',
715
+ attrs: {
716
+ v: '2',
717
+ type,
718
+ count: participant.count.toString()
719
+ },
720
+ content: encryptedContent
721
+ });
722
+ }
723
+ if (participants.length) {
724
+ if (additionalAttributes?.['category'] === 'peer') {
725
+ const peerNode = participants[0]?.content?.[0];
726
+ if (peerNode) {
727
+ binaryNodeContent.push(peerNode); // push only enc
728
+ }
729
+ }
730
+ else {
731
+ binaryNodeContent.push({
732
+ tag: 'participants',
733
+ attrs: {},
734
+ content: participants
735
+ });
736
+ }
737
+ }
738
+ const stanza = {
739
+ tag: 'message',
740
+ attrs: {
741
+ id: msgId,
742
+ to: destinationJid,
743
+ type: getMessageType(message),
744
+ ...(additionalAttributes || {})
745
+ },
746
+ content: binaryNodeContent
747
+ };
748
+ // if the participant to send to is explicitly specified (generally retry recp)
749
+ // ensure the message is only sent to that person
750
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
751
+ if (participant) {
752
+ if (isJidGroup(destinationJid)) {
753
+ stanza.attrs.to = destinationJid;
754
+ stanza.attrs.participant = participant.jid;
755
+ }
756
+ else if (areJidsSameUser(participant.jid, meId)) {
757
+ stanza.attrs.to = participant.jid;
758
+ stanza.attrs.recipient = destinationJid;
759
+ }
760
+ else {
761
+ stanza.attrs.to = participant.jid;
762
+ }
763
+ }
764
+ else {
765
+ stanza.attrs.to = destinationJid;
766
+ }
767
+ if (shouldIncludeDeviceIdentity) {
768
+ ;
769
+ stanza.content.push({
770
+ tag: 'device-identity',
771
+ attrs: {},
772
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
773
+ });
774
+ logger.debug({ jid }, 'adding device identity');
775
+ }
776
+ if (!isNewsletter &&
777
+ !isRetryResend &&
778
+ reportingMessage?.messageContextInfo?.messageSecret &&
779
+ shouldIncludeReportingToken(reportingMessage)) {
780
+ try {
781
+ const encoded = encodeWAMessage(reportingMessage);
782
+ const reportingKey = {
783
+ id: msgId,
784
+ fromMe: true,
785
+ remoteJid: destinationJid,
786
+ participant: participant?.jid
787
+ };
788
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
789
+ if (reportingNode) {
790
+ ;
791
+ stanza.content.push(reportingNode);
792
+ logger.trace({ jid }, 'added reporting token to message');
793
+ }
794
+ }
795
+ catch (error) {
796
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
797
+ }
798
+ }
799
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
800
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
801
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
802
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
803
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
804
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
805
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
806
+ let tcTokenBuffer = existingTokenEntry?.token;
807
+ // Treat expired tokens the same as missing — clear from cache
808
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
809
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
810
+ tcTokenBuffer = undefined;
811
+ // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
812
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
813
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
814
+ : null;
815
+ try {
816
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
817
+ }
818
+ catch (err) {
819
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
820
+ }
821
+ }
822
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
823
+ ;
824
+ stanza.content.push({
825
+ tag: 'tctoken',
826
+ attrs: {},
827
+ content: tcTokenBuffer
828
+ });
829
+ }
830
+ if (additionalNodes && additionalNodes.length > 0) {
831
+ ;
832
+ stanza.content.push(...additionalNodes);
833
+ }
834
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
835
+ await sendNode(stanza);
836
+ // Fire-and-forget: issue our token to the contact AFTER message send.
837
+ // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
838
+ const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
839
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
840
+ if (is1on1Send &&
841
+ !isProtocolMsg &&
842
+ !isBotOrPSA &&
843
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
844
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
845
+ inFlightTcTokenIssuance.add(tcTokenJid);
846
+ const issueTimestamp = unixTimestampSeconds();
847
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
848
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
849
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
850
+ .then(async (result) => {
851
+ await storeTcTokensFromIqResult({
852
+ result,
853
+ fallbackJid: tcTokenJid,
854
+ keys: authState.keys,
855
+ getLIDForPN
856
+ });
857
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
858
+ const currentEntry = currentData[tcTokenJid];
859
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
860
+ await authState.keys.set({
861
+ tctoken: {
862
+ [tcTokenJid]: {
863
+ token: Buffer.alloc(0),
864
+ ...currentEntry,
865
+ senderTimestamp: issueTimestamp
866
+ },
867
+ ...indexWrite
868
+ }
869
+ });
870
+ })
871
+ .catch(err => {
872
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
873
+ })
874
+ .finally(() => {
875
+ inFlightTcTokenIssuance.delete(tcTokenJid);
876
+ });
877
+ }
878
+ // Add message to retry cache if enabled
879
+ if (messageRetryManager && !participant) {
880
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
881
+ }
882
+ }, meId);
883
+ return msgId;
884
+ };
885
+ const getMessageType = (message) => {
886
+ const normalizedMessage = normalizeMessageContent(message);
887
+ if (!normalizedMessage)
888
+ return 'text';
889
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
890
+ return 'reaction';
891
+ }
892
+ if (normalizedMessage.pollCreationMessage ||
893
+ normalizedMessage.pollCreationMessageV2 ||
894
+ normalizedMessage.pollCreationMessageV3 ||
895
+ normalizedMessage.pollUpdateMessage) {
896
+ return 'poll';
897
+ }
898
+ if (normalizedMessage.eventMessage) {
899
+ return 'event';
900
+ }
901
+ if (getMediaType(normalizedMessage) !== '') {
902
+ return 'media';
903
+ }
904
+ return 'text';
905
+ };
906
+ const getMediaType = (message) => {
907
+ if (message.imageMessage) {
908
+ return 'image';
909
+ }
910
+ else if (message.videoMessage) {
911
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
912
+ }
913
+ else if (message.audioMessage) {
914
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
915
+ }
916
+ else if (message.contactMessage) {
917
+ return 'vcard';
918
+ }
919
+ else if (message.documentMessage) {
920
+ return 'document';
921
+ }
922
+ else if (message.contactsArrayMessage) {
923
+ return 'contact_array';
924
+ }
925
+ else if (message.liveLocationMessage) {
926
+ return 'livelocation';
927
+ }
928
+ else if (message.stickerMessage) {
929
+ return 'sticker';
930
+ }
931
+ else if (message.listMessage) {
932
+ return 'list';
933
+ }
934
+ else if (message.listResponseMessage) {
935
+ return 'list_response';
936
+ }
937
+ else if (message.buttonsResponseMessage) {
938
+ return 'buttons_response';
939
+ }
940
+ else if (message.orderMessage) {
941
+ return 'order';
942
+ }
943
+ else if (message.productMessage) {
944
+ return 'product';
945
+ }
946
+ else if (message.interactiveResponseMessage) {
947
+ return 'native_flow_response';
948
+ }
949
+ else if (message.groupInviteMessage) {
950
+ return 'url';
951
+ }
952
+ return '';
953
+ };
954
+ const issuePrivacyTokens = async (jids, timestamp) => {
955
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
956
+ const result = await query({
957
+ tag: 'iq',
958
+ attrs: {
959
+ to: S_WHATSAPP_NET,
960
+ type: 'set',
961
+ xmlns: 'privacy'
962
+ },
963
+ content: [
964
+ {
965
+ tag: 'tokens',
966
+ attrs: {},
967
+ content: jids.map(jid => ({
968
+ tag: 'token',
969
+ attrs: {
970
+ jid: jidNormalizedUser(jid),
971
+ t,
972
+ type: 'trusted_contact'
973
+ }
974
+ }))
975
+ }
976
+ ]
977
+ });
978
+ return result;
979
+ };
980
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
981
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
982
+ registerSocketEndHandler(() => {
983
+ if (!config.userDevicesCache && userDevicesCache.close) {
984
+ userDevicesCache.close();
985
+ }
986
+ mediaConn = undefined;
987
+ if (messageRetryManager) {
988
+ messageRetryManager.clear();
989
+ }
990
+ });
991
+ return {
992
+ ...sock,
993
+ userDevicesCache,
994
+ devicesMutex,
995
+ issuePrivacyTokens,
996
+ assertSessions,
997
+ relayMessage,
998
+ sendReceipt,
999
+ sendReceipts,
1000
+ readMessages,
1001
+ refreshMediaConn,
1002
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1003
+ getMediaHost: () => mediaHost,
1004
+ waUploadToServer,
1005
+ fetchPrivacySettings,
1006
+ sendPeerDataOperationMessage,
1007
+ createParticipantNodes,
1008
+ getUSyncDevices,
1009
+ messageRetryManager,
1010
+ updateMemberLabel,
1011
+ updateMediaMessage: async (message) => {
1012
+ const content = assertMediaContent(message.message);
1013
+ const mediaKey = content.mediaKey;
1014
+ const meId = authState.creds.me.id;
1015
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1016
+ let error = undefined;
1017
+ await Promise.all([
1018
+ sendNode(node),
1019
+ waitForMsgMediaUpdate(async (update) => {
1020
+ const result = update.find(c => c.key.id === message.key.id);
1021
+ if (result) {
1022
+ if (result.error) {
1023
+ error = result.error;
1024
+ }
1025
+ else {
1026
+ try {
1027
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1028
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1029
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1030
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1031
+ data: media,
1032
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1033
+ });
1034
+ }
1035
+ content.directPath = media.directPath;
1036
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1037
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1038
+ }
1039
+ catch (err) {
1040
+ error = err;
1041
+ }
1042
+ }
1043
+ return true;
1044
+ }
1045
+ })
1046
+ ]);
1047
+ if (error) {
1048
+ throw error;
1049
+ }
1050
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1051
+ return message;
1052
+ },
1053
+ sendMessage: async (jid, content, options = {}) => {
1054
+ const userJid = authState.creds.me.id;
1055
+ if (typeof content === 'object' &&
1056
+ 'disappearingMessagesInChat' in content &&
1057
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1058
+ isJidGroup(jid)) {
1059
+ const { disappearingMessagesInChat } = content;
1060
+ const value = typeof disappearingMessagesInChat === 'boolean'
1061
+ ? disappearingMessagesInChat
1062
+ ? WA_DEFAULT_EPHEMERAL
1063
+ : 0
1064
+ : disappearingMessagesInChat;
1065
+ await groupToggleEphemeral(jid, value);
1066
+ }
1067
+ else {
1068
+ const fullMsg = await generateWAMessage(jid, content, {
1069
+ logger,
1070
+ userJid,
1071
+ getUrlInfo: text => getUrlInfo(text, {
1072
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1073
+ fetchOpts: {
1074
+ timeout: 3000,
1075
+ ...(httpRequestOptions || {})
1076
+ },
1077
+ logger,
1078
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1079
+ }),
1080
+ //TODO: CACHE
1081
+ getProfilePicUrl: sock.profilePictureUrl,
1082
+ getCallLink: sock.createCallLink,
1083
+ upload: waUploadToServer,
1084
+ mediaCache: config.mediaCache,
1085
+ options: config.options,
1086
+ messageId: generateMessageIDV2(sock.user?.id),
1087
+ ...options
1088
+ });
1089
+ const isEventMsg = 'event' in content && !!content.event;
1090
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1091
+ const isEditMsg = 'edit' in content && !!content.edit;
1092
+ const isPinMsg = 'pin' in content && !!content.pin;
1093
+ const isPollMessage = 'poll' in content && !!content.poll;
1094
+ const additionalAttributes = {};
1095
+ const additionalNodes = [];
1096
+ // required for delete
1097
+ if (isDeleteMsg) {
1098
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1099
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1100
+ additionalAttributes.edit = '8';
1101
+ }
1102
+ else {
1103
+ additionalAttributes.edit = '7';
1104
+ }
1105
+ }
1106
+ else if (isEditMsg) {
1107
+ additionalAttributes.edit = '1';
1108
+ }
1109
+ else if (isPinMsg) {
1110
+ additionalAttributes.edit = '2';
1111
+ }
1112
+ else if (isPollMessage) {
1113
+ additionalNodes.push({
1114
+ tag: 'meta',
1115
+ attrs: {
1116
+ polltype: 'creation'
1117
+ }
1118
+ });
1119
+ }
1120
+ else if (isEventMsg) {
1121
+ additionalNodes.push({
1122
+ tag: 'meta',
1123
+ attrs: {
1124
+ event_type: 'creation'
1125
+ }
1126
+ });
1127
+ }
1128
+ await relayMessage(jid, fullMsg.message, {
1129
+ messageId: fullMsg.key.id,
1130
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1131
+ additionalAttributes,
1132
+ statusJidList: options.statusJidList,
1133
+ additionalNodes
1134
+ });
1135
+ if (config.emitOwnEvents) {
1136
+ process.nextTick(async () => {
1137
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1138
+ });
1139
+ }
1140
+ return fullMsg;
1141
+ }
1142
+ }
1143
+ };
1144
+ };
1145
+ //# sourceMappingURL=messages-send.js.map