@aseppxyzz12/baileys 1.1.8

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 (185) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +2579 -0
  3. package/WAProto/AICommon/AICommon.js +19396 -0
  4. package/WAProto/AICommon/AICommon.proto +820 -0
  5. package/WAProto/Adv/Adv.js +1137 -0
  6. package/WAProto/Adv/Adv.proto +42 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +8975 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +484 -0
  9. package/WAProto/Cert/Cert.js +893 -0
  10. package/WAProto/Cert/Cert.proto +30 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +2457 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +103 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
  17. package/WAProto/E2E/E2E.js +78728 -0
  18. package/WAProto/E2E/E2E.proto +1970 -0
  19. package/WAProto/Ephemeral/Ephemeral.js +143 -0
  20. package/WAProto/Ephemeral/Ephemeral.proto +7 -0
  21. package/WAProto/HistorySync/HistorySync.js +95931 -0
  22. package/WAProto/HistorySync/HistorySync.proto +229 -0
  23. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
  24. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
  25. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
  26. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
  27. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
  28. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
  29. package/WAProto/MmsRetry/MmsRetry.js +310 -0
  30. package/WAProto/MmsRetry/MmsRetry.proto +19 -0
  31. package/WAProto/Protocol/Protocol.js +399 -0
  32. package/WAProto/Protocol/Protocol.proto +22 -0
  33. package/WAProto/Reporting/Reporting.js +535 -0
  34. package/WAProto/Reporting/Reporting.proto +22 -0
  35. package/WAProto/ServerSync/ServerSync.js +1830 -0
  36. package/WAProto/ServerSync/ServerSync.proto +70 -0
  37. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
  38. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
  39. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
  40. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
  41. package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
  42. package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
  43. package/WAProto/SyncAction/SyncAction.js +17424 -0
  44. package/WAProto/SyncAction/SyncAction.proto +663 -0
  45. package/WAProto/UserPassword/UserPassword.js +544 -0
  46. package/WAProto/UserPassword/UserPassword.proto +28 -0
  47. package/WAProto/VnameCert/VnameCert.js +1466 -0
  48. package/WAProto/VnameCert/VnameCert.proto +65 -0
  49. package/WAProto/Wa6/Wa6.js +4601 -0
  50. package/WAProto/Wa6/Wa6.proto +241 -0
  51. package/WAProto/Web/Web.js +90819 -0
  52. package/WAProto/Web/Web.proto +605 -0
  53. package/WAProto/index.js +30 -0
  54. package/engine-requirements.js +9 -0
  55. package/lib/Defaults/baileys-version.json +3 -0
  56. package/lib/Defaults/connection.js +39 -0
  57. package/lib/Defaults/constants.js +50 -0
  58. package/lib/Defaults/history.js +13 -0
  59. package/lib/Defaults/index.js +36 -0
  60. package/lib/Defaults/media.js +43 -0
  61. package/lib/Defaults/phonenumber-mcc.json +223 -0
  62. package/lib/Defaults/prefix.js +12 -0
  63. package/lib/Function/Download/tiktok.js +19 -0
  64. package/lib/Function/Tools/bypass.js +19 -0
  65. package/lib/Function/index.js +13 -0
  66. package/lib/Signal/Group/ciphertext-message.js +14 -0
  67. package/lib/Signal/Group/group-session-builder.js +46 -0
  68. package/lib/Signal/Group/group_cipher.js +104 -0
  69. package/lib/Signal/Group/index.js +42 -0
  70. package/lib/Signal/Group/keyhelper.js +21 -0
  71. package/lib/Signal/Group/queue-job.js +57 -0
  72. package/lib/Signal/Group/sender-chain-key.js +34 -0
  73. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  74. package/lib/Signal/Group/sender-key-message.js +78 -0
  75. package/lib/Signal/Group/sender-key-name.js +49 -0
  76. package/lib/Signal/Group/sender-key-record.js +45 -0
  77. package/lib/Signal/Group/sender-key-state.js +100 -0
  78. package/lib/Signal/Group/sender-message-key.js +28 -0
  79. package/lib/Signal/libsignal.js +364 -0
  80. package/lib/Signal/lid-mapping.js +164 -0
  81. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  82. package/lib/Socket/Client/index.js +31 -0
  83. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  84. package/lib/Socket/Client/types.js +12 -0
  85. package/lib/Socket/Client/web-socket-client.js +62 -0
  86. package/lib/Socket/Client/websocket.js +67 -0
  87. package/lib/Socket/business.js +291 -0
  88. package/lib/Socket/chats.js +874 -0
  89. package/lib/Socket/community.js +454 -0
  90. package/lib/Socket/dugong.js +658 -0
  91. package/lib/Socket/groups.js +357 -0
  92. package/lib/Socket/index.js +13 -0
  93. package/lib/Socket/messages-recv.js +1509 -0
  94. package/lib/Socket/messages-send.js +1505 -0
  95. package/lib/Socket/mex.js +54 -0
  96. package/lib/Socket/newsletter.js +171 -0
  97. package/lib/Socket/registration.js +167 -0
  98. package/lib/Socket/rich-content.js +279 -0
  99. package/lib/Socket/socket.js +905 -0
  100. package/lib/Socket/username.js +157 -0
  101. package/lib/Socket/usync.js +70 -0
  102. package/lib/Store/index.js +37 -0
  103. package/lib/Store/keyed-db.js +114 -0
  104. package/lib/Store/make-cache-manager-store.js +77 -0
  105. package/lib/Store/make-in-memory-store.js +423 -0
  106. package/lib/Store/make-ordered-dictionary.js +78 -0
  107. package/lib/Store/object-repository.js +26 -0
  108. package/lib/Types/Auth.js +2 -0
  109. package/lib/Types/Bussines.js +2 -0
  110. package/lib/Types/Call.js +2 -0
  111. package/lib/Types/Chat.js +10 -0
  112. package/lib/Types/Contact.js +2 -0
  113. package/lib/Types/Events.js +2 -0
  114. package/lib/Types/GroupMetadata.js +2 -0
  115. package/lib/Types/Label.js +25 -0
  116. package/lib/Types/LabelAssociation.js +4 -0
  117. package/lib/Types/Message.js +11 -0
  118. package/lib/Types/Mex.js +40 -0
  119. package/lib/Types/MexUpdates.js +15 -0
  120. package/lib/Types/Newsletter.js +32 -0
  121. package/lib/Types/Product.js +2 -0
  122. package/lib/Types/Signal.js +2 -0
  123. package/lib/Types/Socket.js +2 -0
  124. package/lib/Types/State.js +9 -0
  125. package/lib/Types/USync.js +2 -0
  126. package/lib/Types/index.js +60 -0
  127. package/lib/Utils/auth-utils.js +256 -0
  128. package/lib/Utils/baileys-event-stream.js +63 -0
  129. package/lib/Utils/bot-toolkit.js +455 -0
  130. package/lib/Utils/browser-utils.js +29 -0
  131. package/lib/Utils/business.js +233 -0
  132. package/lib/Utils/chat-utils.js +904 -0
  133. package/lib/Utils/companion-reg-client-utils.js +41 -0
  134. package/lib/Utils/crypto.js +144 -0
  135. package/lib/Utils/decode-wa-message.js +305 -0
  136. package/lib/Utils/event-buffer.js +555 -0
  137. package/lib/Utils/generics.js +411 -0
  138. package/lib/Utils/history.js +100 -0
  139. package/lib/Utils/identity-change-handler.js +53 -0
  140. package/lib/Utils/index.js +57 -0
  141. package/lib/Utils/link-preview.js +76 -0
  142. package/lib/Utils/logger.js +4 -0
  143. package/lib/Utils/lt-hash.js +45 -0
  144. package/lib/Utils/make-mutex.js +33 -0
  145. package/lib/Utils/message-composer.js +289 -0
  146. package/lib/Utils/message-retry-manager.js +134 -0
  147. package/lib/Utils/messages-media.js +806 -0
  148. package/lib/Utils/messages.js +1908 -0
  149. package/lib/Utils/noise-handler.js +157 -0
  150. package/lib/Utils/offline-node-processor.js +42 -0
  151. package/lib/Utils/pre-key-manager.js +86 -0
  152. package/lib/Utils/process-message.js +814 -0
  153. package/lib/Utils/reporting-utils.js +264 -0
  154. package/lib/Utils/signal.js +183 -0
  155. package/lib/Utils/stanza-ack.js +36 -0
  156. package/lib/Utils/sync-action-utils.js +52 -0
  157. package/lib/Utils/tc-token-utils.js +167 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +104 -0
  159. package/lib/Utils/validate-connection.js +229 -0
  160. package/lib/Utils/vialeys-event-stream.js +41 -0
  161. package/lib/WABinary/constants.js +1308 -0
  162. package/lib/WABinary/decode.js +233 -0
  163. package/lib/WABinary/encode.js +212 -0
  164. package/lib/WABinary/generic-utils.js +124 -0
  165. package/lib/WABinary/index.js +36 -0
  166. package/lib/WABinary/jid-utils.js +101 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.js +12 -0
  169. package/lib/WAM/constants.js +20491 -0
  170. package/lib/WAM/encode.js +148 -0
  171. package/lib/WAM/index.js +34 -0
  172. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
  176. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  179. package/lib/WAUSync/Protocols/index.js +38 -0
  180. package/lib/WAUSync/USyncQuery.js +97 -0
  181. package/lib/WAUSync/USyncUser.js +33 -0
  182. package/lib/WAUSync/index.js +34 -0
  183. package/lib/index.js +113 -0
  184. package/lib/messages-send.js +1496 -0
  185. package/package.json +100 -0
@@ -0,0 +1,874 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { default: NodeCache } = require("@cacheable/node-cache");
4
+ const { Boom: Boom } = require("@hapi/boom");
5
+ const { proto: proto } = require("../../WAProto");
6
+ const {
7
+ CALL_VIDEO_PREFIX: CALL_VIDEO_PREFIX,
8
+ CALL_AUDIO_PREFIX: CALL_AUDIO_PREFIX,
9
+ } = require("../Defaults/prefix");
10
+ const { DEFAULT_CACHE_TTLS: DEFAULT_CACHE_TTLS } = require("../Defaults/constants");
11
+ const { PROCESSABLE_HISTORY_TYPES: PROCESSABLE_HISTORY_TYPES } = require("../Defaults/history");
12
+ const { SyncState: SyncState, ALL_WA_PATCH_NAMES: ALL_WA_PATCH_NAMES } = require("../Types");
13
+ const {
14
+ newLTHashState: newLTHashState,
15
+ processSyncAction: processSyncAction,
16
+ extractSyncdPatches: extractSyncdPatches,
17
+ generateProfilePicture: generateProfilePicture,
18
+ decodeSyncdSnapshot: decodeSyncdSnapshot,
19
+ decodePatches: decodePatches,
20
+ encodeSyncdPatch: encodeSyncdPatch,
21
+ chatModificationToAppPatch: chatModificationToAppPatch,
22
+ getHistoryMsg: getHistoryMsg,
23
+ processMessage: processMessage,
24
+ } = require("../Utils");
25
+ const { makeMutex: makeMutex } = require("../Utils/make-mutex");
26
+ const {
27
+ isPnUser: isPnUser,
28
+ getBinaryNodeChild: getBinaryNodeChild,
29
+ getBinaryNodeChildren: getBinaryNodeChildren,
30
+ jidDecode: jidDecode,
31
+ jidNormalizedUser: jidNormalizedUser,
32
+ reduceBinaryNodeToDictionary: reduceBinaryNodeToDictionary,
33
+ S_WHATSAPP_NET: S_WHATSAPP_NET,
34
+ } = require("../WABinary");
35
+ const { USyncUser: USyncUser, USyncQuery: USyncQuery } = require("../WAUSync");
36
+ const { makeSocket: makeSocket } = require("./socket");
37
+ const MAX_SYNC_ATTEMPTS = 2;
38
+ const makeChatsSocket = (config) => {
39
+ const {
40
+ logger: logger,
41
+ markOnlineOnConnect: markOnlineOnConnect,
42
+ fireInitQueries: fireInitQueries,
43
+ appStateMacVerification: appStateMacVerification,
44
+ shouldIgnoreJid: shouldIgnoreJid,
45
+ shouldSyncHistoryMessage: shouldSyncHistoryMessage,
46
+ getMessage: getMessage,
47
+ } = config;
48
+ const conn = makeSocket(config);
49
+ const {
50
+ ev: ev,
51
+ ws: ws,
52
+ authState: authState,
53
+ generateMessageTag: generateMessageTag,
54
+ sendNode: sendNode,
55
+ query: query,
56
+ signalRepository: signalRepository,
57
+ onUnexpectedError: onUnexpectedError,
58
+ } = conn;
59
+ let privacySettings;
60
+ let syncState = SyncState.Connecting;
61
+ const messageMutex = makeMutex();
62
+ const receiptMutex = makeMutex();
63
+ const appStatePatchMutex = makeMutex();
64
+ const notificationMutex = makeMutex();
65
+ let awaitingSyncTimeout;
66
+ const placeholderResendCache =
67
+ config.placeholderResendCache ||
68
+ new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, useClones: false });
69
+ if (!config.placeholderResendCache) {
70
+ config.placeholderResendCache = placeholderResendCache;
71
+ }
72
+ const getAppStateSyncKey = async (keyId) => {
73
+ const { [keyId]: key } = await authState.keys.get("app-state-sync-key", [keyId]);
74
+ return key;
75
+ };
76
+ const fetchPrivacySettings = async (force = false) => {
77
+ if (!privacySettings || force) {
78
+ const { content: content } = await query({
79
+ tag: "iq",
80
+ attrs: { xmlns: "privacy", to: S_WHATSAPP_NET, type: "get" },
81
+ content: [{ tag: "privacy", attrs: {} }],
82
+ });
83
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], "category");
84
+ }
85
+ return privacySettings;
86
+ };
87
+ const privacyQuery = async (name, value) => {
88
+ await query({
89
+ tag: "iq",
90
+ attrs: { xmlns: "privacy", to: S_WHATSAPP_NET, type: "set" },
91
+ content: [
92
+ {
93
+ tag: "privacy",
94
+ attrs: {},
95
+ content: [{ tag: "category", attrs: { name: name, value: value } }],
96
+ },
97
+ ],
98
+ });
99
+ };
100
+ const updateMessagesPrivacy = async (value) => {
101
+ await privacyQuery("messages", value);
102
+ };
103
+ const updateCallPrivacy = async (value) => {
104
+ await privacyQuery("calladd", value);
105
+ };
106
+ const updateLastSeenPrivacy = async (value) => {
107
+ await privacyQuery("last", value);
108
+ };
109
+ const updateOnlinePrivacy = async (value) => {
110
+ await privacyQuery("online", value);
111
+ };
112
+ const updateProfilePicturePrivacy = async (value) => {
113
+ await privacyQuery("profile", value);
114
+ };
115
+ const updateStatusPrivacy = async (value) => {
116
+ await privacyQuery("status", value);
117
+ };
118
+ const updateReadReceiptsPrivacy = async (value) => {
119
+ await privacyQuery("readreceipts", value);
120
+ };
121
+ const updateGroupsAddPrivacy = async (value) => {
122
+ await privacyQuery("groupadd", value);
123
+ };
124
+ const updateDefaultDisappearingMode = async (duration) => {
125
+ await query({
126
+ tag: "iq",
127
+ attrs: { xmlns: "disappearing_mode", to: S_WHATSAPP_NET, type: "set" },
128
+ content: [{ tag: "disappearing_mode", attrs: { duration: duration.toString() } }],
129
+ });
130
+ };
131
+ const getBotListV2 = async () => {
132
+ const resp = await query({
133
+ tag: "iq",
134
+ attrs: { xmlns: "bot", to: S_WHATSAPP_NET, type: "get" },
135
+ content: [{ tag: "bot", attrs: { v: "2" } }],
136
+ });
137
+ const botNode = getBinaryNodeChild(resp, "bot");
138
+ const botList = [];
139
+ for (const section of getBinaryNodeChildren(botNode, "section")) {
140
+ if (section.attrs.type === "all") {
141
+ for (const bot of getBinaryNodeChildren(section, "bot")) {
142
+ botList.push({
143
+ jid: bot.attrs.jid,
144
+ personaId: bot.attrs["persona_id"],
145
+ });
146
+ }
147
+ }
148
+ }
149
+ return botList;
150
+ };
151
+ const getLidUser = async (jid) => {
152
+ if (!jid) {
153
+ throw new Boom("Please input a jid user");
154
+ }
155
+ if (!isPnUser(jid)) {
156
+ throw new Boom("Invalid JID: Not a user JID!");
157
+ }
158
+ const targetJid = jidNormalizedUser(jid);
159
+ const usyncQuery = new USyncQuery();
160
+ usyncQuery.protocols.push({
161
+ name: "lid",
162
+ getQueryElement: () => ({ tag: "lid", attrs: {}, content: undefined }),
163
+ getUserElement: () => null,
164
+ parser: (node) => node.attrs.val,
165
+ });
166
+ usyncQuery.users.push({ id: targetJid });
167
+ const result = await conn.executeUSyncQuery(usyncQuery);
168
+ if (result) {
169
+ return result.list;
170
+ }
171
+ };
172
+ const fetchStatus = async (...jids) => {
173
+ const usyncQuery = new USyncQuery().withStatusProtocol();
174
+ for (const jid of jids) {
175
+ usyncQuery.withUser(new USyncUser().withId(jid));
176
+ }
177
+ const result = await conn.executeUSyncQuery(usyncQuery);
178
+ if (result) {
179
+ return result.list;
180
+ }
181
+ };
182
+ const fetchDisappearingDuration = async (...jids) => {
183
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
184
+ for (const jid of jids) {
185
+ usyncQuery.withUser(new USyncUser().withId(jid));
186
+ }
187
+ const result = await conn.executeUSyncQuery(usyncQuery);
188
+ if (result) {
189
+ return result.list;
190
+ }
191
+ };
192
+ const updateProfilePicture = async (jid, content, dimensions) => {
193
+ let targetJid;
194
+ if (!jid) {
195
+ throw new Boom(
196
+ "Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update"
197
+ );
198
+ }
199
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
200
+ targetJid = jidNormalizedUser(jid);
201
+ } else {
202
+ targetJid = undefined;
203
+ }
204
+ const { img: img } = await generateProfilePicture(content, dimensions);
205
+ await query({
206
+ tag: "iq",
207
+ attrs: {
208
+ to: S_WHATSAPP_NET,
209
+ type: "set",
210
+ xmlns: "w:profile:picture",
211
+ ...(targetJid ? { target: targetJid } : {}),
212
+ },
213
+ content: [{ tag: "picture", attrs: { type: "image" }, content: img }],
214
+ });
215
+ };
216
+ const removeProfilePicture = async (jid) => {
217
+ let targetJid;
218
+ if (!jid) {
219
+ throw new Boom(
220
+ "Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update"
221
+ );
222
+ }
223
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
224
+ targetJid = jidNormalizedUser(jid);
225
+ } else {
226
+ targetJid = undefined;
227
+ }
228
+ await query({
229
+ tag: "iq",
230
+ attrs: {
231
+ to: S_WHATSAPP_NET,
232
+ type: "set",
233
+ xmlns: "w:profile:picture",
234
+ ...(targetJid ? { target: targetJid } : {}),
235
+ },
236
+ });
237
+ };
238
+ const updateProfileStatus = async (status) => {
239
+ await query({
240
+ tag: "iq",
241
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "status" },
242
+ content: [{ tag: "status", attrs: {}, content: Buffer.from(status, "utf-8") }],
243
+ });
244
+ };
245
+ const updateProfileName = async (name) => {
246
+ await chatModify({ pushNameSetting: name }, "");
247
+ };
248
+ const fetchBlocklist = async () => {
249
+ const result = await query({
250
+ tag: "iq",
251
+ attrs: { xmlns: "blocklist", to: S_WHATSAPP_NET, type: "get" },
252
+ });
253
+ const listNode = getBinaryNodeChild(result, "list");
254
+ return getBinaryNodeChildren(listNode, "item").map((n) => n.attrs.jid);
255
+ };
256
+ const updateBlockStatus = async (jid, action) => {
257
+ await query({
258
+ tag: "iq",
259
+ attrs: { xmlns: "blocklist", to: S_WHATSAPP_NET, type: "set" },
260
+ content: [{ tag: "item", attrs: { action: action, jid: jid } }],
261
+ });
262
+ };
263
+ const getBusinessProfile = async (jid) => {
264
+ const results = await query({
265
+ tag: "iq",
266
+ attrs: { to: "s.whatsapp.net", xmlns: "w:biz", type: "get" },
267
+ content: [
268
+ {
269
+ tag: "business_profile",
270
+ attrs: { v: "244" },
271
+ content: [{ tag: "profile", attrs: { jid: jid } }],
272
+ },
273
+ ],
274
+ });
275
+ const profileNode = getBinaryNodeChild(results, "business_profile");
276
+ const profiles = getBinaryNodeChild(profileNode, "profile");
277
+ if (profiles) {
278
+ const address = getBinaryNodeChild(profiles, "address");
279
+ const description = getBinaryNodeChild(profiles, "description");
280
+ const website = getBinaryNodeChild(profiles, "website");
281
+ const email = getBinaryNodeChild(profiles, "email");
282
+ const category = getBinaryNodeChild(
283
+ getBinaryNodeChild(profiles, "categories"),
284
+ "category"
285
+ );
286
+ const businessHours = getBinaryNodeChild(profiles, "business_hours");
287
+ const businessHoursConfig = businessHours
288
+ ? getBinaryNodeChildren(businessHours, "business_hours_config")
289
+ : undefined;
290
+ const websiteStr = website?.content?.toString();
291
+ return {
292
+ wid: profiles?.attrs?.jid,
293
+ address: address?.content?.toString(),
294
+ description: description?.content?.toString() || "",
295
+ website: websiteStr ? [websiteStr] : [],
296
+ email: email?.content?.toString(),
297
+ category: category?.content?.toString(),
298
+ business_hours: {
299
+ timezone: businessHours?.attrs?.timezone,
300
+ business_config: businessHoursConfig?.map(({ attrs: attrs }) => attrs),
301
+ },
302
+ };
303
+ }
304
+ };
305
+ const cleanDirtyBits = async (type, fromTimestamp) => {
306
+ logger.info({ fromTimestamp: fromTimestamp }, "clean dirty bits " + type);
307
+ await sendNode({
308
+ tag: "iq",
309
+ attrs: {
310
+ to: S_WHATSAPP_NET,
311
+ type: "set",
312
+ xmlns: "urn:xmpp:whatsapp:dirty",
313
+ id: generateMessageTag(),
314
+ },
315
+ content: [
316
+ {
317
+ tag: "clean",
318
+ attrs: {
319
+ type: type,
320
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
321
+ },
322
+ },
323
+ ],
324
+ });
325
+ };
326
+ const newAppStateChunkHandler = (isInitialSync) => ({
327
+ onMutation(mutation) {
328
+ processSyncAction(
329
+ mutation,
330
+ ev,
331
+ authState.creds.me,
332
+ isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined,
333
+ logger
334
+ );
335
+ },
336
+ });
337
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
338
+ const initialVersionMap = {};
339
+ const globalMutationMap = {};
340
+ await authState.keys.transaction(async () => {
341
+ const collectionsToHandle = new Set(collections);
342
+ const attemptsMap = {};
343
+ while (collectionsToHandle.size) {
344
+ const states = {};
345
+ const nodes = [];
346
+ for (const name of collectionsToHandle) {
347
+ const result = await authState.keys.get("app-state-sync-version", [name]);
348
+ let state = result[name];
349
+ if (state) {
350
+ if (typeof initialVersionMap[name] === "undefined") {
351
+ initialVersionMap[name] = state.version;
352
+ }
353
+ } else {
354
+ state = newLTHashState();
355
+ }
356
+ states[name] = state;
357
+ logger.info(`resyncing ${name} from v${state.version}`);
358
+ nodes.push({
359
+ tag: "collection",
360
+ attrs: {
361
+ name: name,
362
+ version: state.version.toString(),
363
+ return_snapshot: (!state.version).toString(),
364
+ },
365
+ });
366
+ }
367
+ const result = await query({
368
+ tag: "iq",
369
+ attrs: {
370
+ to: S_WHATSAPP_NET,
371
+ xmlns: "w:sync:app:state",
372
+ type: "set",
373
+ },
374
+ content: [{ tag: "sync", attrs: {}, content: nodes }],
375
+ });
376
+ const decoded = await extractSyncdPatches(result, config?.options);
377
+ for (const key in decoded) {
378
+ const name = key;
379
+ const {
380
+ patches: patches,
381
+ hasMorePatches: hasMorePatches,
382
+ snapshot: snapshot,
383
+ } = decoded[name];
384
+ try {
385
+ if (snapshot) {
386
+ const { state: newState, mutationMap: mutationMap } =
387
+ await decodeSyncdSnapshot(
388
+ name,
389
+ snapshot,
390
+ getAppStateSyncKey,
391
+ initialVersionMap[name],
392
+ appStateMacVerification.snapshot
393
+ );
394
+ states[name] = newState;
395
+ Object.assign(globalMutationMap, mutationMap);
396
+ logger.info(
397
+ `restored state of ${name} from snapshot to v${newState.version} with mutations`
398
+ );
399
+ await authState.keys.set({
400
+ "app-state-sync-version": { [name]: newState },
401
+ });
402
+ }
403
+ if (patches.length) {
404
+ const { state: newState, mutationMap: mutationMap } =
405
+ await decodePatches(
406
+ name,
407
+ patches,
408
+ states[name],
409
+ getAppStateSyncKey,
410
+ config.options,
411
+ initialVersionMap[name],
412
+ logger,
413
+ appStateMacVerification.patch
414
+ );
415
+ await authState.keys.set({
416
+ "app-state-sync-version": { [name]: newState },
417
+ });
418
+ logger.info(`synced ${name} to v${newState.version}`);
419
+ initialVersionMap[name] = newState.version;
420
+ Object.assign(globalMutationMap, mutationMap);
421
+ }
422
+ if (hasMorePatches) {
423
+ logger.info(`${name} has more patches...`);
424
+ } else {
425
+ collectionsToHandle.delete(name);
426
+ }
427
+ } catch (error) {
428
+ const isIrrecoverableError =
429
+ attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
430
+ error.output?.statusCode === 404 ||
431
+ error.name === "TypeError";
432
+ logger.info(
433
+ { name: name, error: error.stack },
434
+ `failed to sync state from version${isIrrecoverableError ? "" : ", removing and trying from scratch"}`
435
+ );
436
+ await authState.keys.set({
437
+ "app-state-sync-version": { [name]: null },
438
+ });
439
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
440
+ if (isIrrecoverableError) {
441
+ collectionsToHandle.delete(name);
442
+ }
443
+ }
444
+ }
445
+ }
446
+ }, authState?.creds?.me?.id || "resync-app-state");
447
+ const { onMutation: onMutation } = newAppStateChunkHandler(isInitialSync);
448
+ for (const key in globalMutationMap) {
449
+ onMutation(globalMutationMap[key]);
450
+ }
451
+ });
452
+ const createCallLink = async (type, event, timeoutMs) => {
453
+ type = type?.toLowerCase();
454
+ if (!type || (type !== "audio" && type !== "video")) {
455
+ throw new Error("Make sure the type is audio or video!");
456
+ }
457
+ const result = await query(
458
+ {
459
+ tag: "call",
460
+ attrs: { id: generateMessageTag(), to: "@call" },
461
+ content: [
462
+ {
463
+ tag: "link_create",
464
+ attrs: { media: type },
465
+ content: event
466
+ ? [{ tag: "event", attrs: { start_time: String(event) } }]
467
+ : undefined,
468
+ },
469
+ ],
470
+ },
471
+ timeoutMs
472
+ );
473
+ const child = getBinaryNodeChild(result, "link_create");
474
+ const token = child?.attrs?.token;
475
+ return type === "audio" ? CALL_AUDIO_PREFIX + token : CALL_VIDEO_PREFIX + token;
476
+ };
477
+ const sendPresenceUpdate = async (type, toJid) => {
478
+ const me = authState.creds.me;
479
+ if (type === "available" || type === "unavailable") {
480
+ if (!me.name) {
481
+ logger.warn("no name present, ignoring presence update request...");
482
+ return;
483
+ }
484
+ ev.emit("connection.update", { isOnline: type === "available" });
485
+ await sendNode({
486
+ tag: "presence",
487
+ attrs: { name: me.name.replace(/@/g, ""), type: type },
488
+ });
489
+ } else {
490
+ const { server: server } = jidDecode(toJid);
491
+ await sendNode({
492
+ tag: "chatstate",
493
+ attrs: { from: server === "lid" ? me.lid : me.id, to: toJid },
494
+ content: [
495
+ {
496
+ tag: type === "recording" ? "composing" : type,
497
+ attrs: type === "recording" ? { media: "audio" } : {},
498
+ },
499
+ ],
500
+ });
501
+ }
502
+ };
503
+ const presenceSubscribe = (toJid, tcToken) =>
504
+ sendNode({
505
+ tag: "presence",
506
+ attrs: { to: toJid, id: generateMessageTag(), type: "subscribe" },
507
+ content: tcToken ? [{ tag: "tctoken", attrs: {}, content: tcToken }] : undefined,
508
+ });
509
+ const handlePresenceUpdate = ({ tag: tag, attrs: attrs, content: content }) => {
510
+ let presence;
511
+ const jid = attrs.from;
512
+ const participant = attrs.participant || attrs.from;
513
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
514
+ return;
515
+ }
516
+ if (tag === "presence") {
517
+ presence = {
518
+ lastKnownPresence: attrs.type === "unavailable" ? "unavailable" : "available",
519
+ lastSeen: attrs.last && attrs.last !== "deny" ? +attrs.last : undefined,
520
+ };
521
+ } else if (Array.isArray(content)) {
522
+ const [firstChild] = content;
523
+ let type = firstChild.tag;
524
+ if (type === "paused") {
525
+ type = "available";
526
+ }
527
+ if (firstChild.attrs?.media === "audio") {
528
+ type = "recording";
529
+ }
530
+ presence = { lastKnownPresence: type };
531
+ } else {
532
+ logger.error(
533
+ { tag: tag, attrs: attrs, content: content },
534
+ "recv invalid presence node"
535
+ );
536
+ }
537
+ if (presence) {
538
+ ev.emit("presence.update", {
539
+ id: jid,
540
+ presences: { [participant]: presence },
541
+ });
542
+ }
543
+ };
544
+ const appPatch = async (patchCreate) => {
545
+ const name = patchCreate.type;
546
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
547
+ if (!myAppStateKeyId) {
548
+ throw new Boom("App state key not present!", { statusCode: 400 });
549
+ }
550
+ let initial;
551
+ let encodeResult;
552
+ await appStatePatchMutex.mutex(async () => {
553
+ await authState.keys.transaction(async () => {
554
+ logger.debug({ patch: patchCreate }, "applying app patch");
555
+ await resyncAppState([name], false);
556
+ const { [name]: currentSyncVersion } = await authState.keys.get(
557
+ "app-state-sync-version",
558
+ [name]
559
+ );
560
+ initial = currentSyncVersion || newLTHashState();
561
+ encodeResult = await encodeSyncdPatch(
562
+ patchCreate,
563
+ myAppStateKeyId,
564
+ initial,
565
+ getAppStateSyncKey
566
+ );
567
+ const { patch: patch, state: state } = encodeResult;
568
+ const node = {
569
+ tag: "iq",
570
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "w:sync:app:state" },
571
+ content: [
572
+ {
573
+ tag: "sync",
574
+ attrs: {},
575
+ content: [
576
+ {
577
+ tag: "collection",
578
+ attrs: {
579
+ name: name,
580
+ version: (state.version - 1).toString(),
581
+ return_snapshot: "false",
582
+ },
583
+ content: [
584
+ {
585
+ tag: "patch",
586
+ attrs: {},
587
+ content: proto.SyncdPatch.encode(patch).finish(),
588
+ },
589
+ ],
590
+ },
591
+ ],
592
+ },
593
+ ],
594
+ };
595
+ await query(node);
596
+ await authState.keys.set({
597
+ "app-state-sync-version": { [name]: state },
598
+ });
599
+ }, authState?.creds?.me?.id || "app-patch");
600
+ });
601
+ if (config.emitOwnEvents) {
602
+ const { onMutation: onMutation } = newAppStateChunkHandler(false);
603
+ const { mutationMap: mutationMap } = await decodePatches(
604
+ name,
605
+ [
606
+ {
607
+ ...encodeResult.patch,
608
+ version: { version: encodeResult.state.version },
609
+ },
610
+ ],
611
+ initial,
612
+ getAppStateSyncKey,
613
+ config.options,
614
+ undefined,
615
+ logger
616
+ );
617
+ for (const key in mutationMap) {
618
+ onMutation(mutationMap[key]);
619
+ }
620
+ }
621
+ };
622
+ const fetchProps = async () => {
623
+ const resultNode = await query({
624
+ tag: "iq",
625
+ attrs: { to: S_WHATSAPP_NET, xmlns: "w", type: "get" },
626
+ content: [
627
+ {
628
+ tag: "props",
629
+ attrs: { protocol: "2", hash: authState?.creds?.lastPropHash || "" },
630
+ },
631
+ ],
632
+ });
633
+ const propsNode = getBinaryNodeChild(resultNode, "props");
634
+ let props = {};
635
+ if (propsNode) {
636
+ if (propsNode.attrs?.hash) {
637
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
638
+ ev.emit("creds.update", authState.creds);
639
+ }
640
+ props = reduceBinaryNodeToDictionary(propsNode, "prop");
641
+ }
642
+ logger.debug("fetched props");
643
+ return props;
644
+ };
645
+ const chatModify = (mod, jid) => {
646
+ const patch = chatModificationToAppPatch(mod, jid);
647
+ return appPatch(patch);
648
+ };
649
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) =>
650
+ chatModify({ disableLinkPreviews: { isPreviewsDisabled: isPreviewsDisabled } }, "");
651
+ const star = (jid, messages, star) =>
652
+ chatModify({ star: { messages: messages, star: star } }, jid);
653
+ const addOrEditContact = (jid, contact) => chatModify({ contact: contact }, jid);
654
+ const removeContact = (jid) => chatModify({ contact: null }, jid);
655
+ const addLabel = (jid, labels) => chatModify({ addLabel: { ...labels } }, jid);
656
+ const addChatLabel = (jid, labelId) => chatModify({ addChatLabel: { labelId: labelId } }, jid);
657
+ const removeChatLabel = (jid, labelId) =>
658
+ chatModify({ removeChatLabel: { labelId: labelId } }, jid);
659
+ const addMessageLabel = (jid, messageId, labelId) =>
660
+ chatModify({ addMessageLabel: { messageId: messageId, labelId: labelId } }, jid);
661
+ const removeMessageLabel = (jid, messageId, labelId) =>
662
+ chatModify({ removeMessageLabel: { messageId: messageId, labelId: labelId } }, jid);
663
+ const clearMessage = (jid, key, timeStamp) =>
664
+ chatModify(
665
+ {
666
+ delete: true,
667
+ lastMessages: [{ key: key, messageTimestamp: timeStamp }],
668
+ },
669
+ jid
670
+ );
671
+ const addOrEditQuickReply = (quickReply) => chatModify({ quickReply: quickReply }, "");
672
+ const removeQuickReply = (timestamp) =>
673
+ chatModify({ quickReply: { timestamp: timestamp, deleted: true } }, "");
674
+ const executeInitQueries = async () => {
675
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
676
+ };
677
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
678
+ ev.emit("messages.upsert", { messages: [msg], type: type });
679
+ if (!!msg.pushName) {
680
+ let jid = msg.key.fromMe
681
+ ? authState.creds.me.id
682
+ : msg.key.participant || msg.key.remoteJid;
683
+ jid = jidNormalizedUser(jid);
684
+ if (!msg.key.fromMe) {
685
+ ev.emit("contacts.update", [
686
+ { id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName },
687
+ ]);
688
+ }
689
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
690
+ ev.emit("creds.update", {
691
+ me: { ...authState.creds.me, name: msg.pushName },
692
+ });
693
+ }
694
+ }
695
+ const historyMsg = getHistoryMsg(msg.message);
696
+ const shouldProcessHistoryMsg = historyMsg
697
+ ? shouldSyncHistoryMessage(historyMsg) &&
698
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
699
+ : false;
700
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
701
+ if (awaitingSyncTimeout) {
702
+ clearTimeout(awaitingSyncTimeout);
703
+ awaitingSyncTimeout = undefined;
704
+ }
705
+ if (shouldProcessHistoryMsg) {
706
+ syncState = SyncState.Syncing;
707
+ logger.info("Transitioned to Syncing state");
708
+ } else {
709
+ syncState = SyncState.Online;
710
+ logger.info(
711
+ "History sync skipped, transitioning to Online state and flushing buffer"
712
+ );
713
+ ev.flush();
714
+ }
715
+ }
716
+ const doAppStateSync = async () => {
717
+ if (syncState === SyncState.Syncing) {
718
+ logger.info("Doing app state sync");
719
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
720
+ syncState = SyncState.Online;
721
+ logger.info(
722
+ "App state sync complete, transitioning to Online state and flushing buffer"
723
+ );
724
+ ev.flush();
725
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
726
+ ev.emit("creds.update", { accountSyncCounter: accountSyncCounter });
727
+ }
728
+ };
729
+ await Promise.all([
730
+ (async () => {
731
+ if (shouldProcessHistoryMsg) {
732
+ await doAppStateSync();
733
+ }
734
+ })(),
735
+ processMessage(msg, {
736
+ signalRepository: signalRepository,
737
+ shouldProcessHistoryMsg: shouldProcessHistoryMsg,
738
+ placeholderResendCache: placeholderResendCache,
739
+ ev: ev,
740
+ creds: authState.creds,
741
+ keyStore: authState.keys,
742
+ logger: logger,
743
+ options: config.options,
744
+ getMessage: getMessage,
745
+ }),
746
+ ]);
747
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
748
+ logger.info("App state sync key arrived, triggering app state sync");
749
+ await doAppStateSync();
750
+ }
751
+ });
752
+ ws.on("CB:presence", handlePresenceUpdate);
753
+ ws.on("CB:chatstate", handlePresenceUpdate);
754
+ ws.on("CB:ib,,dirty", async (node) => {
755
+ const { attrs: attrs } = getBinaryNodeChild(node, "dirty");
756
+ const type = attrs.type;
757
+ switch (type) {
758
+ case "account_sync":
759
+ if (attrs.timestamp) {
760
+ let { lastAccountSyncTimestamp: lastAccountSyncTimestamp } = authState.creds;
761
+ if (lastAccountSyncTimestamp) {
762
+ await cleanDirtyBits("account_sync", lastAccountSyncTimestamp);
763
+ }
764
+ lastAccountSyncTimestamp = +attrs.timestamp;
765
+ ev.emit("creds.update", {
766
+ lastAccountSyncTimestamp: lastAccountSyncTimestamp,
767
+ });
768
+ }
769
+ break;
770
+ case "groups":
771
+ break;
772
+ default:
773
+ logger.info({ node: node }, "received unknown sync");
774
+ break;
775
+ }
776
+ });
777
+ ev.on(
778
+ "connection.update",
779
+ ({
780
+ connection: connection,
781
+ receivedPendingNotifications: receivedPendingNotifications,
782
+ }) => {
783
+ if (connection === "open") {
784
+ if (fireInitQueries) {
785
+ executeInitQueries().catch((error) => onUnexpectedError(error, "init queries"));
786
+ }
787
+ sendPresenceUpdate(markOnlineOnConnect ? "available" : "unavailable").catch(
788
+ (error) => onUnexpectedError(error, "presence update requests")
789
+ );
790
+ }
791
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
792
+ return;
793
+ }
794
+ syncState = SyncState.AwaitingInitialSync;
795
+ logger.info("Connection is now AwaitingInitialSync, buffering events");
796
+ ev.buffer();
797
+ const willSyncHistory = shouldSyncHistoryMessage(
798
+ proto.Message.HistorySyncNotification.create({
799
+ syncType: proto.HistorySync.HistorySyncType.RECENT,
800
+ })
801
+ );
802
+ if (!willSyncHistory) {
803
+ logger.info(
804
+ "History sync is disabled by config, not waiting for notification. Transitioning to Online."
805
+ );
806
+ syncState = SyncState.Online;
807
+ setTimeout(() => ev.flush(), 0);
808
+ return;
809
+ }
810
+ logger.info("History sync is enabled, awaiting notification with a 20s timeout.");
811
+ if (awaitingSyncTimeout) {
812
+ clearTimeout(awaitingSyncTimeout);
813
+ }
814
+ awaitingSyncTimeout = setTimeout(() => {
815
+ if (syncState === SyncState.AwaitingInitialSync) {
816
+ logger.warn(
817
+ "Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"
818
+ );
819
+ syncState = SyncState.Online;
820
+ ev.flush();
821
+ }
822
+ }, 2e4);
823
+ }
824
+ );
825
+ return {
826
+ ...conn,
827
+ star: star,
828
+ addOrEditContact: addOrEditContact,
829
+ removeContact: removeContact,
830
+ fetchPrivacySettings: fetchPrivacySettings,
831
+ upsertMessage: upsertMessage,
832
+ appPatch: appPatch,
833
+ createCallLink: createCallLink,
834
+ sendPresenceUpdate: sendPresenceUpdate,
835
+ presenceSubscribe: presenceSubscribe,
836
+ getBotListV2: getBotListV2,
837
+ messageMutex: messageMutex,
838
+ receiptMutex: receiptMutex,
839
+ appStatePatchMutex: appStatePatchMutex,
840
+ notificationMutex: notificationMutex,
841
+ getLidUser: getLidUser,
842
+ fetchBlocklist: fetchBlocklist,
843
+ fetchStatus: fetchStatus,
844
+ fetchDisappearingDuration: fetchDisappearingDuration,
845
+ updateProfilePicture: updateProfilePicture,
846
+ removeProfilePicture: removeProfilePicture,
847
+ updateProfileStatus: updateProfileStatus,
848
+ updateProfileName: updateProfileName,
849
+ updateBlockStatus: updateBlockStatus,
850
+ updateCallPrivacy: updateCallPrivacy,
851
+ updateMessagesPrivacy: updateMessagesPrivacy,
852
+ updateLastSeenPrivacy: updateLastSeenPrivacy,
853
+ updateOnlinePrivacy: updateOnlinePrivacy,
854
+ updateProfilePicturePrivacy: updateProfilePicturePrivacy,
855
+ updateStatusPrivacy: updateStatusPrivacy,
856
+ updateReadReceiptsPrivacy: updateReadReceiptsPrivacy,
857
+ updateGroupsAddPrivacy: updateGroupsAddPrivacy,
858
+ updateDefaultDisappearingMode: updateDefaultDisappearingMode,
859
+ updateDisableLinkPreviewsPrivacy: updateDisableLinkPreviewsPrivacy,
860
+ getBusinessProfile: getBusinessProfile,
861
+ resyncAppState: resyncAppState,
862
+ chatModify: chatModify,
863
+ cleanDirtyBits: cleanDirtyBits,
864
+ addLabel: addLabel,
865
+ addChatLabel: addChatLabel,
866
+ removeChatLabel: removeChatLabel,
867
+ addMessageLabel: addMessageLabel,
868
+ removeMessageLabel: removeMessageLabel,
869
+ clearMessage: clearMessage,
870
+ addOrEditQuickReply: addOrEditQuickReply,
871
+ removeQuickReply: removeQuickReply,
872
+ };
873
+ };
874
+ module.exports = { makeChatsSocket: makeChatsSocket };