@sixcore/baileys 1.0.0 → 1.0.1

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