@xbibzlibrary/whatsbibz 1.3.0

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