socketon 1.31.2-rc → 1.51.16

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