@mrlegendbot/baileys 1.2.4 → 1.2.6

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