@vinzsocket/baileys 3.0.0 → 3.0.15

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