@onedevil405/baileys 1.0.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 (372) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +4633 -0
  4. package/WAProto/fix-imports.js +29 -0
  5. package/WAProto/index.d.ts +10688 -0
  6. package/WAProto/index.js +37306 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.d.ts +58 -0
  9. package/lib/Defaults/index.d.ts.map +1 -0
  10. package/lib/Defaults/index.js +108 -0
  11. package/lib/Defaults/index.js.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  14. package/lib/Signal/Group/ciphertext-message.js +12 -0
  15. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  18. package/lib/Signal/Group/group-session-builder.js +30 -0
  19. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  20. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  21. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  22. package/lib/Signal/Group/group_cipher.js +82 -0
  23. package/lib/Signal/Group/group_cipher.js.map +1 -0
  24. package/lib/Signal/Group/index.d.ts +12 -0
  25. package/lib/Signal/Group/index.d.ts.map +1 -0
  26. package/lib/Signal/Group/index.js +12 -0
  27. package/lib/Signal/Group/index.js.map +1 -0
  28. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  29. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  30. package/lib/Signal/Group/keyhelper.js +18 -0
  31. package/lib/Signal/Group/keyhelper.js.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  34. package/lib/Signal/Group/sender-chain-key.js +26 -0
  35. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.js +58 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  42. package/lib/Signal/Group/sender-key-message.js +64 -0
  43. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  46. package/lib/Signal/Group/sender-key-name.js +48 -0
  47. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  50. package/lib/Signal/Group/sender-key-record.js +41 -0
  51. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  54. package/lib/Signal/Group/sender-key-state.js +84 -0
  55. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  58. package/lib/Signal/Group/sender-message-key.js +26 -0
  59. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  60. package/lib/Signal/libsignal.d.ts +5 -0
  61. package/lib/Signal/libsignal.d.ts.map +1 -0
  62. package/lib/Signal/libsignal.js +345 -0
  63. package/lib/Signal/libsignal.js.map +1 -0
  64. package/lib/Signal/lid-mapping.d.ts +24 -0
  65. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  66. package/lib/Signal/lid-mapping.js +126 -0
  67. package/lib/Signal/lid-mapping.js.map +1 -0
  68. package/lib/Socket/Client/index.d.ts +3 -0
  69. package/lib/Socket/Client/index.d.ts.map +1 -0
  70. package/lib/Socket/Client/index.js +3 -0
  71. package/lib/Socket/Client/index.js.map +1 -0
  72. package/lib/Socket/Client/types.d.ts +16 -0
  73. package/lib/Socket/Client/types.d.ts.map +1 -0
  74. package/lib/Socket/Client/types.js +11 -0
  75. package/lib/Socket/Client/types.js.map +1 -0
  76. package/lib/Socket/Client/websocket.d.ts +13 -0
  77. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  78. package/lib/Socket/Client/websocket.js +50 -0
  79. package/lib/Socket/Client/websocket.js.map +1 -0
  80. package/lib/Socket/business.d.ts +188 -0
  81. package/lib/Socket/business.d.ts.map +1 -0
  82. package/lib/Socket/business.js +376 -0
  83. package/lib/Socket/business.js.map +1 -0
  84. package/lib/Socket/chats.d.ts +98 -0
  85. package/lib/Socket/chats.d.ts.map +1 -0
  86. package/lib/Socket/chats.js +959 -0
  87. package/lib/Socket/chats.js.map +1 -0
  88. package/lib/Socket/communities.d.ts +233 -0
  89. package/lib/Socket/communities.d.ts.map +1 -0
  90. package/lib/Socket/communities.js +395 -0
  91. package/lib/Socket/communities.js.map +1 -0
  92. package/lib/Socket/groups.d.ts +137 -0
  93. package/lib/Socket/groups.d.ts.map +1 -0
  94. package/lib/Socket/groups.js +325 -0
  95. package/lib/Socket/groups.js.map +1 -0
  96. package/lib/Socket/index.d.ts +220 -0
  97. package/lib/Socket/index.d.ts.map +1 -0
  98. package/lib/Socket/index.js +17 -0
  99. package/lib/Socket/index.js.map +1 -0
  100. package/lib/Socket/messages-recv.d.ts +173 -0
  101. package/lib/Socket/messages-recv.d.ts.map +1 -0
  102. package/lib/Socket/messages-recv.js +1229 -0
  103. package/lib/Socket/messages-recv.js.map +1 -0
  104. package/lib/Socket/messages-send.d.ts +169 -0
  105. package/lib/Socket/messages-send.d.ts.map +1 -0
  106. package/lib/Socket/messages-send.js +930 -0
  107. package/lib/Socket/messages-send.js.map +1 -0
  108. package/lib/Socket/mex.d.ts +3 -0
  109. package/lib/Socket/mex.d.ts.map +1 -0
  110. package/lib/Socket/mex.js +42 -0
  111. package/lib/Socket/mex.js.map +1 -0
  112. package/lib/Socket/newsletter.d.ts +147 -0
  113. package/lib/Socket/newsletter.d.ts.map +1 -0
  114. package/lib/Socket/newsletter.js +181 -0
  115. package/lib/Socket/newsletter.js.map +1 -0
  116. package/lib/Socket/socket.d.ts +50 -0
  117. package/lib/Socket/socket.d.ts.map +1 -0
  118. package/lib/Socket/socket.js +824 -0
  119. package/lib/Socket/socket.js.map +1 -0
  120. package/lib/Types/Auth.d.ts +106 -0
  121. package/lib/Types/Auth.d.ts.map +1 -0
  122. package/lib/Types/Auth.js +2 -0
  123. package/lib/Types/Auth.js.map +1 -0
  124. package/lib/Types/Bussines.d.ts +25 -0
  125. package/lib/Types/Bussines.d.ts.map +1 -0
  126. package/lib/Types/Bussines.js +2 -0
  127. package/lib/Types/Bussines.js.map +1 -0
  128. package/lib/Types/Call.d.ts +14 -0
  129. package/lib/Types/Call.d.ts.map +1 -0
  130. package/lib/Types/Call.js +2 -0
  131. package/lib/Types/Call.js.map +1 -0
  132. package/lib/Types/Chat.d.ts +123 -0
  133. package/lib/Types/Chat.d.ts.map +1 -0
  134. package/lib/Types/Chat.js +8 -0
  135. package/lib/Types/Chat.js.map +1 -0
  136. package/lib/Types/Contact.d.ts +24 -0
  137. package/lib/Types/Contact.d.ts.map +1 -0
  138. package/lib/Types/Contact.js +2 -0
  139. package/lib/Types/Contact.js.map +1 -0
  140. package/lib/Types/Events.d.ts +199 -0
  141. package/lib/Types/Events.d.ts.map +1 -0
  142. package/lib/Types/Events.js +2 -0
  143. package/lib/Types/Events.js.map +1 -0
  144. package/lib/Types/GroupMetadata.d.ts +66 -0
  145. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  146. package/lib/Types/GroupMetadata.js +2 -0
  147. package/lib/Types/GroupMetadata.js.map +1 -0
  148. package/lib/Types/Label.d.ts +47 -0
  149. package/lib/Types/Label.d.ts.map +1 -0
  150. package/lib/Types/Label.js +25 -0
  151. package/lib/Types/Label.js.map +1 -0
  152. package/lib/Types/LabelAssociation.d.ts +30 -0
  153. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  154. package/lib/Types/LabelAssociation.js +7 -0
  155. package/lib/Types/LabelAssociation.js.map +1 -0
  156. package/lib/Types/Message.d.ts +301 -0
  157. package/lib/Types/Message.d.ts.map +1 -0
  158. package/lib/Types/Message.js +11 -0
  159. package/lib/Types/Message.js.map +1 -0
  160. package/lib/Types/Newsletter.d.ts +135 -0
  161. package/lib/Types/Newsletter.d.ts.map +1 -0
  162. package/lib/Types/Newsletter.js +31 -0
  163. package/lib/Types/Newsletter.js.map +1 -0
  164. package/lib/Types/Product.d.ts +79 -0
  165. package/lib/Types/Product.d.ts.map +1 -0
  166. package/lib/Types/Product.js +2 -0
  167. package/lib/Types/Product.js.map +1 -0
  168. package/lib/Types/Signal.d.ts +76 -0
  169. package/lib/Types/Signal.d.ts.map +1 -0
  170. package/lib/Types/Signal.js +2 -0
  171. package/lib/Types/Signal.js.map +1 -0
  172. package/lib/Types/Socket.d.ts +138 -0
  173. package/lib/Types/Socket.d.ts.map +1 -0
  174. package/lib/Types/Socket.js +3 -0
  175. package/lib/Types/Socket.js.map +1 -0
  176. package/lib/Types/State.d.ts +39 -0
  177. package/lib/Types/State.d.ts.map +1 -0
  178. package/lib/Types/State.js +13 -0
  179. package/lib/Types/State.js.map +1 -0
  180. package/lib/Types/USync.d.ts +26 -0
  181. package/lib/Types/USync.d.ts.map +1 -0
  182. package/lib/Types/USync.js +2 -0
  183. package/lib/Types/USync.js.map +1 -0
  184. package/lib/Types/index.d.ts +65 -0
  185. package/lib/Types/index.d.ts.map +1 -0
  186. package/lib/Types/index.js +26 -0
  187. package/lib/Types/index.js.map +1 -0
  188. package/lib/Utils/auth-utils.d.ts +19 -0
  189. package/lib/Utils/auth-utils.d.ts.map +1 -0
  190. package/lib/Utils/auth-utils.js +474 -0
  191. package/lib/Utils/auth-utils.js.map +1 -0
  192. package/lib/Utils/baileys-event-stream.d.ts +17 -0
  193. package/lib/Utils/baileys-event-stream.d.ts.map +1 -0
  194. package/lib/Utils/baileys-event-stream.js +56 -0
  195. package/lib/Utils/baileys-event-stream.js.map +1 -0
  196. package/lib/Utils/browser-utils.d.ts +4 -0
  197. package/lib/Utils/browser-utils.d.ts.map +1 -0
  198. package/lib/Utils/browser-utils.js +28 -0
  199. package/lib/Utils/browser-utils.js.map +1 -0
  200. package/lib/Utils/business.d.ts +23 -0
  201. package/lib/Utils/business.d.ts.map +1 -0
  202. package/lib/Utils/business.js +231 -0
  203. package/lib/Utils/business.js.map +1 -0
  204. package/lib/Utils/chat-utils.d.ts +71 -0
  205. package/lib/Utils/chat-utils.d.ts.map +1 -0
  206. package/lib/Utils/chat-utils.js +764 -0
  207. package/lib/Utils/chat-utils.js.map +1 -0
  208. package/lib/Utils/crypto.d.ts +41 -0
  209. package/lib/Utils/crypto.d.ts.map +1 -0
  210. package/lib/Utils/crypto.js +142 -0
  211. package/lib/Utils/crypto.js.map +1 -0
  212. package/lib/Utils/decode-wa-message.d.ts +47 -0
  213. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  214. package/lib/Utils/decode-wa-message.js +269 -0
  215. package/lib/Utils/decode-wa-message.js.map +1 -0
  216. package/lib/Utils/event-buffer.d.ts +34 -0
  217. package/lib/Utils/event-buffer.d.ts.map +1 -0
  218. package/lib/Utils/event-buffer.js +547 -0
  219. package/lib/Utils/event-buffer.js.map +1 -0
  220. package/lib/Utils/generics.d.ts +91 -0
  221. package/lib/Utils/generics.d.ts.map +1 -0
  222. package/lib/Utils/generics.js +366 -0
  223. package/lib/Utils/generics.js.map +1 -0
  224. package/lib/Utils/history.d.ts +20 -0
  225. package/lib/Utils/history.d.ts.map +1 -0
  226. package/lib/Utils/history.js +85 -0
  227. package/lib/Utils/history.js.map +1 -0
  228. package/lib/Utils/index.d.ts +21 -0
  229. package/lib/Utils/index.d.ts.map +1 -0
  230. package/lib/Utils/index.js +21 -0
  231. package/lib/Utils/index.js.map +1 -0
  232. package/lib/Utils/link-preview.d.ts +22 -0
  233. package/lib/Utils/link-preview.d.ts.map +1 -0
  234. package/lib/Utils/link-preview.js +85 -0
  235. package/lib/Utils/link-preview.js.map +1 -0
  236. package/lib/Utils/logger.d.ts +12 -0
  237. package/lib/Utils/logger.d.ts.map +1 -0
  238. package/lib/Utils/logger.js +3 -0
  239. package/lib/Utils/logger.js.map +1 -0
  240. package/lib/Utils/lt-hash.d.ts +13 -0
  241. package/lib/Utils/lt-hash.d.ts.map +1 -0
  242. package/lib/Utils/lt-hash.js +48 -0
  243. package/lib/Utils/lt-hash.js.map +1 -0
  244. package/lib/Utils/make-mutex.d.ts +8 -0
  245. package/lib/Utils/make-mutex.d.ts.map +1 -0
  246. package/lib/Utils/make-mutex.js +40 -0
  247. package/lib/Utils/make-mutex.js.map +1 -0
  248. package/lib/Utils/message-retry-manager.d.ts +82 -0
  249. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  250. package/lib/Utils/message-retry-manager.js +149 -0
  251. package/lib/Utils/message-retry-manager.js.map +1 -0
  252. package/lib/Utils/messages-media.d.ts +113 -0
  253. package/lib/Utils/messages-media.d.ts.map +1 -0
  254. package/lib/Utils/messages-media.js +643 -0
  255. package/lib/Utils/messages-media.js.map +1 -0
  256. package/lib/Utils/messages.d.ts +76 -0
  257. package/lib/Utils/messages.d.ts.map +1 -0
  258. package/lib/Utils/messages.js +810 -0
  259. package/lib/Utils/messages.js.map +1 -0
  260. package/lib/Utils/noise-handler.d.ts +20 -0
  261. package/lib/Utils/noise-handler.d.ts.map +1 -0
  262. package/lib/Utils/noise-handler.js +147 -0
  263. package/lib/Utils/noise-handler.js.map +1 -0
  264. package/lib/Utils/process-message.d.ts +43 -0
  265. package/lib/Utils/process-message.d.ts.map +1 -0
  266. package/lib/Utils/process-message.js +384 -0
  267. package/lib/Utils/process-message.js.map +1 -0
  268. package/lib/Utils/proto-utils.d.ts +7 -0
  269. package/lib/Utils/proto-utils.d.ts.map +1 -0
  270. package/lib/Utils/proto-utils.js +7 -0
  271. package/lib/Utils/proto-utils.js.map +1 -0
  272. package/lib/Utils/signal.d.ts +34 -0
  273. package/lib/Utils/signal.d.ts.map +1 -0
  274. package/lib/Utils/signal.js +150 -0
  275. package/lib/Utils/signal.js.map +1 -0
  276. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  277. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  278. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  279. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  280. package/lib/Utils/validate-connection.d.ts +11 -0
  281. package/lib/Utils/validate-connection.d.ts.map +1 -0
  282. package/lib/Utils/validate-connection.js +166 -0
  283. package/lib/Utils/validate-connection.js.map +1 -0
  284. package/lib/WABinary/constants.d.ts +28 -0
  285. package/lib/WABinary/constants.d.ts.map +1 -0
  286. package/lib/WABinary/constants.js +1301 -0
  287. package/lib/WABinary/constants.js.map +1 -0
  288. package/lib/WABinary/decode.d.ts +7 -0
  289. package/lib/WABinary/decode.d.ts.map +1 -0
  290. package/lib/WABinary/decode.js +228 -0
  291. package/lib/WABinary/decode.js.map +1 -0
  292. package/lib/WABinary/encode.d.ts +3 -0
  293. package/lib/WABinary/encode.d.ts.map +1 -0
  294. package/lib/WABinary/encode.js +216 -0
  295. package/lib/WABinary/encode.js.map +1 -0
  296. package/lib/WABinary/generic-utils.d.ts +15 -0
  297. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  298. package/lib/WABinary/generic-utils.js +103 -0
  299. package/lib/WABinary/generic-utils.js.map +1 -0
  300. package/lib/WABinary/index.d.ts +6 -0
  301. package/lib/WABinary/index.d.ts.map +1 -0
  302. package/lib/WABinary/index.js +6 -0
  303. package/lib/WABinary/index.js.map +1 -0
  304. package/lib/WABinary/jid-utils.d.ts +37 -0
  305. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  306. package/lib/WABinary/jid-utils.js +58 -0
  307. package/lib/WABinary/jid-utils.js.map +1 -0
  308. package/lib/WABinary/types.d.ts +19 -0
  309. package/lib/WABinary/types.d.ts.map +1 -0
  310. package/lib/WABinary/types.js +2 -0
  311. package/lib/WABinary/types.js.map +1 -0
  312. package/lib/WAM/BinaryInfo.d.ts +9 -0
  313. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  314. package/lib/WAM/BinaryInfo.js +10 -0
  315. package/lib/WAM/BinaryInfo.js.map +1 -0
  316. package/lib/WAM/constants.d.ts +40 -0
  317. package/lib/WAM/constants.d.ts.map +1 -0
  318. package/lib/WAM/constants.js +15241 -0
  319. package/lib/WAM/constants.js.map +1 -0
  320. package/lib/WAM/encode.d.ts +3 -0
  321. package/lib/WAM/encode.d.ts.map +1 -0
  322. package/lib/WAM/encode.js +150 -0
  323. package/lib/WAM/encode.js.map +1 -0
  324. package/lib/WAM/index.d.ts +4 -0
  325. package/lib/WAM/index.d.ts.map +1 -0
  326. package/lib/WAM/index.js +4 -0
  327. package/lib/WAM/index.js.map +1 -0
  328. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  329. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  330. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  331. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  332. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  333. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  334. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  335. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  336. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  337. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  338. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  339. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  340. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  341. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  342. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  343. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  344. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  345. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  346. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  347. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  348. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  349. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  350. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  351. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  352. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  353. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  354. package/lib/WAUSync/Protocols/index.js +5 -0
  355. package/lib/WAUSync/Protocols/index.js.map +1 -0
  356. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  357. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  358. package/lib/WAUSync/USyncQuery.js +91 -0
  359. package/lib/WAUSync/USyncQuery.js.map +1 -0
  360. package/lib/WAUSync/USyncUser.d.ts +13 -0
  361. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  362. package/lib/WAUSync/USyncUser.js +23 -0
  363. package/lib/WAUSync/USyncUser.js.map +1 -0
  364. package/lib/WAUSync/index.d.ts +4 -0
  365. package/lib/WAUSync/index.d.ts.map +1 -0
  366. package/lib/WAUSync/index.js +4 -0
  367. package/lib/WAUSync/index.js.map +1 -0
  368. package/lib/index.d.ts +12 -0
  369. package/lib/index.d.ts.map +1 -0
  370. package/lib/index.js +11 -0
  371. package/lib/index.js.map +1 -0
  372. package/package.json +37 -0
@@ -0,0 +1,1229 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import Long from 'long';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT } from '../Defaults/index.js';
7
+ import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
+ import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
9
+ import { makeMutex } from '../Utils/make-mutex.js';
10
+ import { decodeAndHydrate } from '../Utils/proto-utils.js';
11
+ import { areJidsSameUser, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidStatusBroadcast, isLidUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { extractGroupMetadata } from './groups.js';
13
+ import { makeMessagesSocket } from './messages-send.js';
14
+ export const makeMessagesRecvSocket = (config) => {
15
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
16
+ const sock = makeMessagesSocket(config);
17
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
18
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
19
+ const retryMutex = makeMutex();
20
+ const msgRetryCache = config.msgRetryCounterCache ||
21
+ new NodeCache({
22
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
23
+ useClones: false
24
+ });
25
+ const callOfferCache = config.callOfferCache ||
26
+ new NodeCache({
27
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
28
+ useClones: false
29
+ });
30
+ const placeholderResendCache = config.placeholderResendCache ||
31
+ new NodeCache({
32
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
33
+ useClones: false
34
+ });
35
+ let sendActiveReceipts = false;
36
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
37
+ if (!authState.creds.me?.id) {
38
+ throw new Boom('Not authenticated');
39
+ }
40
+ const pdoMessage = {
41
+ historySyncOnDemandRequest: {
42
+ chatJid: oldestMsgKey.remoteJid,
43
+ oldestMsgFromMe: oldestMsgKey.fromMe,
44
+ oldestMsgId: oldestMsgKey.id,
45
+ oldestMsgTimestampMs: oldestMsgTimestamp,
46
+ onDemandMsgCount: count
47
+ },
48
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
49
+ };
50
+ return sendPeerDataOperationMessage(pdoMessage);
51
+ };
52
+ const requestPlaceholderResend = async (messageKey) => {
53
+ if (!authState.creds.me?.id) {
54
+ throw new Boom('Not authenticated');
55
+ }
56
+ if (placeholderResendCache.get(messageKey?.id)) {
57
+ logger.debug({ messageKey }, 'already requested resend');
58
+ return;
59
+ }
60
+ else {
61
+ placeholderResendCache.set(messageKey?.id, true);
62
+ }
63
+ await delay(5000);
64
+ if (!placeholderResendCache.get(messageKey?.id)) {
65
+ logger.debug({ messageKey }, 'message received while resend requested');
66
+ return 'RESOLVED';
67
+ }
68
+ const pdoMessage = {
69
+ placeholderMessageResendRequest: [
70
+ {
71
+ messageKey
72
+ }
73
+ ],
74
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
75
+ };
76
+ setTimeout(() => {
77
+ if (placeholderResendCache.get(messageKey?.id)) {
78
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
79
+ placeholderResendCache.del(messageKey?.id);
80
+ }
81
+ }, 15000);
82
+ return sendPeerDataOperationMessage(pdoMessage);
83
+ };
84
+ // Handles mex newsletter notifications
85
+ const handleMexNewsletterNotification = async (node) => {
86
+ const mexNode = getBinaryNodeChild(node, 'mex');
87
+ if (!mexNode?.content) {
88
+ logger.warn({ node }, 'Invalid mex newsletter notification');
89
+ return;
90
+ }
91
+ let data;
92
+ try {
93
+ data = JSON.parse(mexNode.content.toString());
94
+ }
95
+ catch (error) {
96
+ logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
97
+ return;
98
+ }
99
+ const operation = data?.operation;
100
+ const updates = data?.updates;
101
+ if (!updates || !operation) {
102
+ logger.warn({ data }, 'Invalid mex newsletter notification content');
103
+ return;
104
+ }
105
+ logger.info({ operation, updates }, 'got mex newsletter notification');
106
+ switch (operation) {
107
+ case 'NotificationNewsletterUpdate':
108
+ for (const update of updates) {
109
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
110
+ ev.emit('newsletter-settings.update', {
111
+ id: update.jid,
112
+ update: update.settings
113
+ });
114
+ }
115
+ }
116
+ break;
117
+ case 'NotificationNewsletterAdminPromote':
118
+ for (const update of updates) {
119
+ if (update.jid && update.user) {
120
+ ev.emit('newsletter-participants.update', {
121
+ id: update.jid,
122
+ author: node.attrs.from,
123
+ user: update.user,
124
+ new_role: 'ADMIN',
125
+ action: 'promote'
126
+ });
127
+ }
128
+ }
129
+ break;
130
+ default:
131
+ logger.info({ operation, data }, 'Unhandled mex newsletter notification');
132
+ break;
133
+ }
134
+ };
135
+ // Handles newsletter notifications
136
+ const handleNewsletterNotification = async (node) => {
137
+ const from = node.attrs.from;
138
+ const child = getAllBinaryNodeChildren(node)[0];
139
+ const author = node.attrs.participant;
140
+ logger.info({ from, child }, 'got newsletter notification');
141
+ switch (child.tag) {
142
+ case 'reaction':
143
+ const reactionUpdate = {
144
+ id: from,
145
+ server_id: child.attrs.message_id,
146
+ reaction: {
147
+ code: getBinaryNodeChildString(child, 'reaction'),
148
+ count: 1
149
+ }
150
+ };
151
+ ev.emit('newsletter.reaction', reactionUpdate);
152
+ break;
153
+ case 'view':
154
+ const viewUpdate = {
155
+ id: from,
156
+ server_id: child.attrs.message_id,
157
+ count: parseInt(child.content?.toString() || '0', 10)
158
+ };
159
+ ev.emit('newsletter.view', viewUpdate);
160
+ break;
161
+ case 'participant':
162
+ const participantUpdate = {
163
+ id: from,
164
+ author,
165
+ user: child.attrs.jid,
166
+ action: child.attrs.action,
167
+ new_role: child.attrs.role
168
+ };
169
+ ev.emit('newsletter-participants.update', participantUpdate);
170
+ break;
171
+ case 'update':
172
+ const settingsNode = getBinaryNodeChild(child, 'settings');
173
+ if (settingsNode) {
174
+ const update = {};
175
+ const nameNode = getBinaryNodeChild(settingsNode, 'name');
176
+ if (nameNode?.content)
177
+ update.name = nameNode.content.toString();
178
+ const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
179
+ if (descriptionNode?.content)
180
+ update.description = descriptionNode.content.toString();
181
+ ev.emit('newsletter-settings.update', {
182
+ id: from,
183
+ update
184
+ });
185
+ }
186
+ break;
187
+ case 'message':
188
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext');
189
+ if (plaintextNode?.content) {
190
+ try {
191
+ const contentBuf = typeof plaintextNode.content === 'string'
192
+ ? Buffer.from(plaintextNode.content, 'binary')
193
+ : Buffer.from(plaintextNode.content);
194
+ const messageProto = decodeAndHydrate(proto.Message, contentBuf);
195
+ const fullMessage = proto.WebMessageInfo.create({
196
+ key: {
197
+ remoteJid: from,
198
+ id: child.attrs.message_id || child.attrs.server_id,
199
+ fromMe: false
200
+ },
201
+ message: messageProto,
202
+ messageTimestamp: +child.attrs.t
203
+ });
204
+ await upsertMessage(fullMessage, 'append');
205
+ logger.info('Processed plaintext newsletter message');
206
+ }
207
+ catch (error) {
208
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
209
+ }
210
+ }
211
+ break;
212
+ default:
213
+ logger.warn({ node }, 'Unknown newsletter notification');
214
+ break;
215
+ }
216
+ };
217
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
218
+ const stanza = {
219
+ tag: 'ack',
220
+ attrs: {
221
+ id: attrs.id,
222
+ to: attrs.from,
223
+ class: tag
224
+ }
225
+ };
226
+ if (!!errorCode) {
227
+ stanza.attrs.error = errorCode.toString();
228
+ }
229
+ if (!!attrs.participant) {
230
+ stanza.attrs.participant = attrs.participant;
231
+ }
232
+ if (!!attrs.recipient) {
233
+ stanza.attrs.recipient = attrs.recipient;
234
+ }
235
+ if (!!attrs.type &&
236
+ (tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
237
+ stanza.attrs.type = attrs.type;
238
+ }
239
+ if (tag === 'message' && getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
240
+ stanza.attrs.from = authState.creds.me.id;
241
+ }
242
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
243
+ await sendNode(stanza);
244
+ };
245
+ const rejectCall = async (callId, callFrom) => {
246
+ const stanza = {
247
+ tag: 'call',
248
+ attrs: {
249
+ from: authState.creds.me.id,
250
+ to: callFrom
251
+ },
252
+ content: [
253
+ {
254
+ tag: 'reject',
255
+ attrs: {
256
+ 'call-id': callId,
257
+ 'call-creator': callFrom,
258
+ count: '0'
259
+ },
260
+ content: undefined
261
+ }
262
+ ]
263
+ };
264
+ await query(stanza);
265
+ };
266
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
267
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
268
+ const { key: msgKey } = fullMessage;
269
+ const msgId = msgKey.id;
270
+ if (messageRetryManager) {
271
+ // Check if we've exceeded max retries using the new system
272
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
273
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
274
+ messageRetryManager.markRetryFailed(msgId);
275
+ return;
276
+ }
277
+ // Increment retry count using new system
278
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
279
+ // Use the new retry count for the rest of the logic
280
+ const key = `${msgId}:${msgKey?.participant}`;
281
+ msgRetryCache.set(key, retryCount);
282
+ }
283
+ else {
284
+ // Fallback to old system
285
+ const key = `${msgId}:${msgKey?.participant}`;
286
+ let retryCount = (await msgRetryCache.get(key)) || 0;
287
+ if (retryCount >= maxMsgRetryCount) {
288
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
289
+ msgRetryCache.del(key);
290
+ return;
291
+ }
292
+ retryCount += 1;
293
+ await msgRetryCache.set(key, retryCount);
294
+ }
295
+ const key = `${msgId}:${msgKey?.participant}`;
296
+ const retryCount = (await msgRetryCache.get(key)) || 1;
297
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
298
+ const fromJid = node.attrs.from;
299
+ // Check if we should recreate the session
300
+ let shouldRecreateSession = false;
301
+ let recreateReason = '';
302
+ if (enableAutoSessionRecreation && messageRetryManager) {
303
+ try {
304
+ // Check if we have a session with this JID
305
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
306
+ const hasSession = await signalRepository.validateSession(fromJid);
307
+ const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists);
308
+ shouldRecreateSession = result.recreate;
309
+ recreateReason = result.reason;
310
+ if (shouldRecreateSession) {
311
+ logger.info({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
312
+ // Delete existing session to force recreation
313
+ await authState.keys.set({ session: { [sessionId]: null } });
314
+ forceIncludeKeys = true;
315
+ }
316
+ }
317
+ catch (error) {
318
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
319
+ }
320
+ }
321
+ if (retryCount <= 2) {
322
+ // Use new retry manager for phone requests if available
323
+ if (messageRetryManager) {
324
+ // Schedule phone request with delay (like whatsmeow)
325
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
326
+ try {
327
+ const msgId = await requestPlaceholderResend(msgKey);
328
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId} (scheduled)`);
329
+ }
330
+ catch (error) {
331
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
332
+ }
333
+ });
334
+ }
335
+ else {
336
+ // Fallback to immediate request
337
+ const msgId = await requestPlaceholderResend(msgKey);
338
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
339
+ }
340
+ }
341
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
342
+ await authState.keys.transaction(async () => {
343
+ const receipt = {
344
+ tag: 'receipt',
345
+ attrs: {
346
+ id: msgId,
347
+ type: 'retry',
348
+ to: node.attrs.from
349
+ },
350
+ content: [
351
+ {
352
+ tag: 'retry',
353
+ attrs: {
354
+ count: retryCount.toString(),
355
+ id: node.attrs.id,
356
+ t: node.attrs.t,
357
+ v: '1'
358
+ }
359
+ },
360
+ {
361
+ tag: 'registration',
362
+ attrs: {},
363
+ content: encodeBigEndian(authState.creds.registrationId)
364
+ }
365
+ ]
366
+ };
367
+ if (node.attrs.recipient) {
368
+ receipt.attrs.recipient = node.attrs.recipient;
369
+ }
370
+ if (node.attrs.participant) {
371
+ receipt.attrs.participant = node.attrs.participant;
372
+ }
373
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
374
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
375
+ const [keyId] = Object.keys(preKeys);
376
+ const key = preKeys[+keyId];
377
+ const content = receipt.content;
378
+ content.push({
379
+ tag: 'keys',
380
+ attrs: {},
381
+ content: [
382
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
383
+ { tag: 'identity', attrs: {}, content: identityKey.public },
384
+ xmppPreKey(key, +keyId),
385
+ xmppSignedPreKey(signedPreKey),
386
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
387
+ ]
388
+ });
389
+ ev.emit('creds.update', update);
390
+ }
391
+ await sendNode(receipt);
392
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
393
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
394
+ };
395
+ const handleEncryptNotification = async (node) => {
396
+ const from = node.attrs.from;
397
+ if (from === S_WHATSAPP_NET) {
398
+ const countChild = getBinaryNodeChild(node, 'count');
399
+ const count = +countChild.attrs.value;
400
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
401
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
402
+ if (shouldUploadMorePreKeys) {
403
+ await uploadPreKeys();
404
+ }
405
+ }
406
+ else {
407
+ const identityNode = getBinaryNodeChild(node, 'identity');
408
+ if (identityNode) {
409
+ logger.info({ jid: from }, 'identity changed');
410
+ // not handling right now
411
+ // signal will override new identity anyway
412
+ }
413
+ else {
414
+ logger.info({ node }, 'unknown encrypt notification');
415
+ }
416
+ }
417
+ };
418
+ const handleGroupNotification = (participant, child, msg) => {
419
+ const participantJid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || participant;
420
+ // TODO: Add participant LID
421
+ switch (child?.tag) {
422
+ case 'create':
423
+ const metadata = extractGroupMetadata(child);
424
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
425
+ msg.messageStubParameters = [metadata.subject];
426
+ msg.key = { participant: metadata.owner };
427
+ ev.emit('chats.upsert', [
428
+ {
429
+ id: metadata.id,
430
+ name: metadata.subject,
431
+ conversationTimestamp: metadata.creation
432
+ }
433
+ ]);
434
+ ev.emit('groups.upsert', [
435
+ {
436
+ ...metadata,
437
+ author: participant
438
+ }
439
+ ]);
440
+ break;
441
+ case 'ephemeral':
442
+ case 'not_ephemeral':
443
+ msg.message = {
444
+ protocolMessage: {
445
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
446
+ ephemeralExpiration: +(child.attrs.expiration || 0)
447
+ }
448
+ };
449
+ break;
450
+ case 'modify':
451
+ const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
452
+ msg.messageStubParameters = oldNumber || [];
453
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
454
+ break;
455
+ case 'promote':
456
+ case 'demote':
457
+ case 'remove':
458
+ case 'add':
459
+ case 'leave':
460
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
461
+ msg.messageStubType = WAMessageStubType[stubType];
462
+ const participants = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
463
+ if (participants.length === 1 &&
464
+ // if recv. "remove" message and sender removed themselves
465
+ // mark as left
466
+ areJidsSameUser(participants[0], participant) &&
467
+ child.tag === 'remove') {
468
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
469
+ }
470
+ msg.messageStubParameters = participants;
471
+ break;
472
+ case 'subject':
473
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
474
+ msg.messageStubParameters = [child.attrs.subject];
475
+ break;
476
+ case 'description':
477
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString();
478
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
479
+ msg.messageStubParameters = description ? [description] : undefined;
480
+ break;
481
+ case 'announcement':
482
+ case 'not_announcement':
483
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
484
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
485
+ break;
486
+ case 'locked':
487
+ case 'unlocked':
488
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
489
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
490
+ break;
491
+ case 'invite':
492
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
493
+ msg.messageStubParameters = [child.attrs.code];
494
+ break;
495
+ case 'member_add_mode':
496
+ const addMode = child.content;
497
+ if (addMode) {
498
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
499
+ msg.messageStubParameters = [addMode.toString()];
500
+ }
501
+ break;
502
+ case 'membership_approval_mode':
503
+ const approvalMode = getBinaryNodeChild(child, 'group_join');
504
+ if (approvalMode) {
505
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
506
+ msg.messageStubParameters = [approvalMode.attrs.state];
507
+ }
508
+ break;
509
+ case 'created_membership_requests':
510
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
511
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
512
+ break;
513
+ case 'revoked_membership_requests':
514
+ const isDenied = areJidsSameUser(participantJid, participant);
515
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
516
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
517
+ break;
518
+ }
519
+ };
520
+ const processNotification = async (node) => {
521
+ const result = {};
522
+ const [child] = getAllBinaryNodeChildren(node);
523
+ const nodeType = node.attrs.type;
524
+ const from = jidNormalizedUser(node.attrs.from);
525
+ switch (nodeType) {
526
+ case 'privacy_token':
527
+ const tokenList = getBinaryNodeChildren(child, 'token');
528
+ for (const { attrs, content } of tokenList) {
529
+ const jid = attrs.jid;
530
+ ev.emit('chats.update', [
531
+ {
532
+ id: jid,
533
+ tcToken: content
534
+ }
535
+ ]);
536
+ logger.debug({ jid }, 'got privacy token update');
537
+ }
538
+ break;
539
+ case 'newsletter':
540
+ await handleNewsletterNotification(node);
541
+ break;
542
+ case 'mex':
543
+ await handleMexNewsletterNotification(node);
544
+ break;
545
+ case 'w:gp2':
546
+ handleGroupNotification(node.attrs.participant, child, result);
547
+ break;
548
+ case 'mediaretry':
549
+ const event = decodeMediaRetryNode(node);
550
+ ev.emit('messages.media-update', [event]);
551
+ break;
552
+ case 'encrypt':
553
+ await handleEncryptNotification(node);
554
+ break;
555
+ case 'devices':
556
+ const devices = getBinaryNodeChildren(child, 'device');
557
+ if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
558
+ areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
559
+ const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
560
+ logger.info({ deviceData }, 'my own devices changed');
561
+ }
562
+ //TODO: drop a new event, add hashes
563
+ break;
564
+ case 'server_sync':
565
+ const update = getBinaryNodeChild(node, 'collection');
566
+ if (update) {
567
+ const name = update.attrs.name;
568
+ await resyncAppState([name], false);
569
+ }
570
+ break;
571
+ case 'picture':
572
+ const setPicture = getBinaryNodeChild(node, 'set');
573
+ const delPicture = getBinaryNodeChild(node, 'delete');
574
+ ev.emit('contacts.update', [
575
+ {
576
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
577
+ imgUrl: setPicture ? 'changed' : 'removed'
578
+ }
579
+ ]);
580
+ if (isJidGroup(from)) {
581
+ const node = setPicture || delPicture;
582
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
583
+ if (setPicture) {
584
+ result.messageStubParameters = [setPicture.attrs.id];
585
+ }
586
+ result.participant = node?.attrs.author;
587
+ result.key = {
588
+ ...(result.key || {}),
589
+ participant: setPicture?.attrs.author
590
+ };
591
+ }
592
+ break;
593
+ case 'account_sync':
594
+ if (child.tag === 'disappearing_mode') {
595
+ const newDuration = +child.attrs.duration;
596
+ const timestamp = +child.attrs.t;
597
+ logger.info({ newDuration }, 'updated account disappearing mode');
598
+ ev.emit('creds.update', {
599
+ accountSettings: {
600
+ ...authState.creds.accountSettings,
601
+ defaultDisappearingMode: {
602
+ ephemeralExpiration: newDuration,
603
+ ephemeralSettingTimestamp: timestamp
604
+ }
605
+ }
606
+ });
607
+ }
608
+ else if (child.tag === 'blocklist') {
609
+ const blocklists = getBinaryNodeChildren(child, 'item');
610
+ for (const { attrs } of blocklists) {
611
+ const blocklist = [attrs.jid];
612
+ const type = attrs.action === 'block' ? 'add' : 'remove';
613
+ ev.emit('blocklist.update', { blocklist, type });
614
+ }
615
+ }
616
+ break;
617
+ case 'link_code_companion_reg':
618
+ const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
619
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
620
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
621
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
622
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
623
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
624
+ const random = randomBytes(32);
625
+ const linkCodeSalt = randomBytes(32);
626
+ const linkCodePairingExpanded = await hkdf(companionSharedKey, 32, {
627
+ salt: linkCodeSalt,
628
+ info: 'link_code_pairing_key_bundle_encryption_key'
629
+ });
630
+ const encryptPayload = Buffer.concat([
631
+ Buffer.from(authState.creds.signedIdentityKey.public),
632
+ primaryIdentityPublicKey,
633
+ random
634
+ ]);
635
+ const encryptIv = randomBytes(12);
636
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
637
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
638
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
639
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
640
+ authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
641
+ await query({
642
+ tag: 'iq',
643
+ attrs: {
644
+ to: S_WHATSAPP_NET,
645
+ type: 'set',
646
+ id: sock.generateMessageTag(),
647
+ xmlns: 'md'
648
+ },
649
+ content: [
650
+ {
651
+ tag: 'link_code_companion_reg',
652
+ attrs: {
653
+ jid: authState.creds.me.id,
654
+ stage: 'companion_finish'
655
+ },
656
+ content: [
657
+ {
658
+ tag: 'link_code_pairing_wrapped_key_bundle',
659
+ attrs: {},
660
+ content: encryptedPayload
661
+ },
662
+ {
663
+ tag: 'companion_identity_public',
664
+ attrs: {},
665
+ content: authState.creds.signedIdentityKey.public
666
+ },
667
+ {
668
+ tag: 'link_code_pairing_ref',
669
+ attrs: {},
670
+ content: ref
671
+ }
672
+ ]
673
+ }
674
+ ]
675
+ });
676
+ authState.creds.registered = true;
677
+ ev.emit('creds.update', authState.creds);
678
+ }
679
+ if (Object.keys(result).length) {
680
+ return result;
681
+ }
682
+ };
683
+ async function decipherLinkPublicKey(data) {
684
+ const buffer = toRequiredBuffer(data);
685
+ const salt = buffer.slice(0, 32);
686
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
687
+ const iv = buffer.slice(32, 48);
688
+ const payload = buffer.slice(48, 80);
689
+ return aesDecryptCTR(payload, secretKey, iv);
690
+ }
691
+ function toRequiredBuffer(data) {
692
+ if (data === undefined) {
693
+ throw new Boom('Invalid buffer', { statusCode: 400 });
694
+ }
695
+ return data instanceof Buffer ? data : Buffer.from(data);
696
+ }
697
+ const willSendMessageAgain = async (id, participant) => {
698
+ const key = `${id}:${participant}`;
699
+ const retryCount = (await msgRetryCache.get(key)) || 0;
700
+ return retryCount < maxMsgRetryCount;
701
+ };
702
+ const updateSendMessageAgainCount = async (id, participant) => {
703
+ const key = `${id}:${participant}`;
704
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
705
+ await msgRetryCache.set(key, newValue);
706
+ };
707
+ const sendMessagesAgain = async (key, ids, retryNode) => {
708
+ const remoteJid = key.remoteJid;
709
+ const participant = key.participant || remoteJid;
710
+ const retryCount = +retryNode.attrs.count || 1;
711
+ // Try to get messages from cache first, then fallback to getMessage
712
+ const msgs = [];
713
+ for (const id of ids) {
714
+ let msg;
715
+ // Try to get from retry cache first if enabled
716
+ if (messageRetryManager) {
717
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
718
+ if (cachedMsg) {
719
+ msg = cachedMsg.message;
720
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
721
+ // Mark retry as successful since we found the message
722
+ messageRetryManager.markRetrySuccess(id);
723
+ }
724
+ }
725
+ // Fallback to getMessage if not found in cache
726
+ if (!msg) {
727
+ msg = await getMessage({ ...key, id });
728
+ if (msg) {
729
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
730
+ // Also mark as successful if found via getMessage
731
+ if (messageRetryManager) {
732
+ messageRetryManager.markRetrySuccess(id);
733
+ }
734
+ }
735
+ }
736
+ msgs.push(msg);
737
+ }
738
+ // if it's the primary jid sending the request
739
+ // just re-send the message to everyone
740
+ // prevents the first message decryption failure
741
+ const sendToAll = !jidDecode(participant)?.device;
742
+ // Check if we should recreate session for this retry
743
+ let shouldRecreateSession = false;
744
+ let recreateReason = '';
745
+ if (enableAutoSessionRecreation && messageRetryManager) {
746
+ try {
747
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
748
+ const hasSession = await signalRepository.validateSession(participant);
749
+ const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists);
750
+ shouldRecreateSession = result.recreate;
751
+ recreateReason = result.reason;
752
+ if (shouldRecreateSession) {
753
+ logger.info({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
754
+ await authState.keys.set({ session: { [sessionId]: null } });
755
+ }
756
+ }
757
+ catch (error) {
758
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
759
+ }
760
+ }
761
+ await assertSessions([participant]);
762
+ if (isJidGroup(remoteJid)) {
763
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
764
+ }
765
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
766
+ for (const [i, msg] of msgs.entries()) {
767
+ if (!ids[i])
768
+ continue;
769
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
770
+ updateSendMessageAgainCount(ids[i], participant);
771
+ const msgRelayOpts = { messageId: ids[i] };
772
+ if (sendToAll) {
773
+ msgRelayOpts.useUserDevicesCache = false;
774
+ }
775
+ else {
776
+ msgRelayOpts.participant = {
777
+ jid: participant,
778
+ count: +retryNode.attrs.count
779
+ };
780
+ }
781
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
782
+ }
783
+ else {
784
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
785
+ }
786
+ }
787
+ };
788
+ const handleReceipt = async (node) => {
789
+ const { attrs, content } = node;
790
+ const isLid = attrs.from.includes('lid');
791
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
792
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
793
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
794
+ const key = {
795
+ remoteJid,
796
+ id: '',
797
+ fromMe,
798
+ participant: attrs.participant
799
+ };
800
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
801
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
802
+ await sendMessageAck(node);
803
+ return;
804
+ }
805
+ const ids = [attrs.id];
806
+ if (Array.isArray(content)) {
807
+ const items = getBinaryNodeChildren(content[0], 'item');
808
+ ids.push(...items.map(i => i.attrs.id));
809
+ }
810
+ try {
811
+ await Promise.all([
812
+ processingMutex.mutex(async () => {
813
+ const status = getStatusFromReceiptType(attrs.type);
814
+ if (typeof status !== 'undefined' &&
815
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
816
+ // or another device of ours has read some messages
817
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
818
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
819
+ if (attrs.participant) {
820
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
821
+ ev.emit('message-receipt.update', ids.map(id => ({
822
+ key: { ...key, id },
823
+ receipt: {
824
+ userJid: jidNormalizedUser(attrs.participant),
825
+ [updateKey]: +attrs.t
826
+ }
827
+ })));
828
+ }
829
+ }
830
+ else {
831
+ ev.emit('messages.update', ids.map(id => ({
832
+ key: { ...key, id },
833
+ update: { status }
834
+ })));
835
+ }
836
+ }
837
+ if (attrs.type === 'retry') {
838
+ // correctly set who is asking for the retry
839
+ key.participant = key.participant || attrs.from;
840
+ const retryNode = getBinaryNodeChild(node, 'retry');
841
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
842
+ if (key.fromMe) {
843
+ try {
844
+ updateSendMessageAgainCount(ids[0], key.participant);
845
+ logger.debug({ attrs, key }, 'recv retry request');
846
+ await sendMessagesAgain(key, ids, retryNode);
847
+ }
848
+ catch (error) {
849
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
850
+ }
851
+ }
852
+ else {
853
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
854
+ }
855
+ }
856
+ else {
857
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
858
+ }
859
+ }
860
+ })
861
+ ]);
862
+ }
863
+ finally {
864
+ await sendMessageAck(node);
865
+ }
866
+ };
867
+ const handleNotification = async (node) => {
868
+ const remoteJid = node.attrs.from;
869
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
870
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
871
+ await sendMessageAck(node);
872
+ return;
873
+ }
874
+ try {
875
+ await Promise.all([
876
+ processingMutex.mutex(async () => {
877
+ const msg = await processNotification(node);
878
+ if (msg) {
879
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
880
+ msg.key = {
881
+ remoteJid,
882
+ fromMe,
883
+ participant: node.attrs.participant,
884
+ id: node.attrs.id,
885
+ ...(msg.key || {})
886
+ };
887
+ msg.participant ?? (msg.participant = node.attrs.participant);
888
+ msg.messageTimestamp = +node.attrs.t;
889
+ const fullMsg = proto.WebMessageInfo.create(msg);
890
+ await upsertMessage(fullMsg, 'append');
891
+ }
892
+ })
893
+ ]);
894
+ }
895
+ finally {
896
+ await sendMessageAck(node);
897
+ }
898
+ };
899
+ const handleMessage = async (node) => {
900
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
901
+ logger.debug({ key: node.attrs.key }, 'ignored message');
902
+ await sendMessageAck(node);
903
+ return;
904
+ }
905
+ const encNode = getBinaryNodeChild(node, 'enc');
906
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
907
+ if (encNode && encNode.attrs.type === 'msmsg') {
908
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
909
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
910
+ return;
911
+ }
912
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
913
+ if (msg.message?.protocolMessage?.type === proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER &&
914
+ node.attrs.sender_pn) {
915
+ const lid = jidNormalizedUser(node.attrs.from), pn = jidNormalizedUser(node.attrs.sender_pn);
916
+ ev.emit('lid-mapping.update', { lid, pn });
917
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
918
+ await signalRepository.migrateSession(pn, lid);
919
+ }
920
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
921
+ // store new mappings we didn't have before
922
+ if (!!alt) {
923
+ const altServer = jidDecode(alt)?.server;
924
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
925
+ if (altServer === 'lid') {
926
+ if (typeof (await signalRepository.lidMapping.getPNForLID(alt)) === 'string') {
927
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
928
+ await signalRepository.migrateSession(primaryJid, alt);
929
+ }
930
+ }
931
+ else {
932
+ if (typeof (await signalRepository.lidMapping.getLIDForPN(alt)) === 'string') {
933
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
934
+ await signalRepository.migrateSession(alt, primaryJid);
935
+ }
936
+ }
937
+ }
938
+ if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
939
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
940
+ logger.debug({
941
+ jid: msg.key.remoteJid,
942
+ id: msg.key.id
943
+ }, 'Added message to recent cache for retry receipts');
944
+ }
945
+ try {
946
+ await Promise.all([
947
+ processingMutex.mutex(async () => {
948
+ await decrypt();
949
+ // message failed to decrypt
950
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT) {
951
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
952
+ return sendMessageAck(node, NACK_REASONS.ParsingError);
953
+ }
954
+ const errorMessage = msg?.messageStubParameters?.[0] || '';
955
+ const isPreKeyError = errorMessage.includes('PreKey');
956
+ logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
957
+ // Handle both pre-key and normal retries in single mutex
958
+ retryMutex.mutex(async () => {
959
+ try {
960
+ if (!ws.isOpen) {
961
+ logger.debug({ node }, 'Connection closed, skipping retry');
962
+ return;
963
+ }
964
+ // Handle pre-key errors with upload and delay
965
+ if (isPreKeyError) {
966
+ logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
967
+ try {
968
+ logger.debug('Uploading pre-keys for error recovery');
969
+ await uploadPreKeys(5);
970
+ logger.debug('Waiting for server to process new pre-keys');
971
+ await delay(1000);
972
+ }
973
+ catch (uploadErr) {
974
+ logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
975
+ }
976
+ }
977
+ const encNode = getBinaryNodeChild(node, 'enc');
978
+ await sendRetryRequest(node, !encNode);
979
+ if (retryRequestDelayMs) {
980
+ await delay(retryRequestDelayMs);
981
+ }
982
+ }
983
+ catch (err) {
984
+ logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
985
+ // Still attempt retry even if pre-key upload failed
986
+ try {
987
+ const encNode = getBinaryNodeChild(node, 'enc');
988
+ await sendRetryRequest(node, !encNode);
989
+ }
990
+ catch (retryErr) {
991
+ logger.error({ retryErr }, 'Failed to send retry after error handling');
992
+ }
993
+ }
994
+ });
995
+ }
996
+ else {
997
+ // no type in the receipt => message delivered
998
+ let type = undefined;
999
+ let participant = msg.key.participant;
1000
+ if (category === 'peer') {
1001
+ // special peer message
1002
+ type = 'peer_msg';
1003
+ }
1004
+ else if (msg.key.fromMe) {
1005
+ // message was sent by us from a different device
1006
+ type = 'sender';
1007
+ // need to specially handle this case
1008
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1009
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1010
+ }
1011
+ }
1012
+ else if (!sendActiveReceipts) {
1013
+ type = 'inactive';
1014
+ }
1015
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1016
+ // send ack for history message
1017
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
1018
+ if (isAnyHistoryMsg) {
1019
+ const jid = jidNormalizedUser(msg.key.remoteJid);
1020
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
1021
+ }
1022
+ }
1023
+ cleanMessage(msg, authState.creds.me.id);
1024
+ await sendMessageAck(node);
1025
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1026
+ })
1027
+ ]);
1028
+ }
1029
+ catch (error) {
1030
+ logger.error({ error, node }, 'error in handling message');
1031
+ }
1032
+ };
1033
+ const handleCall = async (node) => {
1034
+ let status;
1035
+ const { attrs } = node;
1036
+ const [infoChild] = getAllBinaryNodeChildren(node);
1037
+ if (!infoChild) {
1038
+ throw new Boom('Missing call info in call node');
1039
+ }
1040
+ const callId = infoChild.attrs['call-id'];
1041
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1042
+ status = getCallStatusFromNode(infoChild);
1043
+ if (isLidUser(from) && infoChild.tag === 'relaylatency') {
1044
+ const verify = await callOfferCache.get(callId);
1045
+ if (!verify) {
1046
+ status = 'offer';
1047
+ const callLid = {
1048
+ chatId: attrs.from,
1049
+ from,
1050
+ id: callId,
1051
+ date: new Date(+attrs.t * 1000),
1052
+ offline: !!attrs.offline,
1053
+ status
1054
+ };
1055
+ await callOfferCache.set(callId, callLid);
1056
+ }
1057
+ }
1058
+ const call = {
1059
+ chatId: attrs.from,
1060
+ from,
1061
+ id: callId,
1062
+ date: new Date(+attrs.t * 1000),
1063
+ offline: !!attrs.offline,
1064
+ status
1065
+ };
1066
+ if (status === 'offer') {
1067
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1068
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1069
+ call.groupJid = infoChild.attrs['group-jid'];
1070
+ await callOfferCache.set(call.id, call);
1071
+ }
1072
+ const existingCall = await callOfferCache.get(call.id);
1073
+ // use existing call info to populate this event
1074
+ if (existingCall) {
1075
+ call.isVideo = existingCall.isVideo;
1076
+ call.isGroup = existingCall.isGroup;
1077
+ }
1078
+ // delete data once call has ended
1079
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1080
+ await callOfferCache.del(call.id);
1081
+ }
1082
+ ev.emit('call', [call]);
1083
+ await sendMessageAck(node);
1084
+ };
1085
+ const handleBadAck = async ({ attrs }) => {
1086
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1087
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1088
+ // // current hypothesis is that if pash is sent in the ack
1089
+ // // it means -- the message hasn't reached all devices yet
1090
+ // // we'll retry sending the message here
1091
+ // if(attrs.phash) {
1092
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1093
+ // const msg = await getMessage(key)
1094
+ // if(msg) {
1095
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1096
+ // } else {
1097
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1098
+ // }
1099
+ // }
1100
+ // error in acknowledgement,
1101
+ // device could not display the message
1102
+ if (attrs.error) {
1103
+ logger.warn({ attrs }, 'received error in ack');
1104
+ ev.emit('messages.update', [
1105
+ {
1106
+ key,
1107
+ update: {
1108
+ status: WAMessageStatus.ERROR,
1109
+ messageStubParameters: [attrs.error]
1110
+ }
1111
+ }
1112
+ ]);
1113
+ }
1114
+ };
1115
+ /// processes a node with the given function
1116
+ /// and adds the task to the existing buffer if we're buffering events
1117
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1118
+ ev.buffer();
1119
+ await execTask();
1120
+ ev.flush();
1121
+ function execTask() {
1122
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1123
+ }
1124
+ };
1125
+ const makeOfflineNodeProcessor = () => {
1126
+ const nodeProcessorMap = new Map([
1127
+ ['message', handleMessage],
1128
+ ['call', handleCall],
1129
+ ['receipt', handleReceipt],
1130
+ ['notification', handleNotification]
1131
+ ]);
1132
+ const nodes = [];
1133
+ let isProcessing = false;
1134
+ const enqueue = (type, node) => {
1135
+ nodes.push({ type, node });
1136
+ if (isProcessing) {
1137
+ return;
1138
+ }
1139
+ isProcessing = true;
1140
+ const promise = async () => {
1141
+ while (nodes.length && ws.isOpen) {
1142
+ const { type, node } = nodes.shift();
1143
+ const nodeProcessor = nodeProcessorMap.get(type);
1144
+ if (!nodeProcessor) {
1145
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1146
+ continue;
1147
+ }
1148
+ await nodeProcessor(node);
1149
+ }
1150
+ isProcessing = false;
1151
+ };
1152
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1153
+ };
1154
+ return { enqueue };
1155
+ };
1156
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1157
+ const processNode = (type, node, identifier, exec) => {
1158
+ const isOffline = !!node.attrs.offline;
1159
+ if (isOffline) {
1160
+ offlineNodeProcessor.enqueue(type, node);
1161
+ }
1162
+ else {
1163
+ processNodeWithBuffer(node, identifier, exec);
1164
+ }
1165
+ };
1166
+ // recv a message
1167
+ ws.on('CB:message', (node) => {
1168
+ processNode('message', node, 'processing message', handleMessage);
1169
+ });
1170
+ ws.on('CB:call', async (node) => {
1171
+ processNode('call', node, 'handling call', handleCall);
1172
+ });
1173
+ ws.on('CB:receipt', node => {
1174
+ processNode('receipt', node, 'handling receipt', handleReceipt);
1175
+ });
1176
+ ws.on('CB:notification', async (node) => {
1177
+ processNode('notification', node, 'handling notification', handleNotification);
1178
+ });
1179
+ ws.on('CB:ack,class:message', (node) => {
1180
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1181
+ });
1182
+ ev.on('call', ([call]) => {
1183
+ if (!call) {
1184
+ return;
1185
+ }
1186
+ // missed call + group call notification message generation
1187
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1188
+ const msg = {
1189
+ key: {
1190
+ remoteJid: call.chatId,
1191
+ id: call.id,
1192
+ fromMe: false
1193
+ },
1194
+ messageTimestamp: unixTimestampSeconds(call.date)
1195
+ };
1196
+ if (call.status === 'timeout') {
1197
+ if (call.isGroup) {
1198
+ msg.messageStubType = call.isVideo
1199
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1200
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1201
+ }
1202
+ else {
1203
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1204
+ }
1205
+ }
1206
+ else {
1207
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1208
+ }
1209
+ const protoMsg = proto.WebMessageInfo.create(msg);
1210
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1211
+ }
1212
+ });
1213
+ ev.on('connection.update', ({ isOnline }) => {
1214
+ if (typeof isOnline !== 'undefined') {
1215
+ sendActiveReceipts = isOnline;
1216
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1217
+ }
1218
+ });
1219
+ return {
1220
+ ...sock,
1221
+ sendMessageAck,
1222
+ sendRetryRequest,
1223
+ rejectCall,
1224
+ fetchMessageHistory,
1225
+ requestPlaceholderResend,
1226
+ messageRetryManager
1227
+ };
1228
+ };
1229
+ //# sourceMappingURL=messages-recv.js.map