@kelvdra/baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (385) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1478 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/fix-imports.js +29 -0
  6. package/WAProto/index.d.ts +37016 -0
  7. package/WAProto/index.js +169659 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +62 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +115 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +82 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +26 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +342 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +171 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +50 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +188 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +376 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +98 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +962 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +244 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +431 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +137 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +327 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/hydra.d.ts +174 -0
  98. package/lib/Socket/hydra.js +715 -0
  99. package/lib/Socket/index.d.ts +231 -0
  100. package/lib/Socket/index.d.ts.map +1 -0
  101. package/lib/Socket/index.js +18 -0
  102. package/lib/Socket/index.js.map +1 -0
  103. package/lib/Socket/messages-recv.d.ts +173 -0
  104. package/lib/Socket/messages-recv.d.ts.map +1 -0
  105. package/lib/Socket/messages-recv.js +1228 -0
  106. package/lib/Socket/messages-recv.js.map +1 -0
  107. package/lib/Socket/messages-send.d.ts +169 -0
  108. package/lib/Socket/messages-send.d.ts.map +1 -0
  109. package/lib/Socket/messages-send.js +1367 -0
  110. package/lib/Socket/messages-send.js.map +1 -0
  111. package/lib/Socket/mex.d.ts +3 -0
  112. package/lib/Socket/mex.d.ts.map +1 -0
  113. package/lib/Socket/mex.js +42 -0
  114. package/lib/Socket/mex.js.map +1 -0
  115. package/lib/Socket/newsletter.d.ts +147 -0
  116. package/lib/Socket/newsletter.d.ts.map +1 -0
  117. package/lib/Socket/newsletter.js +181 -0
  118. package/lib/Socket/newsletter.js.map +1 -0
  119. package/lib/Socket/socket.d.ts +51 -0
  120. package/lib/Socket/socket.d.ts.map +1 -0
  121. package/lib/Socket/socket.js +841 -0
  122. package/lib/Socket/socket.js.map +1 -0
  123. package/lib/Store/index.d.ts +4 -0
  124. package/lib/Store/index.js +4 -0
  125. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  126. package/lib/Store/make-cache-manager-store.js +81 -0
  127. package/lib/Store/make-in-memory-store.d.ts +123 -0
  128. package/lib/Store/make-in-memory-store.js +416 -0
  129. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  130. package/lib/Store/make-ordered-dictionary.js +82 -0
  131. package/lib/Store/object-repository.d.ts +10 -0
  132. package/lib/Store/object-repository.js +31 -0
  133. package/lib/Types/Auth.d.ts +111 -0
  134. package/lib/Types/Auth.d.ts.map +1 -0
  135. package/lib/Types/Auth.js +2 -0
  136. package/lib/Types/Auth.js.map +1 -0
  137. package/lib/Types/Bussines.d.ts +25 -0
  138. package/lib/Types/Bussines.d.ts.map +1 -0
  139. package/lib/Types/Bussines.js +2 -0
  140. package/lib/Types/Bussines.js.map +1 -0
  141. package/lib/Types/Call.d.ts +14 -0
  142. package/lib/Types/Call.d.ts.map +1 -0
  143. package/lib/Types/Call.js +2 -0
  144. package/lib/Types/Call.js.map +1 -0
  145. package/lib/Types/Chat.d.ts +123 -0
  146. package/lib/Types/Chat.d.ts.map +1 -0
  147. package/lib/Types/Chat.js +8 -0
  148. package/lib/Types/Chat.js.map +1 -0
  149. package/lib/Types/Contact.d.ts +24 -0
  150. package/lib/Types/Contact.d.ts.map +1 -0
  151. package/lib/Types/Contact.js +2 -0
  152. package/lib/Types/Contact.js.map +1 -0
  153. package/lib/Types/Events.d.ts +202 -0
  154. package/lib/Types/Events.d.ts.map +1 -0
  155. package/lib/Types/Events.js +2 -0
  156. package/lib/Types/Events.js.map +1 -0
  157. package/lib/Types/GroupMetadata.d.ts +67 -0
  158. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  159. package/lib/Types/GroupMetadata.js +2 -0
  160. package/lib/Types/GroupMetadata.js.map +1 -0
  161. package/lib/Types/Label.d.ts +47 -0
  162. package/lib/Types/Label.d.ts.map +1 -0
  163. package/lib/Types/Label.js +25 -0
  164. package/lib/Types/Label.js.map +1 -0
  165. package/lib/Types/LabelAssociation.d.ts +30 -0
  166. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  167. package/lib/Types/LabelAssociation.js +7 -0
  168. package/lib/Types/LabelAssociation.js.map +1 -0
  169. package/lib/Types/Message.d.ts +303 -0
  170. package/lib/Types/Message.d.ts.map +1 -0
  171. package/lib/Types/Message.js +11 -0
  172. package/lib/Types/Message.js.map +1 -0
  173. package/lib/Types/Newsletter.d.ts +135 -0
  174. package/lib/Types/Newsletter.d.ts.map +1 -0
  175. package/lib/Types/Newsletter.js +31 -0
  176. package/lib/Types/Newsletter.js.map +1 -0
  177. package/lib/Types/Product.d.ts +79 -0
  178. package/lib/Types/Product.d.ts.map +1 -0
  179. package/lib/Types/Product.js +2 -0
  180. package/lib/Types/Product.js.map +1 -0
  181. package/lib/Types/Signal.d.ts +76 -0
  182. package/lib/Types/Signal.d.ts.map +1 -0
  183. package/lib/Types/Signal.js +2 -0
  184. package/lib/Types/Signal.js.map +1 -0
  185. package/lib/Types/Socket.d.ts +133 -0
  186. package/lib/Types/Socket.d.ts.map +1 -0
  187. package/lib/Types/Socket.js +3 -0
  188. package/lib/Types/Socket.js.map +1 -0
  189. package/lib/Types/State.d.ts +39 -0
  190. package/lib/Types/State.d.ts.map +1 -0
  191. package/lib/Types/State.js +13 -0
  192. package/lib/Types/State.js.map +1 -0
  193. package/lib/Types/USync.d.ts +26 -0
  194. package/lib/Types/USync.d.ts.map +1 -0
  195. package/lib/Types/USync.js +2 -0
  196. package/lib/Types/USync.js.map +1 -0
  197. package/lib/Types/index.d.ts +65 -0
  198. package/lib/Types/index.d.ts.map +1 -0
  199. package/lib/Types/index.js +26 -0
  200. package/lib/Types/index.js.map +1 -0
  201. package/lib/Utils/auth-utils.d.ts +19 -0
  202. package/lib/Utils/auth-utils.d.ts.map +1 -0
  203. package/lib/Utils/auth-utils.js +257 -0
  204. package/lib/Utils/auth-utils.js.map +1 -0
  205. package/lib/Utils/baileys-event-stream.d.ts +17 -0
  206. package/lib/Utils/baileys-event-stream.d.ts.map +1 -0
  207. package/lib/Utils/baileys-event-stream.js +56 -0
  208. package/lib/Utils/baileys-event-stream.js.map +1 -0
  209. package/lib/Utils/browser-utils.d.ts +4 -0
  210. package/lib/Utils/browser-utils.d.ts.map +1 -0
  211. package/lib/Utils/browser-utils.js +28 -0
  212. package/lib/Utils/browser-utils.js.map +1 -0
  213. package/lib/Utils/business.d.ts +23 -0
  214. package/lib/Utils/business.d.ts.map +1 -0
  215. package/lib/Utils/business.js +231 -0
  216. package/lib/Utils/business.js.map +1 -0
  217. package/lib/Utils/chat-utils.d.ts +70 -0
  218. package/lib/Utils/chat-utils.d.ts.map +1 -0
  219. package/lib/Utils/chat-utils.js +763 -0
  220. package/lib/Utils/chat-utils.js.map +1 -0
  221. package/lib/Utils/crypto.d.ts +41 -0
  222. package/lib/Utils/crypto.d.ts.map +1 -0
  223. package/lib/Utils/crypto.js +142 -0
  224. package/lib/Utils/crypto.js.map +1 -0
  225. package/lib/Utils/decode-wa-message.d.ts +48 -0
  226. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  227. package/lib/Utils/decode-wa-message.js +279 -0
  228. package/lib/Utils/decode-wa-message.js.map +1 -0
  229. package/lib/Utils/event-buffer.d.ts +34 -0
  230. package/lib/Utils/event-buffer.d.ts.map +1 -0
  231. package/lib/Utils/event-buffer.js +548 -0
  232. package/lib/Utils/event-buffer.js.map +1 -0
  233. package/lib/Utils/generics.d.ts +90 -0
  234. package/lib/Utils/generics.d.ts.map +1 -0
  235. package/lib/Utils/generics.js +381 -0
  236. package/lib/Utils/generics.js.map +1 -0
  237. package/lib/Utils/history.d.ts +19 -0
  238. package/lib/Utils/history.d.ts.map +1 -0
  239. package/lib/Utils/history.js +84 -0
  240. package/lib/Utils/history.js.map +1 -0
  241. package/lib/Utils/index.d.ts +20 -0
  242. package/lib/Utils/index.d.ts.map +1 -0
  243. package/lib/Utils/index.js +20 -0
  244. package/lib/Utils/index.js.map +1 -0
  245. package/lib/Utils/link-preview.d.ts +21 -0
  246. package/lib/Utils/link-preview.d.ts.map +1 -0
  247. package/lib/Utils/link-preview.js +85 -0
  248. package/lib/Utils/link-preview.js.map +1 -0
  249. package/lib/Utils/logger.d.ts +12 -0
  250. package/lib/Utils/logger.d.ts.map +1 -0
  251. package/lib/Utils/logger.js +3 -0
  252. package/lib/Utils/logger.js.map +1 -0
  253. package/lib/Utils/lt-hash.d.ts +13 -0
  254. package/lib/Utils/lt-hash.d.ts.map +1 -0
  255. package/lib/Utils/lt-hash.js +48 -0
  256. package/lib/Utils/lt-hash.js.map +1 -0
  257. package/lib/Utils/make-mutex.d.ts +8 -0
  258. package/lib/Utils/make-mutex.d.ts.map +1 -0
  259. package/lib/Utils/make-mutex.js +40 -0
  260. package/lib/Utils/make-mutex.js.map +1 -0
  261. package/lib/Utils/message-retry-manager.d.ts +82 -0
  262. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  263. package/lib/Utils/message-retry-manager.js +149 -0
  264. package/lib/Utils/message-retry-manager.js.map +1 -0
  265. package/lib/Utils/messages-media.d.ts +114 -0
  266. package/lib/Utils/messages-media.d.ts.map +1 -0
  267. package/lib/Utils/messages-media.js +684 -0
  268. package/lib/Utils/messages-media.js.map +1 -0
  269. package/lib/Utils/messages.d.ts +76 -0
  270. package/lib/Utils/messages.d.ts.map +1 -0
  271. package/lib/Utils/messages.js +820 -0
  272. package/lib/Utils/messages.js.map +1 -0
  273. package/lib/Utils/noise-handler.d.ts +20 -0
  274. package/lib/Utils/noise-handler.d.ts.map +1 -0
  275. package/lib/Utils/noise-handler.js +147 -0
  276. package/lib/Utils/noise-handler.js.map +1 -0
  277. package/lib/Utils/pre-key-manager.d.ts +28 -0
  278. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  279. package/lib/Utils/pre-key-manager.js +106 -0
  280. package/lib/Utils/pre-key-manager.js.map +1 -0
  281. package/lib/Utils/process-message.d.ts +42 -0
  282. package/lib/Utils/process-message.d.ts.map +1 -0
  283. package/lib/Utils/process-message.js +413 -0
  284. package/lib/Utils/process-message.js.map +1 -0
  285. package/lib/Utils/signal.d.ts +34 -0
  286. package/lib/Utils/signal.d.ts.map +1 -0
  287. package/lib/Utils/signal.js +159 -0
  288. package/lib/Utils/signal.js.map +1 -0
  289. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  290. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  291. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  292. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  293. package/lib/Utils/validate-connection.d.ts +11 -0
  294. package/lib/Utils/validate-connection.d.ts.map +1 -0
  295. package/lib/Utils/validate-connection.js +195 -0
  296. package/lib/Utils/validate-connection.js.map +1 -0
  297. package/lib/WABinary/constants.d.ts +28 -0
  298. package/lib/WABinary/constants.d.ts.map +1 -0
  299. package/lib/WABinary/constants.js +1301 -0
  300. package/lib/WABinary/constants.js.map +1 -0
  301. package/lib/WABinary/decode.d.ts +7 -0
  302. package/lib/WABinary/decode.d.ts.map +1 -0
  303. package/lib/WABinary/decode.js +238 -0
  304. package/lib/WABinary/decode.js.map +1 -0
  305. package/lib/WABinary/encode.d.ts +3 -0
  306. package/lib/WABinary/encode.d.ts.map +1 -0
  307. package/lib/WABinary/encode.js +216 -0
  308. package/lib/WABinary/encode.js.map +1 -0
  309. package/lib/WABinary/generic-utils.d.ts +15 -0
  310. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  311. package/lib/WABinary/generic-utils.js +111 -0
  312. package/lib/WABinary/generic-utils.js.map +1 -0
  313. package/lib/WABinary/index.d.ts +6 -0
  314. package/lib/WABinary/index.d.ts.map +1 -0
  315. package/lib/WABinary/index.js +6 -0
  316. package/lib/WABinary/index.js.map +1 -0
  317. package/lib/WABinary/jid-utils.d.ts +48 -0
  318. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  319. package/lib/WABinary/jid-utils.js +96 -0
  320. package/lib/WABinary/jid-utils.js.map +1 -0
  321. package/lib/WABinary/types.d.ts +19 -0
  322. package/lib/WABinary/types.d.ts.map +1 -0
  323. package/lib/WABinary/types.js +2 -0
  324. package/lib/WABinary/types.js.map +1 -0
  325. package/lib/WAM/BinaryInfo.d.ts +9 -0
  326. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  327. package/lib/WAM/BinaryInfo.js +10 -0
  328. package/lib/WAM/BinaryInfo.js.map +1 -0
  329. package/lib/WAM/constants.d.ts +40 -0
  330. package/lib/WAM/constants.d.ts.map +1 -0
  331. package/lib/WAM/constants.js +22853 -0
  332. package/lib/WAM/constants.js.map +1 -0
  333. package/lib/WAM/encode.d.ts +3 -0
  334. package/lib/WAM/encode.d.ts.map +1 -0
  335. package/lib/WAM/encode.js +150 -0
  336. package/lib/WAM/encode.js.map +1 -0
  337. package/lib/WAM/index.d.ts +4 -0
  338. package/lib/WAM/index.d.ts.map +1 -0
  339. package/lib/WAM/index.js +4 -0
  340. package/lib/WAM/index.js.map +1 -0
  341. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  342. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  343. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  344. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  345. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  346. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  347. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  348. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  349. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  350. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  351. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  352. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  353. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  354. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  355. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  356. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  357. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  358. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  360. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  362. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  364. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  366. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/index.js +5 -0
  368. package/lib/WAUSync/Protocols/index.js.map +1 -0
  369. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  370. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  371. package/lib/WAUSync/USyncQuery.js +94 -0
  372. package/lib/WAUSync/USyncQuery.js.map +1 -0
  373. package/lib/WAUSync/USyncUser.d.ts +13 -0
  374. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  375. package/lib/WAUSync/USyncUser.js +23 -0
  376. package/lib/WAUSync/USyncUser.js.map +1 -0
  377. package/lib/WAUSync/index.d.ts +4 -0
  378. package/lib/WAUSync/index.d.ts.map +1 -0
  379. package/lib/WAUSync/index.js +4 -0
  380. package/lib/WAUSync/index.js.map +1 -0
  381. package/lib/index.d.ts +13 -0
  382. package/lib/index.d.ts.map +1 -0
  383. package/lib/index.js +12 -0
  384. package/lib/index.js.map +1 -0
  385. package/package.json +104 -0
@@ -0,0 +1,962 @@
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, 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, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
8
+ import { makeMutex } from '../Utils/make-mutex.js';
9
+ import processMessage from '../Utils/process-message.js';
10
+ import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
+ import { makeSocket } from './socket.js';
13
+ const MAX_SYNC_ATTEMPTS = 2;
14
+ export const makeChatsSocket = (config) => {
15
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage } = config;
16
+ const sock = makeSocket(config);
17
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError } = sock;
18
+ let privacySettings;
19
+ let syncState = SyncState.Connecting;
20
+ /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
21
+ const processingMutex = makeMutex();
22
+ // Timeout for AwaitingInitialSync state
23
+ let awaitingSyncTimeout;
24
+ const placeholderResendCache = config.placeholderResendCache ||
25
+ new NodeCache({
26
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
27
+ useClones: false
28
+ });
29
+ if (!config.placeholderResendCache) {
30
+ config.placeholderResendCache = placeholderResendCache;
31
+ }
32
+ /** helper function to fetch the given app state sync key */
33
+ const getAppStateSyncKey = async (keyId) => {
34
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
35
+ return key;
36
+ };
37
+ const fetchPrivacySettings = async (force = false) => {
38
+ if (!privacySettings || force) {
39
+ const { content } = await query({
40
+ tag: 'iq',
41
+ attrs: {
42
+ xmlns: 'privacy',
43
+ to: S_WHATSAPP_NET,
44
+ type: 'get'
45
+ },
46
+ content: [{ tag: 'privacy', attrs: {} }]
47
+ });
48
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
49
+ }
50
+ return privacySettings;
51
+ };
52
+ /** helper function to run a privacy IQ query */
53
+ const privacyQuery = async (name, value) => {
54
+ await query({
55
+ tag: 'iq',
56
+ attrs: {
57
+ xmlns: 'privacy',
58
+ to: S_WHATSAPP_NET,
59
+ type: 'set'
60
+ },
61
+ content: [
62
+ {
63
+ tag: 'privacy',
64
+ attrs: {},
65
+ content: [
66
+ {
67
+ tag: 'category',
68
+ attrs: { name, value }
69
+ }
70
+ ]
71
+ }
72
+ ]
73
+ });
74
+ };
75
+ const updateMessagesPrivacy = async (value) => {
76
+ await privacyQuery('messages', value);
77
+ };
78
+ const updateCallPrivacy = async (value) => {
79
+ await privacyQuery('calladd', value);
80
+ };
81
+ const updateLastSeenPrivacy = async (value) => {
82
+ await privacyQuery('last', value);
83
+ };
84
+ const updateOnlinePrivacy = async (value) => {
85
+ await privacyQuery('online', value);
86
+ };
87
+ const updateProfilePicturePrivacy = async (value) => {
88
+ await privacyQuery('profile', value);
89
+ };
90
+ const updateStatusPrivacy = async (value) => {
91
+ await privacyQuery('status', value);
92
+ };
93
+ const updateReadReceiptsPrivacy = async (value) => {
94
+ await privacyQuery('readreceipts', value);
95
+ };
96
+ const updateGroupsAddPrivacy = async (value) => {
97
+ await privacyQuery('groupadd', value);
98
+ };
99
+ const updateDefaultDisappearingMode = async (duration) => {
100
+ await query({
101
+ tag: 'iq',
102
+ attrs: {
103
+ xmlns: 'disappearing_mode',
104
+ to: S_WHATSAPP_NET,
105
+ type: 'set'
106
+ },
107
+ content: [
108
+ {
109
+ tag: 'disappearing_mode',
110
+ attrs: {
111
+ duration: duration.toString()
112
+ }
113
+ }
114
+ ]
115
+ });
116
+ };
117
+ const getBotListV2 = async () => {
118
+ const resp = await query({
119
+ tag: 'iq',
120
+ attrs: {
121
+ xmlns: 'bot',
122
+ to: S_WHATSAPP_NET,
123
+ type: 'get'
124
+ },
125
+ content: [
126
+ {
127
+ tag: 'bot',
128
+ attrs: {
129
+ v: '2'
130
+ }
131
+ }
132
+ ]
133
+ });
134
+ const botNode = getBinaryNodeChild(resp, 'bot');
135
+ const botList = [];
136
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
137
+ if (section.attrs.type === 'all') {
138
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
139
+ botList.push({
140
+ jid: bot.attrs.jid,
141
+ personaId: bot.attrs['persona_id']
142
+ });
143
+ }
144
+ }
145
+ }
146
+ return botList;
147
+ };
148
+ const fetchStatus = async (...jids) => {
149
+ const usyncQuery = new USyncQuery().withStatusProtocol();
150
+ for (const jid of jids) {
151
+ usyncQuery.withUser(new USyncUser().withId(jid));
152
+ }
153
+ const result = await sock.executeUSyncQuery(usyncQuery);
154
+ if (result) {
155
+ return result.list;
156
+ }
157
+ };
158
+ const fetchDisappearingDuration = async (...jids) => {
159
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
160
+ for (const jid of jids) {
161
+ usyncQuery.withUser(new USyncUser().withId(jid));
162
+ }
163
+ const result = await sock.executeUSyncQuery(usyncQuery);
164
+ if (result) {
165
+ return result.list;
166
+ }
167
+ };
168
+ /** update the profile picture for yourself or a group */
169
+ const updateProfilePicture = async (jid, content, dimensions) => {
170
+ let targetJid;
171
+ if (!jid) {
172
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
173
+ }
174
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
175
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
176
+ }
177
+ else {
178
+ targetJid = undefined;
179
+ }
180
+ const { img } = await generateProfilePicture(content, dimensions);
181
+ await query({
182
+ tag: 'iq',
183
+ attrs: {
184
+ to: S_WHATSAPP_NET,
185
+ type: 'set',
186
+ xmlns: 'w:profile:picture',
187
+ ...(targetJid ? { target: targetJid } : {})
188
+ },
189
+ content: [
190
+ {
191
+ tag: 'picture',
192
+ attrs: { type: 'image' },
193
+ content: img
194
+ }
195
+ ]
196
+ });
197
+ };
198
+ /** remove the profile picture for yourself or a group */
199
+ const removeProfilePicture = async (jid) => {
200
+ let targetJid;
201
+ if (!jid) {
202
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
203
+ }
204
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
205
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
206
+ }
207
+ else {
208
+ targetJid = undefined;
209
+ }
210
+ await query({
211
+ tag: 'iq',
212
+ attrs: {
213
+ to: S_WHATSAPP_NET,
214
+ type: 'set',
215
+ xmlns: 'w:profile:picture',
216
+ ...(targetJid ? { target: targetJid } : {})
217
+ }
218
+ });
219
+ };
220
+ /** update the profile status for yourself */
221
+ const updateProfileStatus = async (status) => {
222
+ await query({
223
+ tag: 'iq',
224
+ attrs: {
225
+ to: S_WHATSAPP_NET,
226
+ type: 'set',
227
+ xmlns: 'status'
228
+ },
229
+ content: [
230
+ {
231
+ tag: 'status',
232
+ attrs: {},
233
+ content: Buffer.from(status, 'utf-8')
234
+ }
235
+ ]
236
+ });
237
+ };
238
+ const updateProfileName = async (name) => {
239
+ await chatModify({ pushNameSetting: name }, '');
240
+ };
241
+ const fetchBlocklist = async () => {
242
+ const result = await query({
243
+ tag: 'iq',
244
+ attrs: {
245
+ xmlns: 'blocklist',
246
+ to: S_WHATSAPP_NET,
247
+ type: 'get'
248
+ }
249
+ });
250
+ const listNode = getBinaryNodeChild(result, 'list');
251
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
252
+ };
253
+ const updateBlockStatus = async (jid, action) => {
254
+ await query({
255
+ tag: 'iq',
256
+ attrs: {
257
+ xmlns: 'blocklist',
258
+ to: S_WHATSAPP_NET,
259
+ type: 'set'
260
+ },
261
+ content: [
262
+ {
263
+ tag: 'item',
264
+ attrs: {
265
+ action,
266
+ jid
267
+ }
268
+ }
269
+ ]
270
+ });
271
+ };
272
+ const getBusinessProfile = async (jid) => {
273
+ const results = await query({
274
+ tag: 'iq',
275
+ attrs: {
276
+ to: 's.whatsapp.net',
277
+ xmlns: 'w:biz',
278
+ type: 'get'
279
+ },
280
+ content: [
281
+ {
282
+ tag: 'business_profile',
283
+ attrs: { v: '244' },
284
+ content: [
285
+ {
286
+ tag: 'profile',
287
+ attrs: { jid }
288
+ }
289
+ ]
290
+ }
291
+ ]
292
+ });
293
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
294
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
295
+ if (profiles) {
296
+ const address = getBinaryNodeChild(profiles, 'address');
297
+ const description = getBinaryNodeChild(profiles, 'description');
298
+ const website = getBinaryNodeChild(profiles, 'website');
299
+ const email = getBinaryNodeChild(profiles, 'email');
300
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
301
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
302
+ const businessHoursConfig = businessHours
303
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
304
+ : undefined;
305
+ const websiteStr = website?.content?.toString();
306
+ return {
307
+ wid: profiles.attrs?.jid,
308
+ address: address?.content?.toString(),
309
+ description: description?.content?.toString() || '',
310
+ website: websiteStr ? [websiteStr] : [],
311
+ email: email?.content?.toString(),
312
+ category: category?.content?.toString(),
313
+ business_hours: {
314
+ timezone: businessHours?.attrs?.timezone,
315
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
316
+ }
317
+ };
318
+ }
319
+ };
320
+ const cleanDirtyBits = async (type, fromTimestamp) => {
321
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
322
+ await sendNode({
323
+ tag: 'iq',
324
+ attrs: {
325
+ to: S_WHATSAPP_NET,
326
+ type: 'set',
327
+ xmlns: 'urn:xmpp:whatsapp:dirty',
328
+ id: generateMessageTag()
329
+ },
330
+ content: [
331
+ {
332
+ tag: 'clean',
333
+ attrs: {
334
+ type,
335
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
336
+ }
337
+ }
338
+ ]
339
+ });
340
+ };
341
+ const newAppStateChunkHandler = (isInitialSync) => {
342
+ return {
343
+ onMutation(mutation) {
344
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
345
+ }
346
+ };
347
+ };
348
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
349
+ // we use this to determine which events to fire
350
+ // otherwise when we resync from scratch -- all notifications will fire
351
+ const initialVersionMap = {};
352
+ const globalMutationMap = {};
353
+ await authState.keys.transaction(async () => {
354
+ const collectionsToHandle = new Set(collections);
355
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
356
+ const attemptsMap = {};
357
+ // keep executing till all collections are done
358
+ // sometimes a single patch request will not return all the patches (God knows why)
359
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
360
+ while (collectionsToHandle.size) {
361
+ const states = {};
362
+ const nodes = [];
363
+ for (const name of collectionsToHandle) {
364
+ const result = await authState.keys.get('app-state-sync-version', [name]);
365
+ let state = result[name];
366
+ if (state) {
367
+ if (typeof initialVersionMap[name] === 'undefined') {
368
+ initialVersionMap[name] = state.version;
369
+ }
370
+ }
371
+ else {
372
+ state = newLTHashState();
373
+ }
374
+ states[name] = state;
375
+ logger.info(`resyncing ${name} from v${state.version}`);
376
+ nodes.push({
377
+ tag: 'collection',
378
+ attrs: {
379
+ name,
380
+ version: state.version.toString(),
381
+ // return snapshot if being synced from scratch
382
+ return_snapshot: (!state.version).toString()
383
+ }
384
+ });
385
+ }
386
+ const result = await query({
387
+ tag: 'iq',
388
+ attrs: {
389
+ to: S_WHATSAPP_NET,
390
+ xmlns: 'w:sync:app:state',
391
+ type: 'set'
392
+ },
393
+ content: [
394
+ {
395
+ tag: 'sync',
396
+ attrs: {},
397
+ content: nodes
398
+ }
399
+ ]
400
+ });
401
+ // extract from binary node
402
+ const decoded = await extractSyncdPatches(result, config?.options);
403
+ for (const key in decoded) {
404
+ const name = key;
405
+ const { patches, hasMorePatches, snapshot } = decoded[name];
406
+ try {
407
+ if (snapshot) {
408
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
409
+ states[name] = newState;
410
+ Object.assign(globalMutationMap, mutationMap);
411
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
412
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
413
+ }
414
+ // only process if there are syncd patches
415
+ if (patches.length) {
416
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
417
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
418
+ logger.info(`synced ${name} to v${newState.version}`);
419
+ initialVersionMap[name] = newState.version;
420
+ Object.assign(globalMutationMap, mutationMap);
421
+ }
422
+ if (hasMorePatches) {
423
+ logger.info(`${name} has more patches...`);
424
+ }
425
+ else {
426
+ // collection is done with sync
427
+ collectionsToHandle.delete(name);
428
+ }
429
+ }
430
+ catch (error) {
431
+ // if retry attempts overshoot
432
+ // or key not found
433
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
434
+ error.output?.statusCode === 404 ||
435
+ error.name === 'TypeError';
436
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
437
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
438
+ // increment number of retries
439
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
440
+ if (isIrrecoverableError) {
441
+ // stop retrying
442
+ collectionsToHandle.delete(name);
443
+ }
444
+ }
445
+ }
446
+ }
447
+ }, authState?.creds?.me?.id || 'resync-app-state');
448
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
449
+ for (const key in globalMutationMap) {
450
+ onMutation(globalMutationMap[key]);
451
+ }
452
+ });
453
+ /**
454
+ * fetch the profile picture of a user/group
455
+ * type = "preview" for a low res picture
456
+ * type = "image for the high res picture"
457
+ */
458
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
459
+ // TOOD: Add support for tctoken, existingID, and newsletter + group options
460
+ jid = jidNormalizedUser(jid);
461
+ const result = await query({
462
+ tag: 'iq',
463
+ attrs: {
464
+ target: jid,
465
+ to: S_WHATSAPP_NET,
466
+ type: 'get',
467
+ xmlns: 'w:profile:picture'
468
+ },
469
+ content: [{ tag: 'picture', attrs: { type, query: 'url' } }]
470
+ }, timeoutMs);
471
+ const child = getBinaryNodeChild(result, 'picture');
472
+ return child?.attrs?.url;
473
+ };
474
+ const createCallLink = async (type, event, timeoutMs) => {
475
+ const result = await query({
476
+ tag: 'call',
477
+ attrs: {
478
+ id: generateMessageTag(),
479
+ to: '@call'
480
+ },
481
+ content: [
482
+ {
483
+ tag: 'link_create',
484
+ attrs: { media: type },
485
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
486
+ }
487
+ ]
488
+ }, timeoutMs);
489
+ const child = getBinaryNodeChild(result, 'link_create');
490
+ return child?.attrs?.token;
491
+ };
492
+ const sendPresenceUpdate = async (type, toJid) => {
493
+ const me = authState.creds.me;
494
+ if (type === 'available' || type === 'unavailable') {
495
+ if (!me.name) {
496
+ logger.warn('no name present, ignoring presence update request...');
497
+ return;
498
+ }
499
+ ev.emit('connection.update', { isOnline: type === 'available' });
500
+ await sendNode({
501
+ tag: 'presence',
502
+ attrs: {
503
+ name: me.name.replace(/@/g, ''),
504
+ type
505
+ }
506
+ });
507
+ }
508
+ else {
509
+ const { server } = jidDecode(toJid);
510
+ const isLid = server === 'lid';
511
+ await sendNode({
512
+ tag: 'chatstate',
513
+ attrs: {
514
+ from: isLid ? me.lid : me.id,
515
+ to: toJid
516
+ },
517
+ content: [
518
+ {
519
+ tag: type === 'recording' ? 'composing' : type,
520
+ attrs: type === 'recording' ? { media: 'audio' } : {}
521
+ }
522
+ ]
523
+ });
524
+ }
525
+ };
526
+ /**
527
+ * @param toJid the jid to subscribe to
528
+ * @param tcToken token for subscription, use if present
529
+ */
530
+ const presenceSubscribe = (toJid, tcToken) => sendNode({
531
+ tag: 'presence',
532
+ attrs: {
533
+ to: toJid,
534
+ id: generateMessageTag(),
535
+ type: 'subscribe'
536
+ },
537
+ content: tcToken
538
+ ? [
539
+ {
540
+ tag: 'tctoken',
541
+ attrs: {},
542
+ content: tcToken
543
+ }
544
+ ]
545
+ : undefined
546
+ });
547
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
548
+ let presence;
549
+ const jid = attrs.from;
550
+ const participant = attrs.participant || attrs.from;
551
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
552
+ return;
553
+ }
554
+ if (tag === 'presence') {
555
+ presence = {
556
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
557
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
558
+ };
559
+ }
560
+ else if (Array.isArray(content)) {
561
+ const [firstChild] = content;
562
+ let type = firstChild.tag;
563
+ if (type === 'paused') {
564
+ type = 'available';
565
+ }
566
+ if (firstChild.attrs?.media === 'audio') {
567
+ type = 'recording';
568
+ }
569
+ presence = { lastKnownPresence: type };
570
+ }
571
+ else {
572
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
573
+ }
574
+ if (presence) {
575
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
576
+ }
577
+ };
578
+ const appPatch = async (patchCreate) => {
579
+ const name = patchCreate.type;
580
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
581
+ if (!myAppStateKeyId) {
582
+ throw new Boom('App state key not present!', { statusCode: 400 });
583
+ }
584
+ let initial;
585
+ let encodeResult;
586
+ await processingMutex.mutex(async () => {
587
+ await authState.keys.transaction(async () => {
588
+ logger.debug({ patch: patchCreate }, 'applying app patch');
589
+ await resyncAppState([name], false);
590
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
591
+ initial = currentSyncVersion || newLTHashState();
592
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
593
+ const { patch, state } = encodeResult;
594
+ const node = {
595
+ tag: 'iq',
596
+ attrs: {
597
+ to: S_WHATSAPP_NET,
598
+ type: 'set',
599
+ xmlns: 'w:sync:app:state'
600
+ },
601
+ content: [
602
+ {
603
+ tag: 'sync',
604
+ attrs: {},
605
+ content: [
606
+ {
607
+ tag: 'collection',
608
+ attrs: {
609
+ name,
610
+ version: (state.version - 1).toString(),
611
+ return_snapshot: 'false'
612
+ },
613
+ content: [
614
+ {
615
+ tag: 'patch',
616
+ attrs: {},
617
+ content: proto.SyncdPatch.encode(patch).finish()
618
+ }
619
+ ]
620
+ }
621
+ ]
622
+ }
623
+ ]
624
+ };
625
+ await query(node);
626
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
627
+ }, authState?.creds?.me?.id || 'app-patch');
628
+ });
629
+ if (config.emitOwnEvents) {
630
+ const { onMutation } = newAppStateChunkHandler(false);
631
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
632
+ for (const key in mutationMap) {
633
+ onMutation(mutationMap[key]);
634
+ }
635
+ }
636
+ };
637
+ /** sending non-abt props may fix QR scan fail if server expects */
638
+ const fetchProps = async () => {
639
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
640
+ const resultNode = await query({
641
+ tag: 'iq',
642
+ attrs: {
643
+ to: S_WHATSAPP_NET,
644
+ xmlns: 'w',
645
+ type: 'get'
646
+ },
647
+ content: [
648
+ {
649
+ tag: 'props',
650
+ attrs: {
651
+ protocol: '2',
652
+ hash: authState?.creds?.lastPropHash || ''
653
+ }
654
+ }
655
+ ]
656
+ });
657
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
658
+ let props = {};
659
+ if (propsNode) {
660
+ if (propsNode.attrs?.hash) {
661
+ // on some clients, the hash is returning as undefined
662
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
663
+ ev.emit('creds.update', authState.creds);
664
+ }
665
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
666
+ }
667
+ logger.debug('fetched props');
668
+ return props;
669
+ };
670
+ /**
671
+ * modify a chat -- mark unread, read etc.
672
+ * lastMessages must be sorted in reverse chronologically
673
+ * requires the last messages till the last message received; required for archive & unread
674
+ */
675
+ const chatModify = (mod, jid) => {
676
+ const patch = chatModificationToAppPatch(mod, jid);
677
+ return appPatch(patch);
678
+ };
679
+ /**
680
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
681
+ */
682
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
683
+ return chatModify({
684
+ disableLinkPreviews: { isPreviewsDisabled }
685
+ }, '');
686
+ };
687
+ /**
688
+ * Star or Unstar a message
689
+ */
690
+ const star = (jid, messages, star) => {
691
+ return chatModify({
692
+ star: {
693
+ messages,
694
+ star
695
+ }
696
+ }, jid);
697
+ };
698
+ /**
699
+ * Add or Edit Contact
700
+ */
701
+ const addOrEditContact = (jid, contact) => {
702
+ return chatModify({
703
+ contact
704
+ }, jid);
705
+ };
706
+ /**
707
+ * Remove Contact
708
+ */
709
+ const removeContact = (jid) => {
710
+ return chatModify({
711
+ contact: null
712
+ }, jid);
713
+ };
714
+ /**
715
+ * Adds label
716
+ */
717
+ const addLabel = (jid, labels) => {
718
+ return chatModify({
719
+ addLabel: {
720
+ ...labels
721
+ }
722
+ }, jid);
723
+ };
724
+ /**
725
+ * Adds label for the chats
726
+ */
727
+ const addChatLabel = (jid, labelId) => {
728
+ return chatModify({
729
+ addChatLabel: {
730
+ labelId
731
+ }
732
+ }, jid);
733
+ };
734
+ /**
735
+ * Removes label for the chat
736
+ */
737
+ const removeChatLabel = (jid, labelId) => {
738
+ return chatModify({
739
+ removeChatLabel: {
740
+ labelId
741
+ }
742
+ }, jid);
743
+ };
744
+ /**
745
+ * Adds label for the message
746
+ */
747
+ const addMessageLabel = (jid, messageId, labelId) => {
748
+ return chatModify({
749
+ addMessageLabel: {
750
+ messageId,
751
+ labelId
752
+ }
753
+ }, jid);
754
+ };
755
+ /**
756
+ * Removes label for the message
757
+ */
758
+ const removeMessageLabel = (jid, messageId, labelId) => {
759
+ return chatModify({
760
+ removeMessageLabel: {
761
+ messageId,
762
+ labelId
763
+ }
764
+ }, jid);
765
+ };
766
+ /**
767
+ * Add or Edit Quick Reply
768
+ */
769
+ const addOrEditQuickReply = (quickReply) => {
770
+ return chatModify({
771
+ quickReply
772
+ }, '');
773
+ };
774
+ /**
775
+ * Remove Quick Reply
776
+ */
777
+ const removeQuickReply = (timestamp) => {
778
+ return chatModify({
779
+ quickReply: { timestamp, deleted: true }
780
+ }, '');
781
+ };
782
+ /**
783
+ * queries need to be fired on connection open
784
+ * help ensure parity with WA Web
785
+ * */
786
+ const executeInitQueries = async () => {
787
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
788
+ };
789
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
790
+ ev.emit('messages.upsert', { messages: [msg], type });
791
+ if (!!msg.pushName) {
792
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
793
+ jid = jidNormalizedUser(jid);
794
+ if (!msg.key.fromMe) {
795
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
796
+ }
797
+ // update our pushname too
798
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
799
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
800
+ }
801
+ }
802
+ const historyMsg = getHistoryMsg(msg.message);
803
+ const shouldProcessHistoryMsg = historyMsg
804
+ ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
805
+ : false;
806
+ // State machine: decide on sync and flush
807
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
808
+ if (awaitingSyncTimeout) {
809
+ clearTimeout(awaitingSyncTimeout);
810
+ awaitingSyncTimeout = undefined;
811
+ }
812
+ if (shouldProcessHistoryMsg) {
813
+ syncState = SyncState.Syncing;
814
+ logger.info('Transitioned to Syncing state');
815
+ // Let doAppStateSync handle the final flush after it's done
816
+ }
817
+ else {
818
+ syncState = SyncState.Online;
819
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
820
+ ev.flush();
821
+ }
822
+ }
823
+ const doAppStateSync = async () => {
824
+ if (syncState === SyncState.Syncing) {
825
+ logger.info('Doing app state sync');
826
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
827
+ // Sync is complete, go online and flush everything
828
+ syncState = SyncState.Online;
829
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
830
+ ev.flush();
831
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
832
+ ev.emit('creds.update', { accountSyncCounter });
833
+ }
834
+ };
835
+ await Promise.all([
836
+ (async () => {
837
+ if (shouldProcessHistoryMsg) {
838
+ await doAppStateSync();
839
+ }
840
+ })(),
841
+ processMessage(msg, {
842
+ signalRepository,
843
+ shouldProcessHistoryMsg,
844
+ placeholderResendCache,
845
+ ev,
846
+ creds: authState.creds,
847
+ keyStore: authState.keys,
848
+ logger,
849
+ options: config.options
850
+ })
851
+ ]);
852
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
853
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
854
+ logger.info('App state sync key arrived, triggering app state sync');
855
+ await doAppStateSync();
856
+ }
857
+ });
858
+ ws.on('CB:presence', handlePresenceUpdate);
859
+ ws.on('CB:chatstate', handlePresenceUpdate);
860
+ ws.on('CB:ib,,dirty', async (node) => {
861
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
862
+ const type = attrs.type;
863
+ switch (type) {
864
+ case 'account_sync':
865
+ if (attrs.timestamp) {
866
+ let { lastAccountSyncTimestamp } = authState.creds;
867
+ if (lastAccountSyncTimestamp) {
868
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
869
+ }
870
+ lastAccountSyncTimestamp = +attrs.timestamp;
871
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
872
+ }
873
+ break;
874
+ case 'groups':
875
+ // handled in groups.ts
876
+ break;
877
+ default:
878
+ logger.info({ node }, 'received unknown sync');
879
+ break;
880
+ }
881
+ });
882
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
883
+ if (connection === 'open') {
884
+ if (fireInitQueries) {
885
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
886
+ }
887
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
888
+ }
889
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
890
+ return;
891
+ }
892
+ syncState = SyncState.AwaitingInitialSync;
893
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
894
+ ev.buffer();
895
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
896
+ syncType: proto.HistorySync.HistorySyncType.RECENT
897
+ }));
898
+ if (!willSyncHistory) {
899
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
900
+ syncState = SyncState.Online;
901
+ setTimeout(() => ev.flush(), 0);
902
+ return;
903
+ }
904
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
905
+ if (awaitingSyncTimeout) {
906
+ clearTimeout(awaitingSyncTimeout);
907
+ }
908
+ awaitingSyncTimeout = setTimeout(() => {
909
+ if (syncState === SyncState.AwaitingInitialSync) {
910
+ // TODO: investigate
911
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
912
+ syncState = SyncState.Online;
913
+ ev.flush();
914
+ }
915
+ }, 20000);
916
+ });
917
+ return {
918
+ ...sock,
919
+ createCallLink,
920
+ getBotListV2,
921
+ processingMutex,
922
+ fetchPrivacySettings,
923
+ upsertMessage,
924
+ appPatch,
925
+ sendPresenceUpdate,
926
+ presenceSubscribe,
927
+ profilePictureUrl,
928
+ fetchBlocklist,
929
+ fetchStatus,
930
+ fetchDisappearingDuration,
931
+ updateProfilePicture,
932
+ removeProfilePicture,
933
+ updateProfileStatus,
934
+ updateProfileName,
935
+ updateBlockStatus,
936
+ updateDisableLinkPreviewsPrivacy,
937
+ updateCallPrivacy,
938
+ updateMessagesPrivacy,
939
+ updateLastSeenPrivacy,
940
+ updateOnlinePrivacy,
941
+ updateProfilePicturePrivacy,
942
+ updateStatusPrivacy,
943
+ updateReadReceiptsPrivacy,
944
+ updateGroupsAddPrivacy,
945
+ updateDefaultDisappearingMode,
946
+ getBusinessProfile,
947
+ resyncAppState,
948
+ chatModify,
949
+ cleanDirtyBits,
950
+ addOrEditContact,
951
+ removeContact,
952
+ addLabel,
953
+ addChatLabel,
954
+ removeChatLabel,
955
+ addMessageLabel,
956
+ removeMessageLabel,
957
+ star,
958
+ addOrEditQuickReply,
959
+ removeQuickReply
960
+ };
961
+ };
962
+ //# sourceMappingURL=chats.js.map