@vinzsocket/baileys 2.8.35 → 3.0.10

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 (410) hide show
  1. package/WAProto/GenerateStatics.sh +2 -2
  2. package/WAProto/WAProto.proto +1339 -493
  3. package/WAProto/fix-imports.js +75 -19
  4. package/WAProto/index.d.ts +5274 -1945
  5. package/WAProto/index.js +81079 -20694
  6. package/lib/Defaults/index.d.ts +75 -0
  7. package/lib/Defaults/index.d.ts.map +1 -0
  8. package/lib/Defaults/index.js +122 -110
  9. package/lib/Defaults/index.js.map +1 -0
  10. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +11 -18
  13. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.js +27 -35
  17. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  18. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  19. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  20. package/lib/Signal/Group/group_cipher.js +75 -95
  21. package/lib/Signal/Group/group_cipher.js.map +1 -0
  22. package/lib/Signal/Group/index.d.ts +12 -0
  23. package/lib/Signal/Group/index.d.ts.map +1 -0
  24. package/lib/Signal/Group/index.js +12 -79
  25. package/lib/Signal/Group/index.js.map +1 -0
  26. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  27. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  28. package/lib/Signal/Group/keyhelper.js +14 -25
  29. package/lib/Signal/Group/keyhelper.js.map +1 -0
  30. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  31. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.js +24 -37
  33. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  34. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.js +62 -61
  37. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  38. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  39. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.js +64 -68
  41. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  42. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  43. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.js +41 -47
  45. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  46. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  47. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.js +36 -50
  49. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  50. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  51. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.js +76 -96
  53. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  54. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  55. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.js +25 -34
  57. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  58. package/lib/Signal/libsignal.d.ts +5 -0
  59. package/lib/Signal/libsignal.d.ts.map +1 -0
  60. package/lib/Signal/libsignal.js +415 -402
  61. package/lib/Signal/libsignal.js.map +1 -0
  62. package/lib/Signal/lid-mapping.d.ts +23 -0
  63. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  64. package/lib/Signal/lid-mapping.js +273 -111
  65. package/lib/Signal/lid-mapping.js.map +1 -0
  66. package/lib/Socket/Client/index.d.ts +3 -0
  67. package/lib/Socket/Client/index.d.ts.map +1 -0
  68. package/lib/Socket/Client/index.js +3 -27
  69. package/lib/Socket/Client/index.js.map +1 -0
  70. package/lib/Socket/Client/types.d.ts +16 -0
  71. package/lib/Socket/Client/types.d.ts.map +1 -0
  72. package/lib/Socket/Client/types.js +10 -17
  73. package/lib/Socket/Client/types.js.map +1 -0
  74. package/lib/Socket/Client/websocket.d.ts +13 -0
  75. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  76. package/lib/Socket/Client/websocket.js +53 -57
  77. package/lib/Socket/Client/websocket.js.map +1 -0
  78. package/lib/Socket/business.d.ts +217 -0
  79. package/lib/Socket/business.d.ts.map +1 -0
  80. package/lib/Socket/business.js +374 -363
  81. package/lib/Socket/business.js.map +1 -0
  82. package/lib/Socket/chats.d.ts +124 -0
  83. package/lib/Socket/chats.d.ts.map +1 -0
  84. package/lib/Socket/chats.js +1162 -1041
  85. package/lib/Socket/chats.js.map +1 -0
  86. package/lib/Socket/communities.d.ts +273 -0
  87. package/lib/Socket/communities.d.ts.map +1 -0
  88. package/lib/Socket/communities.js +418 -469
  89. package/lib/Socket/communities.js.map +1 -0
  90. package/lib/Socket/groups.d.ts +161 -0
  91. package/lib/Socket/groups.d.ts.map +1 -0
  92. package/lib/Socket/groups.js +337 -393
  93. package/lib/Socket/groups.js.map +1 -0
  94. package/lib/Socket/index.d.ts +260 -0
  95. package/lib/Socket/index.d.ts.map +1 -0
  96. package/lib/Socket/index.js +10 -20
  97. package/lib/Socket/index.js.map +1 -0
  98. package/lib/Socket/messages-recv.d.ts +203 -0
  99. package/lib/Socket/messages-recv.d.ts.map +1 -0
  100. package/lib/Socket/messages-recv.js +1738 -1394
  101. package/lib/Socket/messages-recv.js.map +1 -0
  102. package/lib/Socket/messages-send.d.ts +199 -0
  103. package/lib/Socket/messages-send.d.ts.map +1 -0
  104. package/lib/Socket/messages-send.js +1101 -1245
  105. package/lib/Socket/messages-send.js.map +1 -0
  106. package/lib/Socket/mex.d.ts +3 -0
  107. package/lib/Socket/mex.d.ts.map +1 -0
  108. package/lib/Socket/mex.js +38 -51
  109. package/lib/Socket/mex.js.map +1 -0
  110. package/lib/Socket/newsletter.d.ts +170 -0
  111. package/lib/Socket/newsletter.d.ts.map +1 -0
  112. package/lib/Socket/newsletter.js +175 -225
  113. package/lib/Socket/newsletter.js.map +1 -0
  114. package/lib/Socket/socket.d.ts +59 -0
  115. package/lib/Socket/socket.d.ts.map +1 -0
  116. package/lib/Socket/socket.js +930 -914
  117. package/lib/Socket/socket.js.map +1 -0
  118. package/lib/Types/Auth.d.ts +117 -0
  119. package/lib/Types/Auth.d.ts.map +1 -0
  120. package/lib/Types/Auth.js +2 -5
  121. package/lib/Types/Auth.js.map +1 -0
  122. package/lib/Types/Bussines.d.ts +25 -0
  123. package/lib/Types/Bussines.d.ts.map +1 -0
  124. package/lib/Types/Bussines.js +2 -5
  125. package/lib/Types/Bussines.js.map +1 -0
  126. package/lib/Types/Call.d.ts +15 -0
  127. package/lib/Types/Call.d.ts.map +1 -0
  128. package/lib/Types/Call.js +2 -5
  129. package/lib/Types/Call.js.map +1 -0
  130. package/lib/Types/Chat.d.ts +124 -0
  131. package/lib/Types/Chat.d.ts.map +1 -0
  132. package/lib/Types/Chat.js +7 -7
  133. package/lib/Types/Chat.js.map +1 -0
  134. package/lib/Types/Contact.d.ts +26 -0
  135. package/lib/Types/Contact.d.ts.map +1 -0
  136. package/lib/Types/Contact.js +2 -5
  137. package/lib/Types/Contact.js.map +1 -0
  138. package/lib/Types/Events.d.ts +256 -0
  139. package/lib/Types/Events.d.ts.map +1 -0
  140. package/lib/Types/Events.js +2 -3
  141. package/lib/Types/Events.js.map +1 -0
  142. package/lib/Types/GroupMetadata.d.ts +71 -0
  143. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  144. package/lib/Types/GroupMetadata.js +2 -5
  145. package/lib/Types/GroupMetadata.js.map +1 -0
  146. package/lib/Types/Label.d.ts +47 -0
  147. package/lib/Types/Label.d.ts.map +1 -0
  148. package/lib/Types/Label.js +22 -28
  149. package/lib/Types/Label.js.map +1 -0
  150. package/lib/Types/LabelAssociation.d.ts +30 -0
  151. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  152. package/lib/Types/LabelAssociation.js +4 -10
  153. package/lib/Types/LabelAssociation.js.map +1 -0
  154. package/lib/Types/Message.d.ts +320 -0
  155. package/lib/Types/Message.d.ts.map +1 -0
  156. package/lib/Types/Message.js +8 -20
  157. package/lib/Types/Message.js.map +1 -0
  158. package/lib/Types/Mex.d.ts +141 -0
  159. package/lib/Types/Mex.d.ts.map +1 -0
  160. package/lib/Types/Mex.js +37 -0
  161. package/lib/Types/Mex.js.map +1 -0
  162. package/lib/Types/Product.d.ts +79 -0
  163. package/lib/Types/Product.d.ts.map +1 -0
  164. package/lib/Types/Product.js +2 -5
  165. package/lib/Types/Product.js.map +1 -0
  166. package/lib/Types/Signal.d.ts +87 -0
  167. package/lib/Types/Signal.d.ts.map +1 -0
  168. package/lib/Types/Signal.js +2 -3
  169. package/lib/Types/Signal.js.map +1 -0
  170. package/lib/Types/Socket.d.ts +136 -0
  171. package/lib/Types/Socket.d.ts.map +1 -0
  172. package/lib/Types/Socket.js +3 -4
  173. package/lib/Types/Socket.js.map +1 -0
  174. package/lib/Types/State.d.ts +97 -0
  175. package/lib/Types/State.d.ts.map +1 -0
  176. package/lib/Types/State.js +54 -17
  177. package/lib/Types/State.js.map +1 -0
  178. package/lib/Types/USync.d.ts +26 -0
  179. package/lib/Types/USync.d.ts.map +1 -0
  180. package/lib/Types/USync.js +2 -3
  181. package/lib/Types/USync.js.map +1 -0
  182. package/lib/Types/index.d.ts +65 -0
  183. package/lib/Types/index.d.ts.map +1 -0
  184. package/lib/Types/index.js +24 -165
  185. package/lib/Types/index.js.map +1 -0
  186. package/lib/Utils/auth-utils.d.ts +24 -0
  187. package/lib/Utils/auth-utils.d.ts.map +1 -0
  188. package/lib/Utils/auth-utils.js +272 -461
  189. package/lib/Utils/auth-utils.js.map +1 -0
  190. package/lib/Utils/browser-utils.d.ts +4 -0
  191. package/lib/Utils/browser-utils.d.ts.map +1 -0
  192. package/lib/Utils/browser-utils.js +28 -0
  193. package/lib/Utils/browser-utils.js.map +1 -0
  194. package/lib/Utils/business.d.ts +23 -0
  195. package/lib/Utils/business.d.ts.map +1 -0
  196. package/lib/Utils/business.js +207 -223
  197. package/lib/Utils/business.js.map +1 -0
  198. package/lib/Utils/chat-utils.d.ts +100 -0
  199. package/lib/Utils/chat-utils.d.ts.map +1 -0
  200. package/lib/Utils/chat-utils.js +828 -803
  201. package/lib/Utils/chat-utils.js.map +1 -0
  202. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  203. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  204. package/lib/Utils/companion-reg-client-utils.js +35 -0
  205. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  206. package/lib/Utils/crypto.d.ts +37 -0
  207. package/lib/Utils/crypto.d.ts.map +1 -0
  208. package/lib/Utils/crypto.js +87 -144
  209. package/lib/Utils/crypto.js.map +1 -0
  210. package/lib/Utils/decode-wa-message.d.ts +66 -0
  211. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  212. package/lib/Utils/decode-wa-message.js +291 -262
  213. package/lib/Utils/decode-wa-message.js.map +1 -0
  214. package/lib/Utils/event-buffer.d.ts +36 -0
  215. package/lib/Utils/event-buffer.d.ts.map +1 -0
  216. package/lib/Utils/event-buffer.js +598 -560
  217. package/lib/Utils/event-buffer.js.map +1 -0
  218. package/lib/Utils/generics.d.ts +91 -0
  219. package/lib/Utils/generics.d.ts.map +1 -0
  220. package/lib/Utils/generics.js +329 -363
  221. package/lib/Utils/generics.js.map +1 -0
  222. package/lib/Utils/history.d.ts +24 -0
  223. package/lib/Utils/history.d.ts.map +1 -0
  224. package/lib/Utils/history.js +129 -96
  225. package/lib/Utils/history.js.map +1 -0
  226. package/lib/Utils/identity-change-handler.d.ts +44 -0
  227. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  228. package/lib/Utils/identity-change-handler.js +50 -0
  229. package/lib/Utils/identity-change-handler.js.map +1 -0
  230. package/lib/Utils/index.d.ts +22 -0
  231. package/lib/Utils/index.d.ts.map +1 -0
  232. package/lib/Utils/index.js +22 -236
  233. package/lib/Utils/index.js.map +1 -0
  234. package/lib/Utils/link-preview.d.ts +21 -0
  235. package/lib/Utils/link-preview.d.ts.map +1 -0
  236. package/lib/Utils/link-preview.js +69 -86
  237. package/lib/Utils/link-preview.js.map +1 -0
  238. package/lib/Utils/logger.d.ts +12 -0
  239. package/lib/Utils/logger.d.ts.map +1 -0
  240. package/lib/Utils/logger.js +3 -11
  241. package/lib/Utils/logger.js.map +1 -0
  242. package/lib/Utils/lt-hash.d.ts +8 -0
  243. package/lib/Utils/lt-hash.d.ts.map +1 -0
  244. package/lib/Utils/lt-hash.js +2 -52
  245. package/lib/Utils/lt-hash.js.map +1 -0
  246. package/lib/Utils/make-mutex.d.ts +9 -0
  247. package/lib/Utils/make-mutex.d.ts.map +1 -0
  248. package/lib/Utils/make-mutex.js +30 -43
  249. package/lib/Utils/make-mutex.js.map +1 -0
  250. package/lib/Utils/message-retry-manager.d.ts +115 -0
  251. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  252. package/lib/Utils/message-retry-manager.js +259 -162
  253. package/lib/Utils/message-retry-manager.js.map +1 -0
  254. package/lib/Utils/messages-media.d.ts +133 -0
  255. package/lib/Utils/messages-media.d.ts.map +1 -0
  256. package/lib/Utils/messages-media.js +732 -711
  257. package/lib/Utils/messages-media.js.map +1 -0
  258. package/lib/Utils/messages.d.ts +91 -0
  259. package/lib/Utils/messages.d.ts.map +1 -0
  260. package/lib/Utils/messages.js +817 -803
  261. package/lib/Utils/messages.js.map +1 -0
  262. package/lib/Utils/noise-handler.d.ts +20 -0
  263. package/lib/Utils/noise-handler.d.ts.map +1 -0
  264. package/lib/Utils/noise-handler.js +195 -168
  265. package/lib/Utils/noise-handler.js.map +1 -0
  266. package/lib/Utils/offline-node-processor.d.ts +17 -0
  267. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  268. package/lib/Utils/offline-node-processor.js +40 -0
  269. package/lib/Utils/offline-node-processor.js.map +1 -0
  270. package/lib/Utils/pre-key-manager.d.ts +28 -0
  271. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  272. package/lib/Utils/pre-key-manager.js +106 -0
  273. package/lib/Utils/pre-key-manager.js.map +1 -0
  274. package/lib/Utils/process-message.d.ts +60 -0
  275. package/lib/Utils/process-message.d.ts.map +1 -0
  276. package/lib/Utils/process-message.js +601 -424
  277. package/lib/Utils/process-message.js.map +1 -0
  278. package/lib/Utils/reporting-utils.d.ts +11 -0
  279. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  280. package/lib/Utils/reporting-utils.js +258 -0
  281. package/lib/Utils/reporting-utils.js.map +1 -0
  282. package/lib/Utils/signal.d.ts +47 -0
  283. package/lib/Utils/signal.d.ts.map +1 -0
  284. package/lib/Utils/signal.js +180 -206
  285. package/lib/Utils/signal.js.map +1 -0
  286. package/lib/Utils/stanza-ack.d.ts +11 -0
  287. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  288. package/lib/Utils/stanza-ack.js +38 -0
  289. package/lib/Utils/stanza-ack.js.map +1 -0
  290. package/lib/Utils/sync-action-utils.d.ts +19 -0
  291. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  292. package/lib/Utils/sync-action-utils.js +49 -0
  293. package/lib/Utils/sync-action-utils.js.map +1 -0
  294. package/lib/Utils/tc-token-utils.d.ts +37 -0
  295. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  296. package/lib/Utils/tc-token-utils.js +163 -0
  297. package/lib/Utils/tc-token-utils.js.map +1 -0
  298. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  299. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  300. package/lib/Utils/use-multi-file-auth-state.js +98 -101
  301. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  302. package/lib/Utils/validate-connection.d.ts +11 -0
  303. package/lib/Utils/validate-connection.d.ts.map +1 -0
  304. package/lib/Utils/validate-connection.js +191 -188
  305. package/lib/Utils/validate-connection.js.map +1 -0
  306. package/lib/WABinary/constants.d.ts +28 -0
  307. package/lib/WABinary/constants.d.ts.map +1 -0
  308. package/lib/WABinary/constants.js +1295 -36
  309. package/lib/WABinary/constants.js.map +1 -0
  310. package/lib/WABinary/decode.d.ts +7 -0
  311. package/lib/WABinary/decode.d.ts.map +1 -0
  312. package/lib/WABinary/decode.js +254 -232
  313. package/lib/WABinary/decode.js.map +1 -0
  314. package/lib/WABinary/encode.d.ts +3 -0
  315. package/lib/WABinary/encode.d.ts.map +1 -0
  316. package/lib/WABinary/encode.js +208 -210
  317. package/lib/WABinary/encode.js.map +1 -0
  318. package/lib/WABinary/generic-utils.d.ts +15 -0
  319. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  320. package/lib/WABinary/generic-utils.js +97 -106
  321. package/lib/WABinary/generic-utils.js.map +1 -0
  322. package/lib/WABinary/index.d.ts +6 -0
  323. package/lib/WABinary/index.d.ts.map +1 -0
  324. package/lib/WABinary/index.js +6 -60
  325. package/lib/WABinary/index.js.map +1 -0
  326. package/lib/WABinary/jid-utils.d.ts +48 -0
  327. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  328. package/lib/WABinary/jid-utils.js +83 -70
  329. package/lib/WABinary/jid-utils.js.map +1 -0
  330. package/lib/WABinary/types.d.ts +19 -0
  331. package/lib/WABinary/types.d.ts.map +1 -0
  332. package/lib/WABinary/types.js +2 -4
  333. package/lib/WABinary/types.js.map +1 -0
  334. package/lib/WAM/BinaryInfo.d.ts +9 -0
  335. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  336. package/lib/WAM/BinaryInfo.js +9 -16
  337. package/lib/WAM/BinaryInfo.js.map +1 -0
  338. package/lib/WAM/constants.d.ts +40 -0
  339. package/lib/WAM/constants.d.ts.map +1 -0
  340. package/lib/WAM/constants.js +22853 -13001
  341. package/lib/WAM/constants.js.map +1 -0
  342. package/lib/WAM/encode.d.ts +3 -0
  343. package/lib/WAM/encode.d.ts.map +1 -0
  344. package/lib/WAM/encode.js +133 -133
  345. package/lib/WAM/encode.js.map +1 -0
  346. package/lib/WAM/index.d.ts +4 -0
  347. package/lib/WAM/index.d.ts.map +1 -0
  348. package/lib/WAM/index.js +4 -38
  349. package/lib/WAM/index.js.map +1 -0
  350. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  351. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  352. package/lib/WAUSync/Protocols/USyncContactProtocol.js +50 -34
  353. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  354. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  355. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  356. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -61
  357. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  358. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  359. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  360. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -32
  361. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  362. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  363. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  364. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +35 -40
  365. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  366. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  367. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  368. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +23 -29
  369. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  370. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  371. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  372. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +47 -64
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  374. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  375. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  376. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +27 -26
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  378. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  379. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  380. package/lib/WAUSync/Protocols/index.js +6 -60
  381. package/lib/WAUSync/Protocols/index.js.map +1 -0
  382. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  383. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  384. package/lib/WAUSync/USyncQuery.js +94 -97
  385. package/lib/WAUSync/USyncQuery.js.map +1 -0
  386. package/lib/WAUSync/USyncUser.d.ts +17 -0
  387. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  388. package/lib/WAUSync/USyncUser.js +30 -29
  389. package/lib/WAUSync/USyncUser.js.map +1 -0
  390. package/lib/WAUSync/index.d.ts +4 -0
  391. package/lib/WAUSync/index.d.ts.map +1 -0
  392. package/lib/WAUSync/index.js +4 -38
  393. package/lib/WAUSync/index.js.map +1 -0
  394. package/lib/index.d.ts +12 -0
  395. package/lib/index.d.ts.map +1 -0
  396. package/lib/index.js +11 -114
  397. package/lib/index.js.map +1 -0
  398. package/package.json +47 -20
  399. package/README.md +0 -1315
  400. package/lib/Signal/Group/queue-job.js +0 -61
  401. package/lib/Store/index.js +0 -49
  402. package/lib/Store/make-cache-manager-store.js +0 -106
  403. package/lib/Store/make-in-memory-store.js +0 -497
  404. package/lib/Store/make-ordered-dictionary.js +0 -83
  405. package/lib/Store/object-repository.js +0 -32
  406. package/lib/Types/Newsletter.js +0 -37
  407. package/lib/Utils/baileys-event-stream.js +0 -74
  408. package/lib/Utils/extended-messages.js +0 -285
  409. package/lib/Utils/lid-resolver.js +0 -81
  410. package/lib/Utils/mention.js +0 -137
@@ -1,1072 +1,1193 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.makeChatsSocket = void 0;
7
- var _nodeCache = _interopRequireDefault(require("@cacheable/node-cache"));
8
- var _boom = require("@hapi/boom");
9
- var _index = require("../../WAProto/index.js");
10
- var _index2 = require("../Defaults/index.js");
11
- var _index3 = require("../Types/index.js");
12
- var _State = require("../Types/State.js");
13
- var _index4 = require("../Utils/index.js");
14
- var _makeMutex = require("../Utils/make-mutex.js");
15
- var _processMessage = _interopRequireDefault(require("../Utils/process-message.js"));
16
- var _index5 = require("../WABinary/index.js");
17
- var _index6 = require("../WAUSync/index.js");
18
- var _socket = require("./socket.js");
19
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
20
- const MAX_SYNC_ATTEMPTS = 2;
21
- const makeChatsSocket = config => {
22
- const {
23
- logger,
24
- markOnlineOnConnect,
25
- fireInitQueries,
26
- appStateMacVerification,
27
- shouldIgnoreJid,
28
- shouldSyncHistoryMessage
29
- } = config;
30
- const sock = (0, _socket.makeSocket)(config);
31
- const {
32
- ev,
33
- ws,
34
- authState,
35
- generateMessageTag,
36
- sendNode,
37
- query,
38
- signalRepository,
39
- onUnexpectedError
40
- } = sock;
41
- let privacySettings;
42
- let syncState = _State.SyncState.Connecting;
43
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
44
- const processingMutex = (0, _makeMutex.makeMutex)();
45
- // Timeout for AwaitingInitialSync state
46
- let awaitingSyncTimeout;
47
- const placeholderResendCache = config.placeholderResendCache || new _nodeCache.default({
48
- stdTTL: _index2.DEFAULT_CACHE_TTLS.MSG_RETRY,
49
- // 1 hour
50
- useClones: false
51
- });
52
- if (!config.placeholderResendCache) {
53
- config.placeholderResendCache = placeholderResendCache;
54
- }
55
- /** helper function to fetch the given app state sync key */
56
- const getAppStateSyncKey = async keyId => {
57
- const {
58
- [keyId]: key
59
- } = await authState.keys.get('app-state-sync-key', [keyId]);
60
- return key;
61
- };
62
- const fetchPrivacySettings = async (force = false) => {
63
- if (!privacySettings || force) {
64
- const {
65
- content
66
- } = await query({
67
- tag: 'iq',
68
- attrs: {
69
- xmlns: 'privacy',
70
- to: _index5.S_WHATSAPP_NET,
71
- type: 'get'
72
- },
73
- content: [{
74
- tag: 'privacy',
75
- attrs: {}
76
- }]
77
- });
78
- privacySettings = (0, _index5.reduceBinaryNodeToDictionary)(content?.[0], 'category');
79
- }
80
- return privacySettings;
81
- };
82
- /** helper function to run a privacy IQ query */
83
- const privacyQuery = async (name, value) => {
84
- await query({
85
- tag: 'iq',
86
- attrs: {
87
- xmlns: 'privacy',
88
- to: _index5.S_WHATSAPP_NET,
89
- type: 'set'
90
- },
91
- content: [{
92
- tag: 'privacy',
93
- attrs: {},
94
- content: [{
95
- tag: 'category',
96
- attrs: {
97
- name,
98
- value
99
- }
100
- }]
101
- }]
102
- });
103
- };
104
- const updateMessagesPrivacy = async value => {
105
- await privacyQuery('messages', value);
106
- };
107
- const updateCallPrivacy = async value => {
108
- await privacyQuery('calladd', value);
109
- };
110
- const updateLastSeenPrivacy = async value => {
111
- await privacyQuery('last', value);
112
- };
113
- const updateOnlinePrivacy = async value => {
114
- await privacyQuery('online', value);
115
- };
116
- const updateProfilePicturePrivacy = async value => {
117
- await privacyQuery('profile', value);
118
- };
119
- const updateStatusPrivacy = async value => {
120
- await privacyQuery('status', value);
121
- };
122
- const updateReadReceiptsPrivacy = async value => {
123
- await privacyQuery('readreceipts', value);
124
- };
125
- const updateGroupsAddPrivacy = async value => {
126
- await privacyQuery('groupadd', value);
127
- };
128
- const updateDefaultDisappearingMode = async duration => {
129
- await query({
130
- tag: 'iq',
131
- attrs: {
132
- xmlns: 'disappearing_mode',
133
- to: _index5.S_WHATSAPP_NET,
134
- type: 'set'
135
- },
136
- content: [{
137
- tag: 'disappearing_mode',
138
- attrs: {
139
- duration: duration.toString()
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
+ import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
+ import { SyncState } from '../Types/State.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
8
+ import { makeMutex } from '../Utils/make-mutex.js';
9
+ import processMessage from '../Utils/process-message.js';
10
+ import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { makeSocket } from './socket.js';
14
+ export const makeChatsSocket = (config) => {
15
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
16
+ const sock = makeSocket(config);
17
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
18
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
19
+ let privacySettings;
20
+ /** Server-assigned AB props for protocol behavior. */
21
+ const serverProps = {
22
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
23
+ privacyTokenOn1to1: true,
24
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
25
+ profilePicPrivacyToken: true,
26
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
27
+ lidTrustedTokenIssueToLid: false
28
+ };
29
+ let syncState = SyncState.Connecting;
30
+ /** this mutex ensures that messages are processed in order */
31
+ const messageMutex = makeMutex();
32
+ /** this mutex ensures that receipts are processed in order */
33
+ const receiptMutex = makeMutex();
34
+ /** this mutex ensures that app state patches are processed in order */
35
+ const appStatePatchMutex = makeMutex();
36
+ /** this mutex ensures that notifications are processed in order */
37
+ const notificationMutex = makeMutex();
38
+ // Timeout for AwaitingInitialSync state
39
+ let awaitingSyncTimeout;
40
+ // In-memory history sync completion tracking (resets on reconnection)
41
+ const historySyncStatus = {
42
+ initialBootstrapComplete: false,
43
+ recentSyncComplete: false
44
+ };
45
+ let historySyncPausedTimeout;
46
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
47
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
48
+ const blockedCollections = new Set();
49
+ const placeholderResendCache = config.placeholderResendCache ||
50
+ new NodeCache({
51
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
52
+ useClones: false
53
+ });
54
+ /** helper function to fetch the given app state sync key */
55
+ const getAppStateSyncKey = async (keyId) => {
56
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
57
+ return key;
58
+ };
59
+ const fetchPrivacySettings = async (force = false) => {
60
+ if (!privacySettings || force) {
61
+ const { content } = await query({
62
+ tag: 'iq',
63
+ attrs: {
64
+ xmlns: 'privacy',
65
+ to: S_WHATSAPP_NET,
66
+ type: 'get'
67
+ },
68
+ content: [{ tag: 'privacy', attrs: {} }]
69
+ });
70
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
140
71
  }
141
- }]
142
- });
143
- };
144
- const getBotListV2 = async () => {
145
- const resp = await query({
146
- tag: 'iq',
147
- attrs: {
148
- xmlns: 'bot',
149
- to: _index5.S_WHATSAPP_NET,
150
- type: 'get'
151
- },
152
- content: [{
153
- tag: 'bot',
154
- attrs: {
155
- v: '2'
72
+ return privacySettings;
73
+ };
74
+ /** helper function to run a privacy IQ query */
75
+ const privacyQuery = async (name, value) => {
76
+ await query({
77
+ tag: 'iq',
78
+ attrs: {
79
+ xmlns: 'privacy',
80
+ to: S_WHATSAPP_NET,
81
+ type: 'set'
82
+ },
83
+ content: [
84
+ {
85
+ tag: 'privacy',
86
+ attrs: {},
87
+ content: [
88
+ {
89
+ tag: 'category',
90
+ attrs: { name, value }
91
+ }
92
+ ]
93
+ }
94
+ ]
95
+ });
96
+ };
97
+ const updateMessagesPrivacy = async (value) => {
98
+ await privacyQuery('messages', value);
99
+ };
100
+ const updateCallPrivacy = async (value) => {
101
+ await privacyQuery('calladd', value);
102
+ };
103
+ const updateLastSeenPrivacy = async (value) => {
104
+ await privacyQuery('last', value);
105
+ };
106
+ const updateOnlinePrivacy = async (value) => {
107
+ await privacyQuery('online', value);
108
+ };
109
+ const updateProfilePicturePrivacy = async (value) => {
110
+ await privacyQuery('profile', value);
111
+ };
112
+ const updateStatusPrivacy = async (value) => {
113
+ await privacyQuery('status', value);
114
+ };
115
+ const updateReadReceiptsPrivacy = async (value) => {
116
+ await privacyQuery('readreceipts', value);
117
+ };
118
+ const updateGroupsAddPrivacy = async (value) => {
119
+ await privacyQuery('groupadd', value);
120
+ };
121
+ const updateDefaultDisappearingMode = async (duration) => {
122
+ await query({
123
+ tag: 'iq',
124
+ attrs: {
125
+ xmlns: 'disappearing_mode',
126
+ to: S_WHATSAPP_NET,
127
+ type: 'set'
128
+ },
129
+ content: [
130
+ {
131
+ tag: 'disappearing_mode',
132
+ attrs: {
133
+ duration: duration.toString()
134
+ }
135
+ }
136
+ ]
137
+ });
138
+ };
139
+ const getBotListV2 = async () => {
140
+ const resp = await query({
141
+ tag: 'iq',
142
+ attrs: {
143
+ xmlns: 'bot',
144
+ to: S_WHATSAPP_NET,
145
+ type: 'get'
146
+ },
147
+ content: [
148
+ {
149
+ tag: 'bot',
150
+ attrs: {
151
+ v: '2'
152
+ }
153
+ }
154
+ ]
155
+ });
156
+ const botNode = getBinaryNodeChild(resp, 'bot');
157
+ const botList = [];
158
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
159
+ if (section.attrs.type === 'all') {
160
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
161
+ botList.push({
162
+ jid: bot.attrs.jid,
163
+ personaId: bot.attrs['persona_id']
164
+ });
165
+ }
166
+ }
156
167
  }
157
- }]
158
- });
159
- const botNode = (0, _index5.getBinaryNodeChild)(resp, 'bot');
160
- const botList = [];
161
- for (const section of (0, _index5.getBinaryNodeChildren)(botNode, 'section')) {
162
- if (section.attrs.type === 'all') {
163
- for (const bot of (0, _index5.getBinaryNodeChildren)(section, 'bot')) {
164
- botList.push({
165
- jid: bot.attrs.jid,
166
- personaId: bot.attrs['persona_id']
167
- });
168
+ return botList;
169
+ };
170
+ const fetchStatus = async (...jids) => {
171
+ const usyncQuery = new USyncQuery().withStatusProtocol();
172
+ for (const jid of jids) {
173
+ usyncQuery.withUser(new USyncUser().withId(jid));
168
174
  }
169
- }
170
- }
171
- return botList;
172
- };
173
- const fetchStatus = async (...jids) => {
174
- const usyncQuery = new _index6.USyncQuery().withStatusProtocol();
175
- for (const jid of jids) {
176
- usyncQuery.withUser(new _index6.USyncUser().withId(jid));
177
- }
178
- const result = await sock.executeUSyncQuery(usyncQuery);
179
- if (result) {
180
- return result.list;
181
- }
182
- };
183
- const fetchDisappearingDuration = async (...jids) => {
184
- const usyncQuery = new _index6.USyncQuery().withDisappearingModeProtocol();
185
- for (const jid of jids) {
186
- usyncQuery.withUser(new _index6.USyncUser().withId(jid));
187
- }
188
- const result = await sock.executeUSyncQuery(usyncQuery);
189
- if (result) {
190
- return result.list;
191
- }
192
- };
193
- /** update the profile picture for yourself or a group */
194
- const updateProfilePicture = async (jid, content, dimensions) => {
195
- let targetJid;
196
- if (!jid) {
197
- throw new _boom.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
198
- }
199
- if ((0, _index5.jidNormalizedUser)(jid) !== (0, _index5.jidNormalizedUser)(authState.creds.me.id)) {
200
- targetJid = (0, _index5.jidNormalizedUser)(jid); // in case it is someone other than us
201
- } else {
202
- targetJid = undefined;
203
- }
204
- const {
205
- img
206
- } = await (0, _index4.generateProfilePicture)(content, dimensions);
207
- await query({
208
- tag: 'iq',
209
- attrs: {
210
- to: _index5.S_WHATSAPP_NET,
211
- type: 'set',
212
- xmlns: 'w:profile:picture',
213
- ...(targetJid ? {
214
- target: targetJid
215
- } : {})
216
- },
217
- content: [{
218
- tag: 'picture',
219
- attrs: {
220
- type: 'image'
221
- },
222
- content: img
223
- }]
224
- });
225
- };
226
- /** remove the profile picture for yourself or a group */
227
- const removeProfilePicture = async jid => {
228
- let targetJid;
229
- if (!jid) {
230
- throw new _boom.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
231
- }
232
- if ((0, _index5.jidNormalizedUser)(jid) !== (0, _index5.jidNormalizedUser)(authState.creds.me.id)) {
233
- targetJid = (0, _index5.jidNormalizedUser)(jid); // in case it is someone other than us
234
- } else {
235
- targetJid = undefined;
236
- }
237
- await query({
238
- tag: 'iq',
239
- attrs: {
240
- to: _index5.S_WHATSAPP_NET,
241
- type: 'set',
242
- xmlns: 'w:profile:picture',
243
- ...(targetJid ? {
244
- target: targetJid
245
- } : {})
246
- }
247
- });
248
- };
249
- /** update the profile status for yourself */
250
- const updateProfileStatus = async status => {
251
- await query({
252
- tag: 'iq',
253
- attrs: {
254
- to: _index5.S_WHATSAPP_NET,
255
- type: 'set',
256
- xmlns: 'status'
257
- },
258
- content: [{
259
- tag: 'status',
260
- attrs: {},
261
- content: Buffer.from(status, 'utf-8')
262
- }]
263
- });
264
- };
265
- const updateProfileName = async name => {
266
- await chatModify({
267
- pushNameSetting: name
268
- }, '');
269
- };
270
- const fetchBlocklist = async () => {
271
- const result = await query({
272
- tag: 'iq',
273
- attrs: {
274
- xmlns: 'blocklist',
275
- to: _index5.S_WHATSAPP_NET,
276
- type: 'get'
277
- }
278
- });
279
- const listNode = (0, _index5.getBinaryNodeChild)(result, 'list');
280
- return (0, _index5.getBinaryNodeChildren)(listNode, 'item').map(n => n.attrs.jid);
281
- };
282
- const updateBlockStatus = async (jid, action) => {
283
- await query({
284
- tag: 'iq',
285
- attrs: {
286
- xmlns: 'blocklist',
287
- to: _index5.S_WHATSAPP_NET,
288
- type: 'set'
289
- },
290
- content: [{
291
- tag: 'item',
292
- attrs: {
293
- action,
294
- jid
175
+ const result = await sock.executeUSyncQuery(usyncQuery);
176
+ if (result) {
177
+ return result.list;
295
178
  }
296
- }]
297
- });
298
- };
299
- const getBusinessProfile = async jid => {
300
- const results = await query({
301
- tag: 'iq',
302
- attrs: {
303
- to: 's.whatsapp.net',
304
- xmlns: 'w:biz',
305
- type: 'get'
306
- },
307
- content: [{
308
- tag: 'business_profile',
309
- attrs: {
310
- v: '244'
311
- },
312
- content: [{
313
- tag: 'profile',
314
- attrs: {
315
- jid
316
- }
317
- }]
318
- }]
319
- });
320
- const profileNode = (0, _index5.getBinaryNodeChild)(results, 'business_profile');
321
- const profiles = (0, _index5.getBinaryNodeChild)(profileNode, 'profile');
322
- if (profiles) {
323
- const address = (0, _index5.getBinaryNodeChild)(profiles, 'address');
324
- const description = (0, _index5.getBinaryNodeChild)(profiles, 'description');
325
- const website = (0, _index5.getBinaryNodeChild)(profiles, 'website');
326
- const email = (0, _index5.getBinaryNodeChild)(profiles, 'email');
327
- const category = (0, _index5.getBinaryNodeChild)((0, _index5.getBinaryNodeChild)(profiles, 'categories'), 'category');
328
- const businessHours = (0, _index5.getBinaryNodeChild)(profiles, 'business_hours');
329
- const businessHoursConfig = businessHours ? (0, _index5.getBinaryNodeChildren)(businessHours, 'business_hours_config') : undefined;
330
- const websiteStr = website?.content?.toString();
331
- return {
332
- wid: profiles.attrs?.jid,
333
- address: address?.content?.toString(),
334
- description: description?.content?.toString() || '',
335
- website: websiteStr ? [websiteStr] : [],
336
- email: email?.content?.toString(),
337
- category: category?.content?.toString(),
338
- business_hours: {
339
- timezone: businessHours?.attrs?.timezone,
340
- business_config: businessHoursConfig?.map(({
341
- attrs
342
- }) => attrs)
179
+ };
180
+ const fetchDisappearingDuration = async (...jids) => {
181
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
182
+ for (const jid of jids) {
183
+ usyncQuery.withUser(new USyncUser().withId(jid));
343
184
  }
344
- };
345
- }
346
- };
347
- const cleanDirtyBits = async (type, fromTimestamp) => {
348
- logger.info({
349
- fromTimestamp
350
- }, 'clean dirty bits ' + type);
351
- await sendNode({
352
- tag: 'iq',
353
- attrs: {
354
- to: _index5.S_WHATSAPP_NET,
355
- type: 'set',
356
- xmlns: 'urn:xmpp:whatsapp:dirty',
357
- id: generateMessageTag()
358
- },
359
- content: [{
360
- tag: 'clean',
361
- attrs: {
362
- type,
363
- ...(fromTimestamp ? {
364
- timestamp: fromTimestamp.toString()
365
- } : null)
185
+ const result = await sock.executeUSyncQuery(usyncQuery);
186
+ if (result) {
187
+ return result.list;
366
188
  }
367
- }]
368
- });
369
- };
370
- const newAppStateChunkHandler = isInitialSync => {
371
- return {
372
- onMutation(mutation) {
373
- (0, _index4.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? {
374
- accountSettings: authState.creds.accountSettings
375
- } : undefined, logger);
376
- }
377
189
  };
378
- };
379
- const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
380
- // we use this to determine which events to fire
381
- // otherwise when we resync from scratch -- all notifications will fire
382
- const initialVersionMap = {};
383
- const globalMutationMap = {};
384
- await authState.keys.transaction(async () => {
385
- const collectionsToHandle = new Set(collections);
386
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
387
- const attemptsMap = {};
388
- // keep executing till all collections are done
389
- // sometimes a single patch request will not return all the patches (God knows why)
390
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
391
- while (collectionsToHandle.size) {
392
- const states = {};
393
- const nodes = [];
394
- for (const name of collectionsToHandle) {
395
- const result = await authState.keys.get('app-state-sync-version', [name]);
396
- let state = result[name];
397
- if (state) {
398
- if (typeof initialVersionMap[name] === 'undefined') {
399
- initialVersionMap[name] = state.version;
190
+ /** update the profile picture for yourself or a group */
191
+ const updateProfilePicture = async (jid, content, dimensions) => {
192
+ let targetJid;
193
+ if (!jid) {
194
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
195
+ }
196
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
197
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
198
+ }
199
+ else {
200
+ targetJid = undefined;
201
+ }
202
+ const { img } = await generateProfilePicture(content, dimensions);
203
+ await query({
204
+ tag: 'iq',
205
+ attrs: {
206
+ to: S_WHATSAPP_NET,
207
+ type: 'set',
208
+ xmlns: 'w:profile:picture',
209
+ ...(targetJid ? { target: targetJid } : {})
210
+ },
211
+ content: [
212
+ {
213
+ tag: 'picture',
214
+ attrs: { type: 'image' },
215
+ content: img
216
+ }
217
+ ]
218
+ });
219
+ };
220
+ /** remove the profile picture for yourself or a group */
221
+ const removeProfilePicture = async (jid) => {
222
+ let targetJid;
223
+ if (!jid) {
224
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
225
+ }
226
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
227
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
228
+ }
229
+ else {
230
+ targetJid = undefined;
231
+ }
232
+ await query({
233
+ tag: 'iq',
234
+ attrs: {
235
+ to: S_WHATSAPP_NET,
236
+ type: 'set',
237
+ xmlns: 'w:profile:picture',
238
+ ...(targetJid ? { target: targetJid } : {})
400
239
  }
401
- } else {
402
- state = (0, _index4.newLTHashState)();
403
- }
404
- states[name] = state;
405
- logger.info(`resyncing ${name} from v${state.version}`);
406
- nodes.push({
407
- tag: 'collection',
240
+ });
241
+ };
242
+ /** update the profile status for yourself */
243
+ const updateProfileStatus = async (status) => {
244
+ await query({
245
+ tag: 'iq',
408
246
  attrs: {
409
- name,
410
- version: state.version.toString(),
411
- // return snapshot if being synced from scratch
412
- return_snapshot: (!state.version).toString()
247
+ to: S_WHATSAPP_NET,
248
+ type: 'set',
249
+ xmlns: 'status'
250
+ },
251
+ content: [
252
+ {
253
+ tag: 'status',
254
+ attrs: {},
255
+ content: Buffer.from(status, 'utf-8')
256
+ }
257
+ ]
258
+ });
259
+ };
260
+ const updateProfileName = async (name) => {
261
+ await chatModify({ pushNameSetting: name }, '');
262
+ };
263
+ const fetchBlocklist = async () => {
264
+ const result = await query({
265
+ tag: 'iq',
266
+ attrs: {
267
+ xmlns: 'blocklist',
268
+ to: S_WHATSAPP_NET,
269
+ type: 'get'
270
+ }
271
+ });
272
+ const listNode = getBinaryNodeChild(result, 'list');
273
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
274
+ };
275
+ const updateBlockStatus = async (jid, action) => {
276
+ const normalizedJid = jidNormalizedUser(jid);
277
+ let lid;
278
+ let pn_jid;
279
+ if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
280
+ lid = normalizedJid;
281
+ if (action === 'block') {
282
+ const pn = await signalRepository.lidMapping.getPNForLID(normalizedJid);
283
+ if (!pn) {
284
+ throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
285
+ }
286
+ pn_jid = jidNormalizedUser(pn);
413
287
  }
414
- });
415
288
  }
416
- const result = await query({
417
- tag: 'iq',
418
- attrs: {
419
- to: _index5.S_WHATSAPP_NET,
420
- xmlns: 'w:sync:app:state',
421
- type: 'set'
422
- },
423
- content: [{
424
- tag: 'sync',
425
- attrs: {},
426
- content: nodes
427
- }]
289
+ else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
290
+ const mapped = await signalRepository.lidMapping.getLIDForPN(normalizedJid);
291
+ if (!mapped) {
292
+ throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
293
+ }
294
+ lid = mapped;
295
+ if (action === 'block') {
296
+ pn_jid = jidNormalizedUser(normalizedJid);
297
+ }
298
+ }
299
+ else {
300
+ throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
301
+ }
302
+ const itemAttrs = {
303
+ action,
304
+ jid: lid
305
+ };
306
+ if (action === 'block') {
307
+ if (!pn_jid) {
308
+ throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
309
+ }
310
+ itemAttrs.pn_jid = pn_jid;
311
+ }
312
+ await query({
313
+ tag: 'iq',
314
+ attrs: {
315
+ xmlns: 'blocklist',
316
+ to: S_WHATSAPP_NET,
317
+ type: 'set'
318
+ },
319
+ content: [
320
+ {
321
+ tag: 'item',
322
+ attrs: itemAttrs
323
+ }
324
+ ]
325
+ });
326
+ };
327
+ const getBusinessProfile = async (jid) => {
328
+ const results = await query({
329
+ tag: 'iq',
330
+ attrs: {
331
+ to: 's.whatsapp.net',
332
+ xmlns: 'w:biz',
333
+ type: 'get'
334
+ },
335
+ content: [
336
+ {
337
+ tag: 'business_profile',
338
+ attrs: { v: '244' },
339
+ content: [
340
+ {
341
+ tag: 'profile',
342
+ attrs: { jid }
343
+ }
344
+ ]
345
+ }
346
+ ]
347
+ });
348
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
349
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
350
+ if (profiles) {
351
+ const address = getBinaryNodeChild(profiles, 'address');
352
+ const description = getBinaryNodeChild(profiles, 'description');
353
+ const website = getBinaryNodeChild(profiles, 'website');
354
+ const email = getBinaryNodeChild(profiles, 'email');
355
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
356
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
357
+ const businessHoursConfig = businessHours
358
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
359
+ : undefined;
360
+ const websiteStr = website?.content?.toString();
361
+ return {
362
+ wid: profiles.attrs?.jid,
363
+ address: address?.content?.toString(),
364
+ description: description?.content?.toString() || '',
365
+ website: websiteStr ? [websiteStr] : [],
366
+ email: email?.content?.toString(),
367
+ category: category?.content?.toString(),
368
+ business_hours: {
369
+ timezone: businessHours?.attrs?.timezone,
370
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
371
+ }
372
+ };
373
+ }
374
+ };
375
+ const cleanDirtyBits = async (type, fromTimestamp) => {
376
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
377
+ await sendNode({
378
+ tag: 'iq',
379
+ attrs: {
380
+ to: S_WHATSAPP_NET,
381
+ type: 'set',
382
+ xmlns: 'urn:xmpp:whatsapp:dirty',
383
+ id: generateMessageTag()
384
+ },
385
+ content: [
386
+ {
387
+ tag: 'clean',
388
+ attrs: {
389
+ type,
390
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
391
+ }
392
+ }
393
+ ]
428
394
  });
429
- // extract from binary node
430
- const decoded = await (0, _index4.extractSyncdPatches)(result, config?.options);
431
- for (const key in decoded) {
432
- const name = key;
433
- const {
434
- patches,
435
- hasMorePatches,
436
- snapshot
437
- } = decoded[name];
438
- try {
439
- if (snapshot) {
440
- const {
441
- state: newState,
442
- mutationMap
443
- } = await (0, _index4.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
444
- states[name] = newState;
445
- Object.assign(globalMutationMap, mutationMap);
446
- logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
447
- await authState.keys.set({
448
- 'app-state-sync-version': {
449
- [name]: newState
395
+ };
396
+ const newAppStateChunkHandler = (isInitialSync) => {
397
+ return {
398
+ onMutation(mutation) {
399
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
400
+ }
401
+ };
402
+ };
403
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
404
+ const appStateSyncKeyCache = new Map();
405
+ const getCachedAppStateSyncKey = async (keyId) => {
406
+ if (appStateSyncKeyCache.has(keyId)) {
407
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
408
+ }
409
+ const key = await getAppStateSyncKey(keyId);
410
+ appStateSyncKeyCache.set(keyId, key ?? null);
411
+ return key;
412
+ };
413
+ // we use this to determine which events to fire
414
+ // otherwise when we resync from scratch -- all notifications will fire
415
+ const initialVersionMap = {};
416
+ const globalMutationMap = {};
417
+ await authState.keys.transaction(async () => {
418
+ const collectionsToHandle = new Set(collections);
419
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
420
+ const attemptsMap = {};
421
+ // collections that failed and need a full snapshot on retry
422
+ // mirrors WA Web's ErrorFatal -> force snapshot behavior
423
+ const forceSnapshotCollections = new Set();
424
+ // keep executing till all collections are done
425
+ // sometimes a single patch request will not return all the patches (God knows why)
426
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
427
+ while (collectionsToHandle.size) {
428
+ const states = {};
429
+ const nodes = [];
430
+ for (const name of collectionsToHandle) {
431
+ const result = await authState.keys.get('app-state-sync-version', [name]);
432
+ let state = result[name];
433
+ if (state) {
434
+ state = ensureLTHashStateVersion(state);
435
+ if (typeof initialVersionMap[name] === 'undefined') {
436
+ initialVersionMap[name] = state.version;
437
+ }
438
+ }
439
+ else {
440
+ state = newLTHashState();
441
+ }
442
+ states[name] = state;
443
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
444
+ if (shouldForceSnapshot) {
445
+ forceSnapshotCollections.delete(name);
446
+ }
447
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
448
+ nodes.push({
449
+ tag: 'collection',
450
+ attrs: {
451
+ name,
452
+ version: state.version.toString(),
453
+ // return snapshot if syncing from scratch or forcing after a failed attempt
454
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
455
+ }
456
+ });
457
+ }
458
+ const result = await query({
459
+ tag: 'iq',
460
+ attrs: {
461
+ to: S_WHATSAPP_NET,
462
+ xmlns: 'w:sync:app:state',
463
+ type: 'set'
464
+ },
465
+ content: [
466
+ {
467
+ tag: 'sync',
468
+ attrs: {},
469
+ content: nodes
470
+ }
471
+ ]
472
+ });
473
+ // extract from binary node
474
+ const decoded = await extractSyncdPatches(result, config?.options);
475
+ for (const key in decoded) {
476
+ const name = key;
477
+ const { patches, hasMorePatches, snapshot } = decoded[name];
478
+ try {
479
+ if (snapshot) {
480
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
481
+ states[name] = newState;
482
+ Object.assign(globalMutationMap, mutationMap);
483
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
484
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
485
+ }
486
+ // only process if there are syncd patches
487
+ if (patches.length) {
488
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
489
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
490
+ logger.info(`synced ${name} to v${newState.version}`);
491
+ initialVersionMap[name] = newState.version;
492
+ Object.assign(globalMutationMap, mutationMap);
493
+ }
494
+ if (hasMorePatches) {
495
+ logger.info(`${name} has more patches...`);
496
+ }
497
+ else {
498
+ // collection is done with sync
499
+ collectionsToHandle.delete(name);
500
+ }
501
+ }
502
+ catch (error) {
503
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
504
+ const logData = {
505
+ name,
506
+ attempt: attemptsMap[name],
507
+ version: states[name].version,
508
+ statusCode: error.output?.statusCode,
509
+ errorType: error.name,
510
+ error: error.stack
511
+ };
512
+ if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
513
+ // WA Web treats missing keys as "Blocked" — park the collection
514
+ // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
515
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
516
+ blockedCollections.add(name);
517
+ collectionsToHandle.delete(name);
518
+ }
519
+ else if (isMissingKeyError(error)) {
520
+ // Retry with a snapshot which may use a different key.
521
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
522
+ forceSnapshotCollections.add(name);
523
+ }
524
+ else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
525
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
526
+ collectionsToHandle.delete(name);
527
+ }
528
+ else {
529
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
530
+ // force a full snapshot on retry to recover from
531
+ // corrupted local state (e.g. LTHash MAC mismatch)
532
+ forceSnapshotCollections.add(name);
533
+ }
534
+ }
450
535
  }
451
- });
452
536
  }
453
- // only process if there are syncd patches
454
- if (patches.length) {
455
- const {
456
- state: newState,
457
- mutationMap
458
- } = await (0, _index4.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
459
- await authState.keys.set({
460
- 'app-state-sync-version': {
461
- [name]: newState
537
+ }, authState?.creds?.me?.id || 'resync-app-state');
538
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
539
+ for (const key in globalMutationMap) {
540
+ onMutation(globalMutationMap[key]);
541
+ }
542
+ });
543
+ /**
544
+ * fetch the profile picture of a user/group
545
+ * type = "preview" for a low res picture
546
+ * type = "image for the high res picture"
547
+ */
548
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
549
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
550
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
551
+ // and never for own profile pic (Chat model for self has no tcToken).
552
+ // Including tctoken for own JID causes the server to never respond.
553
+ const normalizedJid = jidNormalizedUser(jid);
554
+ const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
555
+ const me = authState.creds.me;
556
+ const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
557
+ let content = baseContent;
558
+ if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
559
+ content = await buildTcTokenFromJid({
560
+ authState,
561
+ jid: normalizedJid,
562
+ baseContent,
563
+ getLIDForPN
564
+ });
565
+ }
566
+ jid = jidNormalizedUser(jid);
567
+ const result = await query({
568
+ tag: 'iq',
569
+ attrs: {
570
+ target: jid,
571
+ to: S_WHATSAPP_NET,
572
+ type: 'get',
573
+ xmlns: 'w:profile:picture'
574
+ },
575
+ content
576
+ }, timeoutMs);
577
+ const child = getBinaryNodeChild(result, 'picture');
578
+ return child?.attrs?.url;
579
+ };
580
+ const createCallLink = async (type, event, timeoutMs) => {
581
+ const result = await query({
582
+ tag: 'call',
583
+ attrs: {
584
+ id: generateMessageTag(),
585
+ to: '@call'
586
+ },
587
+ content: [
588
+ {
589
+ tag: 'link_create',
590
+ attrs: { media: type },
591
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
462
592
  }
463
- });
464
- logger.info(`synced ${name} to v${newState.version}`);
465
- initialVersionMap[name] = newState.version;
466
- Object.assign(globalMutationMap, mutationMap);
593
+ ]
594
+ }, timeoutMs);
595
+ const child = getBinaryNodeChild(result, 'link_create');
596
+ return child?.attrs?.token;
597
+ };
598
+ const sendPresenceUpdate = async (type, toJid) => {
599
+ const me = authState.creds.me;
600
+ const isAvailableType = type === 'available';
601
+ if (isAvailableType || type === 'unavailable') {
602
+ if (!me.name) {
603
+ logger.warn('no name present, ignoring presence update request...');
604
+ return;
467
605
  }
468
- if (hasMorePatches) {
469
- logger.info(`${name} has more patches...`);
470
- } else {
471
- // collection is done with sync
472
- collectionsToHandle.delete(name);
606
+ ev.emit('connection.update', { isOnline: isAvailableType });
607
+ if (isAvailableType) {
608
+ void sendUnifiedSession();
473
609
  }
474
- } catch (error) {
475
- // if retry attempts overshoot
476
- // or key not found
477
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS || error.output?.statusCode === 404 || error.name === 'TypeError';
478
- logger.info({
479
- name,
480
- error: error.stack
481
- }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
482
- await authState.keys.set({
483
- 'app-state-sync-version': {
484
- [name]: null
485
- }
610
+ await sendNode({
611
+ tag: 'presence',
612
+ attrs: {
613
+ name: me.name.replace(/@/g, ''),
614
+ type
615
+ }
486
616
  });
487
- // increment number of retries
488
- attemptsMap[name] = (attemptsMap[name] || 0) + 1;
489
- if (isIrrecoverableError) {
490
- // stop retrying
491
- collectionsToHandle.delete(name);
617
+ }
618
+ else {
619
+ const { server } = jidDecode(toJid);
620
+ const isLid = server === 'lid';
621
+ await sendNode({
622
+ tag: 'chatstate',
623
+ attrs: {
624
+ from: isLid ? me.lid : me.id,
625
+ to: toJid
626
+ },
627
+ content: [
628
+ {
629
+ tag: type === 'recording' ? 'composing' : type,
630
+ attrs: type === 'recording' ? { media: 'audio' } : {}
631
+ }
632
+ ]
633
+ });
634
+ }
635
+ };
636
+ /**
637
+ * @param toJid the jid to subscribe to
638
+ * @param tcToken token for subscription, use if present
639
+ */
640
+ const presenceSubscribe = async (toJid) => {
641
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
642
+ const normalizedToJid = jidNormalizedUser(toJid);
643
+ const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
644
+ const tcTokenContent = isUserJid
645
+ ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
646
+ : undefined;
647
+ return sendNode({
648
+ tag: 'presence',
649
+ attrs: {
650
+ to: toJid,
651
+ id: generateMessageTag(),
652
+ type: 'subscribe'
653
+ },
654
+ content: tcTokenContent
655
+ });
656
+ };
657
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
658
+ let presence;
659
+ const jid = attrs.from;
660
+ const participant = attrs.participant || attrs.from;
661
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
662
+ return;
663
+ }
664
+ if (tag === 'presence') {
665
+ presence = {
666
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
667
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
668
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
669
+ };
670
+ }
671
+ else if (Array.isArray(content)) {
672
+ const [firstChild] = content;
673
+ let type = firstChild.tag;
674
+ if (type === 'paused') {
675
+ type = 'available';
676
+ }
677
+ if (firstChild.attrs?.media === 'audio') {
678
+ type = 'recording';
492
679
  }
493
- }
680
+ presence = { lastKnownPresence: type };
494
681
  }
495
- }
496
- }, authState?.creds?.me?.id || 'resync-app-state');
497
- const {
498
- onMutation
499
- } = newAppStateChunkHandler(isInitialSync);
500
- for (const key in globalMutationMap) {
501
- onMutation(globalMutationMap[key]);
502
- }
503
- });
504
- /**
505
- * fetch the profile picture of a user/group
506
- * type = "preview" for a low res picture
507
- * type = "image for the high res picture"
508
- */
509
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
510
- jid = (0, _index5.jidNormalizedUser)(jid);
511
- const result = await query({
512
- tag: 'iq',
513
- attrs: {
514
- target: jid,
515
- to: _index5.S_WHATSAPP_NET,
516
- type: 'get',
517
- xmlns: 'w:profile:picture'
518
- },
519
- content: [{
520
- tag: 'picture',
521
- attrs: {
522
- type,
523
- query: 'url'
682
+ else {
683
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
524
684
  }
525
- }]
526
- }, timeoutMs);
527
- const child = (0, _index5.getBinaryNodeChild)(result, 'picture');
528
- return child?.attrs?.url;
529
- };
530
- const createCallLink = async (type, event, timeoutMs) => {
531
- const result = await query({
532
- tag: 'call',
533
- attrs: {
534
- id: generateMessageTag(),
535
- to: '@call'
536
- },
537
- content: [{
538
- tag: 'link_create',
539
- attrs: {
540
- media: type
541
- },
542
- content: event ? [{
543
- tag: 'event',
544
- attrs: {
545
- start_time: String(event.startTime)
546
- }
547
- }] : undefined
548
- }]
549
- }, timeoutMs);
550
- const child = (0, _index5.getBinaryNodeChild)(result, 'link_create');
551
- return child?.attrs?.token;
552
- };
553
- const sendPresenceUpdate = async (type, toJid) => {
554
- const me = authState.creds.me;
555
- if (type === 'available' || type === 'unavailable') {
556
- if (!me.name) {
557
- logger.warn('no name present, ignoring presence update request...');
558
- return;
559
- }
560
- ev.emit('connection.update', {
561
- isOnline: type === 'available'
562
- });
563
- await sendNode({
564
- tag: 'presence',
565
- attrs: {
566
- name: me.name.replace(/@/g, ''),
567
- type
685
+ if (presence) {
686
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
568
687
  }
569
- });
570
- } else {
571
- const {
572
- server
573
- } = (0, _index5.jidDecode)(toJid);
574
- const isLid = server === 'lid';
575
- await sendNode({
576
- tag: 'chatstate',
577
- attrs: {
578
- from: isLid ? me.lid : me.id,
579
- to: toJid
580
- },
581
- content: [{
582
- tag: type === 'recording' ? 'composing' : type,
583
- attrs: type === 'recording' ? {
584
- media: 'audio'
585
- } : {}
586
- }]
587
- });
588
- }
589
- };
590
- /**
591
- * @param toJid the jid to subscribe to
592
- * @param tcToken token for subscription, use if present
593
- */
594
- const presenceSubscribe = (toJid, tcToken) => sendNode({
595
- tag: 'presence',
596
- attrs: {
597
- to: toJid,
598
- id: generateMessageTag(),
599
- type: 'subscribe'
600
- },
601
- content: tcToken ? [{
602
- tag: 'tctoken',
603
- attrs: {},
604
- content: tcToken
605
- }] : undefined
606
- });
607
- const handlePresenceUpdate = ({
608
- tag,
609
- attrs,
610
- content
611
- }) => {
612
- let presence;
613
- const jid = attrs.from;
614
- const participant = attrs.participant || attrs.from;
615
- if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
616
- return;
617
- }
618
- if (tag === 'presence') {
619
- presence = {
620
- lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
621
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
622
- };
623
- } else if (Array.isArray(content)) {
624
- const [firstChild] = content;
625
- let type = firstChild.tag;
626
- if (type === 'paused') {
627
- type = 'available';
628
- }
629
- if (firstChild.attrs?.media === 'audio') {
630
- type = 'recording';
631
- }
632
- presence = {
633
- lastKnownPresence: type
634
- };
635
- } else {
636
- logger.error({
637
- tag,
638
- attrs,
639
- content
640
- }, 'recv invalid presence node');
641
- }
642
- if (presence) {
643
- ev.emit('presence.update', {
644
- id: jid,
645
- presences: {
646
- [participant]: presence
688
+ };
689
+ const appPatch = async (patchCreate) => {
690
+ const name = patchCreate.type;
691
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
692
+ if (!myAppStateKeyId) {
693
+ throw new Boom('App state key not present!', { statusCode: 400 });
647
694
  }
648
- });
649
- }
650
- };
651
- const appPatch = async patchCreate => {
652
- const name = patchCreate.type;
653
- const myAppStateKeyId = authState.creds.myAppStateKeyId;
654
- if (!myAppStateKeyId) {
655
- throw new _boom.Boom('App state key not present!', {
656
- statusCode: 400
657
- });
658
- }
659
- let initial;
660
- let encodeResult;
661
- await processingMutex.mutex(async () => {
662
- await authState.keys.transaction(async () => {
663
- logger.debug({
664
- patch: patchCreate
665
- }, 'applying app patch');
666
- await resyncAppState([name], false);
667
- const {
668
- [name]: currentSyncVersion
669
- } = await authState.keys.get('app-state-sync-version', [name]);
670
- initial = currentSyncVersion || (0, _index4.newLTHashState)();
671
- encodeResult = await (0, _index4.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
672
- const {
673
- patch,
674
- state
675
- } = encodeResult;
676
- const node = {
677
- tag: 'iq',
678
- attrs: {
679
- to: _index5.S_WHATSAPP_NET,
680
- type: 'set',
681
- xmlns: 'w:sync:app:state'
682
- },
683
- content: [{
684
- tag: 'sync',
685
- attrs: {},
686
- content: [{
687
- tag: 'collection',
688
- attrs: {
689
- name,
690
- version: (state.version - 1).toString(),
691
- return_snapshot: 'false'
692
- },
693
- content: [{
694
- tag: 'patch',
695
- attrs: {},
696
- content: _index.proto.SyncdPatch.encode(patch).finish()
697
- }]
698
- }]
699
- }]
700
- };
701
- await query(node);
702
- await authState.keys.set({
703
- 'app-state-sync-version': {
704
- [name]: state
705
- }
695
+ let initial;
696
+ let encodeResult;
697
+ await appStatePatchMutex.mutex(async () => {
698
+ await authState.keys.transaction(async () => {
699
+ logger.debug({ patch: patchCreate }, 'applying app patch');
700
+ await resyncAppState([name], false);
701
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
702
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
703
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
704
+ const { patch, state } = encodeResult;
705
+ const node = {
706
+ tag: 'iq',
707
+ attrs: {
708
+ to: S_WHATSAPP_NET,
709
+ type: 'set',
710
+ xmlns: 'w:sync:app:state'
711
+ },
712
+ content: [
713
+ {
714
+ tag: 'sync',
715
+ attrs: {},
716
+ content: [
717
+ {
718
+ tag: 'collection',
719
+ attrs: {
720
+ name,
721
+ version: (state.version - 1).toString(),
722
+ return_snapshot: 'false'
723
+ },
724
+ content: [
725
+ {
726
+ tag: 'patch',
727
+ attrs: {},
728
+ content: proto.SyncdPatch.encode(patch).finish()
729
+ }
730
+ ]
731
+ }
732
+ ]
733
+ }
734
+ ]
735
+ };
736
+ await query(node);
737
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
738
+ }, authState?.creds?.me?.id || 'app-patch');
706
739
  });
707
- }, authState?.creds?.me?.id || 'app-patch');
740
+ if (config.emitOwnEvents) {
741
+ const { onMutation } = newAppStateChunkHandler(false);
742
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
743
+ for (const key in mutationMap) {
744
+ onMutation(mutationMap[key]);
745
+ }
746
+ }
747
+ };
748
+ /** fetch AB props */
749
+ const fetchProps = async () => {
750
+ const resultNode = await query({
751
+ tag: 'iq',
752
+ attrs: {
753
+ to: S_WHATSAPP_NET,
754
+ xmlns: 'abt',
755
+ type: 'get'
756
+ },
757
+ content: [
758
+ {
759
+ tag: 'props',
760
+ attrs: {
761
+ protocol: '1',
762
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
763
+ }
764
+ }
765
+ ]
766
+ });
767
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
768
+ let props = {};
769
+ if (propsNode) {
770
+ if (propsNode.attrs?.hash) {
771
+ // on some clients, the hash is returning as undefined
772
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
773
+ ev.emit('creds.update', authState.creds);
774
+ }
775
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
776
+ }
777
+ // Extract protocol-relevant AB props (only the ones we need)
778
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
779
+ if (privacyTokenProp !== undefined) {
780
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
781
+ }
782
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
783
+ if (profilePicProp !== undefined) {
784
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
785
+ }
786
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
787
+ if (lidIssueProp !== undefined) {
788
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
789
+ }
790
+ logger.debug({ serverProps }, 'fetched props');
791
+ return props;
792
+ };
793
+ /**
794
+ * modify a chat -- mark unread, read etc.
795
+ * lastMessages must be sorted in reverse chronologically
796
+ * requires the last messages till the last message received; required for archive & unread
797
+ */
798
+ const chatModify = (mod, jid) => {
799
+ const patch = chatModificationToAppPatch(mod, jid);
800
+ return appPatch(patch);
801
+ };
802
+ /**
803
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
804
+ */
805
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
806
+ return chatModify({
807
+ disableLinkPreviews: { isPreviewsDisabled }
808
+ }, '');
809
+ };
810
+ /**
811
+ * Star or Unstar a message
812
+ */
813
+ const star = (jid, messages, star) => {
814
+ return chatModify({
815
+ star: {
816
+ messages,
817
+ star
818
+ }
819
+ }, jid);
820
+ };
821
+ /**
822
+ * Add or Edit Contact
823
+ */
824
+ const addOrEditContact = (jid, contact) => {
825
+ return chatModify({
826
+ contact
827
+ }, jid);
828
+ };
829
+ /**
830
+ * Remove Contact
831
+ */
832
+ const removeContact = (jid) => {
833
+ return chatModify({
834
+ contact: null
835
+ }, jid);
836
+ };
837
+ /**
838
+ * Adds label
839
+ */
840
+ const addLabel = (jid, labels) => {
841
+ return chatModify({
842
+ addLabel: {
843
+ ...labels
844
+ }
845
+ }, jid);
846
+ };
847
+ /**
848
+ * Adds label for the chats
849
+ */
850
+ const addChatLabel = (jid, labelId) => {
851
+ return chatModify({
852
+ addChatLabel: {
853
+ labelId
854
+ }
855
+ }, jid);
856
+ };
857
+ /**
858
+ * Removes label for the chat
859
+ */
860
+ const removeChatLabel = (jid, labelId) => {
861
+ return chatModify({
862
+ removeChatLabel: {
863
+ labelId
864
+ }
865
+ }, jid);
866
+ };
867
+ /**
868
+ * Adds label for the message
869
+ */
870
+ const addMessageLabel = (jid, messageId, labelId) => {
871
+ return chatModify({
872
+ addMessageLabel: {
873
+ messageId,
874
+ labelId
875
+ }
876
+ }, jid);
877
+ };
878
+ /**
879
+ * Removes label for the message
880
+ */
881
+ const removeMessageLabel = (jid, messageId, labelId) => {
882
+ return chatModify({
883
+ removeMessageLabel: {
884
+ messageId,
885
+ labelId
886
+ }
887
+ }, jid);
888
+ };
889
+ /**
890
+ * Add or Edit Quick Reply
891
+ */
892
+ const addOrEditQuickReply = (quickReply) => {
893
+ return chatModify({
894
+ quickReply
895
+ }, '');
896
+ };
897
+ /**
898
+ * Remove Quick Reply
899
+ */
900
+ const removeQuickReply = (timestamp) => {
901
+ return chatModify({
902
+ quickReply: { timestamp, deleted: true }
903
+ }, '');
904
+ };
905
+ /**
906
+ * queries need to be fired on connection open
907
+ * help ensure parity with WA Web
908
+ * */
909
+ const executeInitQueries = async () => {
910
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
911
+ };
912
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
913
+ ev.emit('messages.upsert', { messages: [msg], type });
914
+ if (!!msg.pushName) {
915
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
916
+ jid = jidNormalizedUser(jid);
917
+ if (!msg.key.fromMe) {
918
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
919
+ }
920
+ // update our pushname too
921
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
922
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
923
+ }
924
+ }
925
+ const historyMsg = getHistoryMsg(msg.message);
926
+ const shouldProcessHistoryMsg = historyMsg
927
+ ? shouldSyncHistoryMessage(historyMsg) &&
928
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
929
+ : false;
930
+ if (historyMsg && shouldProcessHistoryMsg) {
931
+ const syncType = historyMsg.syncType;
932
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
933
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
934
+ !historySyncStatus.initialBootstrapComplete) {
935
+ historySyncStatus.initialBootstrapComplete = true;
936
+ ev.emit('messaging-history.status', {
937
+ syncType,
938
+ status: 'complete',
939
+ explicit: true
940
+ });
941
+ }
942
+ // RECENT with progress === 100 — explicit completion
943
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
944
+ historyMsg.progress === 100 &&
945
+ !historySyncStatus.recentSyncComplete) {
946
+ historySyncStatus.recentSyncComplete = true;
947
+ clearTimeout(historySyncPausedTimeout);
948
+ historySyncPausedTimeout = undefined;
949
+ ev.emit('messaging-history.status', {
950
+ syncType,
951
+ status: 'complete',
952
+ explicit: true
953
+ });
954
+ }
955
+ // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
956
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
957
+ clearTimeout(historySyncPausedTimeout);
958
+ historySyncPausedTimeout = setTimeout(() => {
959
+ if (!historySyncStatus.recentSyncComplete) {
960
+ historySyncStatus.recentSyncComplete = true;
961
+ ev.emit('messaging-history.status', {
962
+ syncType: proto.HistorySync.HistorySyncType.RECENT,
963
+ status: 'paused',
964
+ explicit: false
965
+ });
966
+ }
967
+ historySyncPausedTimeout = undefined;
968
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
969
+ }
970
+ }
971
+ // State machine: decide on sync and flush
972
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
973
+ if (awaitingSyncTimeout) {
974
+ clearTimeout(awaitingSyncTimeout);
975
+ awaitingSyncTimeout = undefined;
976
+ }
977
+ if (shouldProcessHistoryMsg) {
978
+ syncState = SyncState.Syncing;
979
+ logger.info('Transitioned to Syncing state');
980
+ // Let doAppStateSync handle the final flush after it's done
981
+ }
982
+ else {
983
+ syncState = SyncState.Online;
984
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
985
+ ev.flush();
986
+ }
987
+ }
988
+ const doAppStateSync = async () => {
989
+ if (syncState === SyncState.Syncing) {
990
+ // All collections will be synced, so clear any blocked ones
991
+ blockedCollections.clear();
992
+ logger.info('Doing app state sync');
993
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
994
+ // Sync is complete, go online and flush everything
995
+ syncState = SyncState.Online;
996
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
997
+ ev.flush();
998
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
999
+ ev.emit('creds.update', { accountSyncCounter });
1000
+ }
1001
+ };
1002
+ await Promise.all([
1003
+ (async () => {
1004
+ if (shouldProcessHistoryMsg) {
1005
+ await doAppStateSync();
1006
+ }
1007
+ })(),
1008
+ processMessage(msg, {
1009
+ signalRepository,
1010
+ shouldProcessHistoryMsg,
1011
+ placeholderResendCache,
1012
+ ev,
1013
+ creds: authState.creds,
1014
+ keyStore: authState.keys,
1015
+ logger,
1016
+ options: config.options,
1017
+ getMessage
1018
+ })
1019
+ ]);
1020
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
1021
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1022
+ logger.info('App state sync key arrived, triggering app state sync');
1023
+ await doAppStateSync();
1024
+ }
1025
+ });
1026
+ ws.on('CB:presence', handlePresenceUpdate);
1027
+ ws.on('CB:chatstate', handlePresenceUpdate);
1028
+ ws.on('CB:ib,,dirty', async (node) => {
1029
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
1030
+ const type = attrs.type;
1031
+ switch (type) {
1032
+ case 'account_sync':
1033
+ if (attrs.timestamp) {
1034
+ let { lastAccountSyncTimestamp } = authState.creds;
1035
+ if (lastAccountSyncTimestamp) {
1036
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
1037
+ }
1038
+ lastAccountSyncTimestamp = +attrs.timestamp;
1039
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
1040
+ }
1041
+ break;
1042
+ case 'groups':
1043
+ // handled in groups.ts
1044
+ break;
1045
+ default:
1046
+ logger.info({ node }, 'received unknown sync');
1047
+ break;
1048
+ }
1049
+ });
1050
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1051
+ if (connection === 'close') {
1052
+ blockedCollections.clear();
1053
+ clearTimeout(historySyncPausedTimeout);
1054
+ historySyncPausedTimeout = undefined;
1055
+ }
1056
+ if (connection === 'open') {
1057
+ if (fireInitQueries) {
1058
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
1059
+ }
1060
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
1061
+ }
1062
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1063
+ return;
1064
+ }
1065
+ historySyncStatus.initialBootstrapComplete = false;
1066
+ historySyncStatus.recentSyncComplete = false;
1067
+ clearTimeout(historySyncPausedTimeout);
1068
+ historySyncPausedTimeout = undefined;
1069
+ syncState = SyncState.AwaitingInitialSync;
1070
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
1071
+ ev.buffer();
1072
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1073
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1074
+ }));
1075
+ if (!willSyncHistory) {
1076
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1077
+ syncState = SyncState.Online;
1078
+ setTimeout(() => ev.flush(), 0);
1079
+ return;
1080
+ }
1081
+ // On reconnection (accountSyncCounter > 0), the server does not push
1082
+ // history sync notifications — the device already has its data.
1083
+ // Skip the 20s wait and go online immediately.
1084
+ if (authState.creds.accountSyncCounter > 0) {
1085
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1086
+ syncState = SyncState.Online;
1087
+ setTimeout(() => ev.flush(), 0);
1088
+ return;
1089
+ }
1090
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1091
+ if (awaitingSyncTimeout) {
1092
+ clearTimeout(awaitingSyncTimeout);
1093
+ }
1094
+ awaitingSyncTimeout = setTimeout(() => {
1095
+ if (syncState === SyncState.AwaitingInitialSync) {
1096
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1097
+ syncState = SyncState.Online;
1098
+ ev.flush();
1099
+ // Increment so subsequent reconnections skip the 20s wait.
1100
+ // Late-arriving history is still processed via processMessage
1101
+ // regardless of the state machine phase.
1102
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1103
+ ev.emit('creds.update', { accountSyncCounter });
1104
+ }
1105
+ }, 20000);
708
1106
  });
709
- if (config.emitOwnEvents) {
710
- const {
711
- onMutation
712
- } = newAppStateChunkHandler(false);
713
- const {
714
- mutationMap
715
- } = await (0, _index4.decodePatches)(name, [{
716
- ...encodeResult.patch,
717
- version: {
718
- version: encodeResult.state.version
1107
+ // When an app state sync key arrives (myAppStateKeyId is set) and there are
1108
+ // collections blocked on a missing key, trigger a re-sync for just those collections.
1109
+ // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1110
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
1111
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
1112
+ return;
719
1113
  }
720
- }], initial, getAppStateSyncKey, config.options, undefined, logger);
721
- for (const key in mutationMap) {
722
- onMutation(mutationMap[key]);
723
- }
724
- }
725
- };
726
- /** sending non-abt props may fix QR scan fail if server expects */
727
- const fetchProps = async () => {
728
- const resultNode = await query({
729
- tag: 'iq',
730
- attrs: {
731
- to: _index5.S_WHATSAPP_NET,
732
- xmlns: 'w',
733
- type: 'get'
734
- },
735
- content: [{
736
- tag: 'props',
737
- attrs: {
738
- protocol: '2',
739
- hash: authState?.creds?.lastPropHash || ''
1114
+ // If we're in the middle of a full sync, doAppStateSync handles all collections
1115
+ if (syncState === SyncState.Syncing) {
1116
+ blockedCollections.clear();
1117
+ return;
740
1118
  }
741
- }]
1119
+ const collections = [...blockedCollections];
1120
+ blockedCollections.clear();
1121
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1122
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
742
1123
  });
743
- const propsNode = (0, _index5.getBinaryNodeChild)(resultNode, 'props');
744
- let props = {};
745
- if (propsNode) {
746
- if (propsNode.attrs?.hash) {
747
- // on some clients, the hash is returning as undefined
748
- authState.creds.lastPropHash = propsNode?.attrs?.hash;
749
- ev.emit('creds.update', authState.creds);
750
- }
751
- props = (0, _index5.reduceBinaryNodeToDictionary)(propsNode, 'prop');
752
- }
753
- logger.debug('fetched props');
754
- return props;
755
- };
756
- /**
757
- * modify a chat -- mark unread, read etc.
758
- * lastMessages must be sorted in reverse chronologically
759
- * requires the last messages till the last message received; required for archive & unread
760
- */
761
- const chatModify = (mod, jid) => {
762
- const patch = (0, _index4.chatModificationToAppPatch)(mod, jid);
763
- return appPatch(patch);
764
- };
765
- /**
766
- * Enable/Disable link preview privacy, not related to baileys link preview generation
767
- */
768
- const updateDisableLinkPreviewsPrivacy = isPreviewsDisabled => {
769
- return chatModify({
770
- disableLinkPreviews: {
771
- isPreviewsDisabled
772
- }
773
- }, '');
774
- };
775
- /**
776
- * Star or Unstar a message
777
- */
778
- const star = (jid, messages, star) => {
779
- return chatModify({
780
- star: {
781
- messages,
782
- star
783
- }
784
- }, jid);
785
- };
786
- /**
787
- * Add or Edit Contact
788
- */
789
- const addOrEditContact = (jid, contact) => {
790
- return chatModify({
791
- contact
792
- }, jid);
793
- };
794
- /**
795
- * Remove Contact
796
- */
797
- const removeContact = jid => {
798
- return chatModify({
799
- contact: null
800
- }, jid);
801
- };
802
- /**
803
- * Adds label
804
- */
805
- const addLabel = (jid, labels) => {
806
- return chatModify({
807
- addLabel: {
808
- ...labels
809
- }
810
- }, jid);
811
- };
812
- /**
813
- * Adds label for the chats
814
- */
815
- const addChatLabel = (jid, labelId) => {
816
- return chatModify({
817
- addChatLabel: {
818
- labelId
819
- }
820
- }, jid);
821
- };
822
- /**
823
- * Removes label for the chat
824
- */
825
- const removeChatLabel = (jid, labelId) => {
826
- return chatModify({
827
- removeChatLabel: {
828
- labelId
829
- }
830
- }, jid);
831
- };
832
- /**
833
- * Adds label for the message
834
- */
835
- const addMessageLabel = (jid, messageId, labelId) => {
836
- return chatModify({
837
- addMessageLabel: {
838
- messageId,
839
- labelId
840
- }
841
- }, jid);
842
- };
843
- /**
844
- * Removes label for the message
845
- */
846
- const removeMessageLabel = (jid, messageId, labelId) => {
847
- return chatModify({
848
- removeMessageLabel: {
849
- messageId,
850
- labelId
851
- }
852
- }, jid);
853
- };
854
- /**
855
- * Add or Edit Quick Reply
856
- */
857
- const addOrEditQuickReply = quickReply => {
858
- return chatModify({
859
- quickReply
860
- }, '');
861
- };
862
- /**
863
- * Remove Quick Reply
864
- */
865
- const removeQuickReply = timestamp => {
866
- return chatModify({
867
- quickReply: {
868
- timestamp,
869
- deleted: true
870
- }
871
- }, '');
872
- };
873
- /**
874
- * queries need to be fired on connection open
875
- * help ensure parity with WA Web
876
- * */
877
- const executeInitQueries = async () => {
878
- await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
879
- };
880
- const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
881
- ev.emit('messages.upsert', {
882
- messages: [msg],
883
- type
1124
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1125
+ try {
1126
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1127
+ }
1128
+ catch (error) {
1129
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1130
+ }
884
1131
  });
885
- if (!!msg.pushName) {
886
- let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
887
- jid = (0, _index5.jidNormalizedUser)(jid);
888
- if (!msg.key.fromMe) {
889
- ev.emit('contacts.update', [{
890
- id: jid,
891
- notify: msg.pushName,
892
- verifiedName: msg.verifiedBizName
893
- }]);
894
- }
895
- // update our pushname too
896
- if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
897
- ev.emit('creds.update', {
898
- me: {
899
- ...authState.creds.me,
900
- name: msg.pushName
901
- }
902
- });
903
- }
904
- }
905
- const historyMsg = (0, _index4.getHistoryMsg)(msg.message);
906
- const shouldProcessHistoryMsg = historyMsg ? shouldSyncHistoryMessage(historyMsg) && _index2.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType) : false;
907
- // State machine: decide on sync and flush
908
- if (historyMsg && syncState === _State.SyncState.AwaitingInitialSync) {
909
- if (awaitingSyncTimeout) {
910
- clearTimeout(awaitingSyncTimeout);
911
- awaitingSyncTimeout = undefined;
912
- }
913
- if (shouldProcessHistoryMsg) {
914
- syncState = _State.SyncState.Syncing;
915
- logger.info('Transitioned to Syncing state');
916
- // Let doAppStateSync handle the final flush after it's done
917
- } else {
918
- syncState = _State.SyncState.Online;
919
- logger.info('History sync skipped, transitioning to Online state and flushing buffer');
920
- ev.flush();
921
- }
922
- }
923
- const doAppStateSync = async () => {
924
- if (syncState === _State.SyncState.Syncing) {
925
- logger.info('Doing app state sync');
926
- await resyncAppState(_index3.ALL_WA_PATCH_NAMES, true);
927
- // Sync is complete, go online and flush everything
928
- syncState = _State.SyncState.Online;
929
- logger.info('App state sync complete, transitioning to Online state and flushing buffer');
930
- ev.flush();
931
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
932
- ev.emit('creds.update', {
933
- accountSyncCounter
934
- });
935
- }
936
- };
937
- await Promise.all([(async () => {
938
- if (shouldProcessHistoryMsg) {
939
- await doAppStateSync();
940
- }
941
- })(), (0, _processMessage.default)(msg, {
942
- signalRepository,
943
- shouldProcessHistoryMsg,
944
- placeholderResendCache,
945
- ev,
946
- creds: authState.creds,
947
- keyStore: authState.keys,
948
- logger,
949
- options: config.options
950
- })]);
951
- // If the app state key arrives and we are waiting to sync, trigger the sync now.
952
- if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === _State.SyncState.Syncing) {
953
- logger.info('App state sync key arrived, triggering app state sync');
954
- await doAppStateSync();
955
- }
956
- });
957
- ws.on('CB:presence', handlePresenceUpdate);
958
- ws.on('CB:chatstate', handlePresenceUpdate);
959
- ws.on('CB:ib,,dirty', async node => {
960
- const {
961
- attrs
962
- } = (0, _index5.getBinaryNodeChild)(node, 'dirty');
963
- const type = attrs.type;
964
- switch (type) {
965
- case 'account_sync':
966
- if (attrs.timestamp) {
967
- let {
968
- lastAccountSyncTimestamp
969
- } = authState.creds;
970
- if (lastAccountSyncTimestamp) {
971
- await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
972
- }
973
- lastAccountSyncTimestamp = +attrs.timestamp;
974
- ev.emit('creds.update', {
975
- lastAccountSyncTimestamp
976
- });
1132
+ registerSocketEndHandler(() => {
1133
+ if (awaitingSyncTimeout) {
1134
+ clearTimeout(awaitingSyncTimeout);
1135
+ awaitingSyncTimeout = undefined;
1136
+ }
1137
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
1138
+ placeholderResendCache.close();
977
1139
  }
978
- break;
979
- case 'groups':
980
- // handled in groups.ts
981
- break;
982
- default:
983
- logger.info({
984
- node
985
- }, 'received unknown sync');
986
- break;
987
- }
988
- });
989
- ev.on('connection.update', ({
990
- connection,
991
- receivedPendingNotifications
992
- }) => {
993
- if (connection === 'open') {
994
- if (fireInitQueries) {
995
- executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
996
- }
997
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
998
- }
999
- if (!receivedPendingNotifications || syncState !== _State.SyncState.Connecting) {
1000
- return;
1001
- }
1002
- syncState = _State.SyncState.AwaitingInitialSync;
1003
- logger.info('Connection is now AwaitingInitialSync, buffering events');
1004
- ev.buffer();
1005
- const willSyncHistory = shouldSyncHistoryMessage(_index.proto.Message.HistorySyncNotification.create({
1006
- syncType: _index.proto.HistorySync.HistorySyncType.RECENT
1007
- }));
1008
- if (!willSyncHistory) {
1009
- logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1010
- syncState = _State.SyncState.Online;
1011
- setTimeout(() => ev.flush(), 0);
1012
- return;
1013
- }
1014
- logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1015
- if (awaitingSyncTimeout) {
1016
- clearTimeout(awaitingSyncTimeout);
1017
- }
1018
- awaitingSyncTimeout = setTimeout(() => {
1019
- if (syncState === _State.SyncState.AwaitingInitialSync) {
1020
- logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1021
- syncState = _State.SyncState.Online;
1022
- ev.flush();
1023
- }
1024
- }, 20000);
1025
- });
1026
- return {
1027
- ...sock,
1028
- createCallLink,
1029
- getBotListV2,
1030
- processingMutex,
1031
- fetchPrivacySettings,
1032
- upsertMessage,
1033
- appPatch,
1034
- sendPresenceUpdate,
1035
- presenceSubscribe,
1036
- profilePictureUrl,
1037
- fetchBlocklist,
1038
- fetchStatus,
1039
- fetchDisappearingDuration,
1040
- updateProfilePicture,
1041
- removeProfilePicture,
1042
- updateProfileStatus,
1043
- updateProfileName,
1044
- updateBlockStatus,
1045
- updateDisableLinkPreviewsPrivacy,
1046
- updateCallPrivacy,
1047
- updateMessagesPrivacy,
1048
- updateLastSeenPrivacy,
1049
- updateOnlinePrivacy,
1050
- updateProfilePicturePrivacy,
1051
- updateStatusPrivacy,
1052
- updateReadReceiptsPrivacy,
1053
- updateGroupsAddPrivacy,
1054
- updateDefaultDisappearingMode,
1055
- getBusinessProfile,
1056
- resyncAppState,
1057
- chatModify,
1058
- cleanDirtyBits,
1059
- addOrEditContact,
1060
- removeContact,
1061
- addLabel,
1062
- addChatLabel,
1063
- removeChatLabel,
1064
- addMessageLabel,
1065
- removeMessageLabel,
1066
- star,
1067
- addOrEditQuickReply,
1068
- removeQuickReply
1069
- };
1140
+ syncState = SyncState.Connecting;
1141
+ privacySettings = undefined;
1142
+ });
1143
+ return {
1144
+ ...sock,
1145
+ serverProps,
1146
+ createCallLink,
1147
+ getBotListV2,
1148
+ messageMutex,
1149
+ receiptMutex,
1150
+ appStatePatchMutex,
1151
+ notificationMutex,
1152
+ fetchPrivacySettings,
1153
+ upsertMessage,
1154
+ appPatch,
1155
+ sendPresenceUpdate,
1156
+ presenceSubscribe,
1157
+ profilePictureUrl,
1158
+ fetchBlocklist,
1159
+ fetchStatus,
1160
+ fetchDisappearingDuration,
1161
+ updateProfilePicture,
1162
+ removeProfilePicture,
1163
+ updateProfileStatus,
1164
+ updateProfileName,
1165
+ updateBlockStatus,
1166
+ updateDisableLinkPreviewsPrivacy,
1167
+ updateCallPrivacy,
1168
+ updateMessagesPrivacy,
1169
+ updateLastSeenPrivacy,
1170
+ updateOnlinePrivacy,
1171
+ updateProfilePicturePrivacy,
1172
+ updateStatusPrivacy,
1173
+ updateReadReceiptsPrivacy,
1174
+ updateGroupsAddPrivacy,
1175
+ updateDefaultDisappearingMode,
1176
+ getBusinessProfile,
1177
+ resyncAppState,
1178
+ chatModify,
1179
+ cleanDirtyBits,
1180
+ addOrEditContact,
1181
+ removeContact,
1182
+ placeholderResendCache,
1183
+ addLabel,
1184
+ addChatLabel,
1185
+ removeChatLabel,
1186
+ addMessageLabel,
1187
+ removeMessageLabel,
1188
+ star,
1189
+ addOrEditQuickReply,
1190
+ removeQuickReply
1191
+ };
1070
1192
  };
1071
- //# sourceMappingURL=chats.js.map
1072
- exports.makeChatsSocket = makeChatsSocket;
1193
+ //# sourceMappingURL=chats.js.map