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