@vinzsocket/baileys 2.0.0-pre.1

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