@sgintokic/baileys 0.0.2

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.

Potentially problematic release.


This version of @sgintokic/baileys might be problematic. Click here for more details.

Files changed (106) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1097 -0
  3. package/WAProto/index.js +2 -0
  4. package/engine-requirements.js +1 -0
  5. package/lib/Defaults/index.js +155 -0
  6. package/lib/Signal/Group/ciphertext-message.js +11 -0
  7. package/lib/Signal/Group/group-session-builder.js +41 -0
  8. package/lib/Signal/Group/group_cipher.js +108 -0
  9. package/lib/Signal/Group/index.js +11 -0
  10. package/lib/Signal/Group/keyhelper.js +14 -0
  11. package/lib/Signal/Group/sender-chain-key.js +31 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  13. package/lib/Signal/Group/sender-key-message.js +79 -0
  14. package/lib/Signal/Group/sender-key-name.js +49 -0
  15. package/lib/Signal/Group/sender-key-record.js +46 -0
  16. package/lib/Signal/Group/sender-key-state.js +104 -0
  17. package/lib/Signal/Group/sender-message-key.js +29 -0
  18. package/lib/Signal/libsignal.js +485 -0
  19. package/lib/Signal/lid-mapping.js +291 -0
  20. package/lib/Socket/Client/index.js +2 -0
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +64 -0
  23. package/lib/Socket/business.js +293 -0
  24. package/lib/Socket/chats.js +1068 -0
  25. package/lib/Socket/communities.js +476 -0
  26. package/lib/Socket/groups.js +383 -0
  27. package/lib/Socket/index.js +8 -0
  28. package/lib/Socket/messages-recv.js +1830 -0
  29. package/lib/Socket/messages-send.js +1462 -0
  30. package/lib/Socket/mex.js +55 -0
  31. package/lib/Socket/newsletter.js +277 -0
  32. package/lib/Socket/socket.js +1087 -0
  33. package/lib/Store/index.js +3 -0
  34. package/lib/Store/make-in-memory-store.js +517 -0
  35. package/lib/Store/make-ordered-dictionary.js +75 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Types/Auth.js +1 -0
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -0
  40. package/lib/Types/Chat.js +7 -0
  41. package/lib/Types/Contact.js +1 -0
  42. package/lib/Types/Events.js +1 -0
  43. package/lib/Types/GroupMetadata.js +1 -0
  44. package/lib/Types/Label.js +24 -0
  45. package/lib/Types/LabelAssociation.js +6 -0
  46. package/lib/Types/Message.js +18 -0
  47. package/lib/Types/Newsletter.js +33 -0
  48. package/lib/Types/Product.js +1 -0
  49. package/lib/Types/Signal.js +1 -0
  50. package/lib/Types/Socket.js +2 -0
  51. package/lib/Types/State.js +15 -0
  52. package/lib/Types/USync.js +1 -0
  53. package/lib/Types/index.js +31 -0
  54. package/lib/Utils/auth-utils.js +293 -0
  55. package/lib/Utils/browser-utils.js +32 -0
  56. package/lib/Utils/business.js +245 -0
  57. package/lib/Utils/chat-utils.js +959 -0
  58. package/lib/Utils/crypto.js +133 -0
  59. package/lib/Utils/decode-wa-message.js +376 -0
  60. package/lib/Utils/event-buffer.js +620 -0
  61. package/lib/Utils/generics.js +417 -0
  62. package/lib/Utils/history.js +150 -0
  63. package/lib/Utils/identity-change-handler.js +63 -0
  64. package/lib/Utils/index.js +21 -0
  65. package/lib/Utils/link-preview.js +91 -0
  66. package/lib/Utils/logger.js +2 -0
  67. package/lib/Utils/lt-hash.js +6 -0
  68. package/lib/Utils/make-mutex.js +31 -0
  69. package/lib/Utils/message-retry-manager.js +240 -0
  70. package/lib/Utils/messages-media.js +901 -0
  71. package/lib/Utils/messages.js +2052 -0
  72. package/lib/Utils/noise-handler.js +229 -0
  73. package/lib/Utils/offline-node-processor.js +50 -0
  74. package/lib/Utils/pre-key-manager.js +119 -0
  75. package/lib/Utils/process-message.js +641 -0
  76. package/lib/Utils/reporting-utils.js +346 -0
  77. package/lib/Utils/signal.js +188 -0
  78. package/lib/Utils/stanza-ack.js +33 -0
  79. package/lib/Utils/sync-action-utils.js +53 -0
  80. package/lib/Utils/tc-token-utils.js +15 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +116 -0
  82. package/lib/Utils/use-single-file-auth-state.js +94 -0
  83. package/lib/Utils/validate-connection.js +235 -0
  84. package/lib/WABinary/constants.js +1300 -0
  85. package/lib/WABinary/decode.js +258 -0
  86. package/lib/WABinary/encode.js +219 -0
  87. package/lib/WABinary/generic-utils.js +203 -0
  88. package/lib/WABinary/index.js +5 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +1 -0
  91. package/lib/WAM/BinaryInfo.js +9 -0
  92. package/lib/WAM/constants.js +20669 -0
  93. package/lib/WAM/encode.js +151 -0
  94. package/lib/WAM/index.js +3 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +21 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  101. package/lib/WAUSync/Protocols/index.js +4 -0
  102. package/lib/WAUSync/USyncQuery.js +103 -0
  103. package/lib/WAUSync/USyncUser.js +22 -0
  104. package/lib/WAUSync/index.js +3 -0
  105. package/lib/index.js +11 -0
  106. package/package.json +58 -0
@@ -0,0 +1,291 @@
1
+ import { LRUCache } from "lru-cache";
2
+ import {
3
+ isHostedPnUser,
4
+ isLidUser,
5
+ isPnUser,
6
+ jidDecode,
7
+ jidNormalizedUser,
8
+ WAJIDDomains,
9
+ } from "../WABinary/index.js";
10
+ export class LIDMappingStore {
11
+ constructor(keys, logger, pnToLIDFunc) {
12
+ this.mappingCache = new LRUCache({
13
+ ttl: 3 * 24 * 60 * 60 * 1e3, // 7 days
14
+ ttlAutopurge: true,
15
+ updateAgeOnGet: true,
16
+ });
17
+ this.inflightLIDLookups = new Map();
18
+ this.inflightPNLookups = new Map();
19
+ this.keys = keys;
20
+ this.pnToLIDFunc = pnToLIDFunc;
21
+ this.logger = logger;
22
+ }
23
+ async storeLIDPNMappings(pairs) {
24
+ if (pairs.length === 0) return;
25
+ const validatedPairs = [];
26
+ for (const { lid, pn } of pairs) {
27
+ if (
28
+ !((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))
29
+ ) {
30
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
31
+ continue;
32
+ }
33
+ const lidDecoded = jidDecode(lid);
34
+ const pnDecoded = jidDecode(pn);
35
+ if (!lidDecoded || !pnDecoded) continue;
36
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
37
+ }
38
+ if (validatedPairs.length === 0) return;
39
+ const cacheMissSet = new Set();
40
+ const existingMappings = new Map();
41
+ for (const { pnUser } of validatedPairs) {
42
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
43
+ if (cached) {
44
+ existingMappings.set(pnUser, cached);
45
+ } else {
46
+ cacheMissSet.add(pnUser);
47
+ }
48
+ }
49
+ if (cacheMissSet.size > 0) {
50
+ const cacheMisses = [...cacheMissSet];
51
+ this.logger.trace(
52
+ `Batch fetching ${cacheMisses.length} LID mappings from database`,
53
+ );
54
+ const stored = await this.keys.get("lid-mapping", cacheMisses);
55
+ for (const pnUser of cacheMisses) {
56
+ const existingLidUser = stored[pnUser];
57
+ if (existingLidUser) {
58
+ existingMappings.set(pnUser, existingLidUser);
59
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
60
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
61
+ }
62
+ }
63
+ }
64
+ const pairMap = {};
65
+ for (const { pnUser, lidUser } of validatedPairs) {
66
+ const existingLidUser = existingMappings.get(pnUser);
67
+ if (existingLidUser === lidUser) {
68
+ this.logger.debug(
69
+ { pnUser: pnUser, lidUser: lidUser },
70
+ "LID mapping already exists, skipping",
71
+ );
72
+ continue;
73
+ }
74
+ pairMap[pnUser] = lidUser;
75
+ }
76
+ if (Object.keys(pairMap).length === 0) return;
77
+ this.logger.trace(
78
+ { pairMap: pairMap },
79
+ `Storing ${Object.keys(pairMap).length} pn mappings`,
80
+ );
81
+ const batchData = {};
82
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
83
+ batchData[pnUser] = lidUser;
84
+ batchData[`${lidUser}_reverse`] = pnUser;
85
+ }
86
+ await this.keys.transaction(async () => {
87
+ await this.keys.set({ "lid-mapping": batchData });
88
+ }, "lid-mapping");
89
+ // Update cache after successful DB write
90
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
91
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
92
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
93
+ }
94
+ }
95
+ async getLIDForPN(pn) {
96
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
97
+ }
98
+ async getLIDsForPNs(pns) {
99
+ if (pns.length === 0) return null;
100
+ const sortedPns = [...new Set(pns)].sort();
101
+ const cacheKey = sortedPns.join(",");
102
+ const inflight = this.inflightLIDLookups.get(cacheKey);
103
+ if (inflight) {
104
+ this.logger.trace(
105
+ `Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`,
106
+ );
107
+ return inflight;
108
+ }
109
+ const promise = this._getLIDsForPNsImpl(pns);
110
+ this.inflightLIDLookups.set(cacheKey, promise);
111
+ try {
112
+ return await promise;
113
+ } finally {
114
+ this.inflightLIDLookups.delete(cacheKey);
115
+ }
116
+ }
117
+ async _getLIDsForPNsImpl(pns) {
118
+ const usyncFetch = {};
119
+ const successfulPairs = {};
120
+ const pending = [];
121
+ const addResolvedPair = (pn, decoded, lidUser) => {
122
+ const normalizedLidUser = lidUser.toString();
123
+ if (!normalizedLidUser) {
124
+ this.logger.warn(
125
+ `Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`,
126
+ );
127
+ return false;
128
+ }
129
+ // Push the PN device ID to the LID to maintain device separation
130
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
131
+ const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === "hosted" ? "hosted.lid" : "lid"}`;
132
+ this.logger.trace(
133
+ `getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`,
134
+ );
135
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn: pn };
136
+ return true;
137
+ };
138
+ for (const pn of pns) {
139
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) continue;
140
+ const decoded = jidDecode(pn);
141
+ if (!decoded) continue;
142
+ const pnUser = decoded.user;
143
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
144
+ if (cached && typeof cached === "string") {
145
+ if (!addResolvedPair(pn, decoded, cached)) {
146
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
147
+ continue;
148
+ }
149
+ continue;
150
+ }
151
+ pending.push({ pn: pn, pnUser: pnUser, decoded: decoded });
152
+ }
153
+ if (pending.length) {
154
+ const pnUsers = [...new Set(pending.map((item) => item.pnUser))];
155
+ const stored = await this.keys.get("lid-mapping", pnUsers);
156
+ for (const pnUser of pnUsers) {
157
+ const lidUser = stored[pnUser];
158
+ if (lidUser && typeof lidUser === "string") {
159
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
160
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
161
+ }
162
+ }
163
+ for (const { pn, pnUser, decoded } of pending) {
164
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
165
+ if (cached && typeof cached === "string") {
166
+ if (!addResolvedPair(pn, decoded, cached)) {
167
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
168
+ continue;
169
+ }
170
+ } else {
171
+ this.logger.trace(
172
+ `No LID mapping found for PN user ${pnUser}; batch getting from USync`,
173
+ );
174
+ const device = decoded.device || 0;
175
+ let normalizedPn = jidNormalizedUser(pn);
176
+ if (isHostedPnUser(normalizedPn)) {
177
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
178
+ }
179
+ if (!usyncFetch[normalizedPn]) {
180
+ usyncFetch[normalizedPn] = [device];
181
+ } else {
182
+ usyncFetch[normalizedPn]?.push(device);
183
+ }
184
+ }
185
+ }
186
+ }
187
+ if (Object.keys(usyncFetch).length > 0) {
188
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch)); // this function already adds LIDs to mapping
189
+ if (result && result.length > 0) {
190
+ await this.storeLIDPNMappings(result);
191
+ for (const pair of result) {
192
+ const pnDecoded = jidDecode(pair.pn);
193
+ const pnUser = pnDecoded?.user;
194
+ if (!pnUser) continue;
195
+ const lidUser = jidDecode(pair.lid)?.user;
196
+ if (!lidUser) continue;
197
+ for (const device of usyncFetch[pair.pn]) {
198
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted.lid" : "lid"}`;
199
+ this.logger.trace(
200
+ `getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`,
201
+ );
202
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted" : "s.whatsapp.net"}`;
203
+ successfulPairs[deviceSpecificPn] = {
204
+ lid: deviceSpecificLid,
205
+ pn: deviceSpecificPn,
206
+ };
207
+ }
208
+ }
209
+ } else {
210
+ this.logger.warn("USync fetch yielded no results for pending PNs");
211
+ }
212
+ }
213
+ return Object.values(successfulPairs).length > 0
214
+ ? Object.values(successfulPairs)
215
+ : null;
216
+ }
217
+ async getPNForLID(lid) {
218
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
219
+ }
220
+ async getPNsForLIDs(lids) {
221
+ if (lids.length === 0) return null;
222
+ const sortedLids = [...new Set(lids)].sort();
223
+ const cacheKey = sortedLids.join(",");
224
+ const inflight = this.inflightPNLookups.get(cacheKey);
225
+ if (inflight) {
226
+ this.logger.trace(
227
+ `Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`,
228
+ );
229
+ return inflight;
230
+ }
231
+ const promise = this._getPNsForLIDsImpl(lids);
232
+ this.inflightPNLookups.set(cacheKey, promise);
233
+ try {
234
+ return await promise;
235
+ } finally {
236
+ this.inflightPNLookups.delete(cacheKey);
237
+ }
238
+ }
239
+ async _getPNsForLIDsImpl(lids) {
240
+ const successfulPairs = {};
241
+ const pending = [];
242
+ const addResolvedPair = (lid, decoded, pnUser) => {
243
+ if (!pnUser || typeof pnUser !== "string") {
244
+ return false;
245
+ }
246
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
247
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? "hosted" : "s.whatsapp.net"}`;
248
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
249
+ successfulPairs[lid] = { lid: lid, pn: pnJid };
250
+ return true;
251
+ };
252
+ for (const lid of lids) {
253
+ if (!isLidUser(lid)) continue;
254
+ const decoded = jidDecode(lid);
255
+ if (!decoded) continue;
256
+ const lidUser = decoded.user;
257
+ const cached = this.mappingCache.get(`lid:${lidUser}`);
258
+ if (cached && typeof cached === "string") {
259
+ addResolvedPair(lid, decoded, cached);
260
+ continue;
261
+ }
262
+ pending.push({ lid: lid, lidUser: lidUser, decoded: decoded });
263
+ }
264
+ if (pending.length) {
265
+ const reverseKeys = [
266
+ ...new Set(pending.map((item) => `${item.lidUser}_reverse`)),
267
+ ];
268
+ const stored = await this.keys.get("lid-mapping", reverseKeys);
269
+ for (const { lid, lidUser, decoded } of pending) {
270
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
271
+ if (!pnUser || typeof pnUser !== "string") {
272
+ pnUser = stored[`${lidUser}_reverse`];
273
+ if (pnUser && typeof pnUser === "string") {
274
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
275
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
276
+ }
277
+ }
278
+ if (pnUser && typeof pnUser === "string") {
279
+ addResolvedPair(lid, decoded, pnUser);
280
+ } else {
281
+ this.logger.trace(
282
+ `No reverse mapping found for LID user: ${lidUser}`,
283
+ );
284
+ }
285
+ }
286
+ }
287
+ return Object.values(successfulPairs).length
288
+ ? Object.values(successfulPairs)
289
+ : null;
290
+ }
291
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./types.js";
2
+ export * from "./websocket.js";
@@ -0,0 +1,10 @@
1
+ import { EventEmitter } from "events";
2
+ import { URL } from "url";
3
+ export class AbstractSocketClient extends EventEmitter {
4
+ constructor(url, config) {
5
+ super();
6
+ this.url = url;
7
+ this.config = config;
8
+ this.setMaxListeners(0);
9
+ }
10
+ }
@@ -0,0 +1,64 @@
1
+ import WebSocket from "ws";
2
+ import { DEFAULT_ORIGIN } from "../../Defaults/index.js";
3
+ import { AbstractSocketClient } from "./types.js";
4
+ export class WebSocketClient extends AbstractSocketClient {
5
+ constructor() {
6
+ super(...arguments);
7
+ this.socket = null;
8
+ }
9
+ get isOpen() {
10
+ return this.socket?.readyState === WebSocket.OPEN;
11
+ }
12
+ get isClosed() {
13
+ return this.socket === null || this.socket?.readyState === WebSocket.CLOSED;
14
+ }
15
+ get isClosing() {
16
+ return (
17
+ this.socket === null || this.socket?.readyState === WebSocket.CLOSING
18
+ );
19
+ }
20
+ get isConnecting() {
21
+ return this.socket?.readyState === WebSocket.CONNECTING;
22
+ }
23
+ connect() {
24
+ if (this.socket) {
25
+ return;
26
+ }
27
+ this.socket = new WebSocket(this.url, {
28
+ origin: DEFAULT_ORIGIN,
29
+ headers: this.config.options?.headers,
30
+ handshakeTimeout: this.config.connectTimeoutMs,
31
+ timeout: this.config.connectTimeoutMs,
32
+ agent: this.config.agent,
33
+ });
34
+ this.socket.setMaxListeners(0);
35
+ const events = [
36
+ "close",
37
+ "error",
38
+ "upgrade",
39
+ "message",
40
+ "open",
41
+ "ping",
42
+ "pong",
43
+ "unexpected-response",
44
+ ];
45
+ for (const event of events) {
46
+ this.socket?.on(event, (...args) => this.emit(event, ...args));
47
+ }
48
+ }
49
+ async close() {
50
+ if (!this.socket) {
51
+ return;
52
+ }
53
+ const closePromise = new Promise((resolve) => {
54
+ this.socket?.once("close", resolve);
55
+ });
56
+ this.socket.close();
57
+ await closePromise;
58
+ this.socket = null;
59
+ }
60
+ send(str, cb) {
61
+ this.socket?.send(str, cb);
62
+ return Boolean(this.socket);
63
+ }
64
+ }
@@ -0,0 +1,293 @@
1
+ import { getRawMediaUploadData } from "../Utils/index.js";
2
+ import {
3
+ parseCatalogNode,
4
+ parseCollectionsNode,
5
+ parseOrderDetailsNode,
6
+ parseProductNode,
7
+ toProductNode,
8
+ uploadingNecessaryImagesOfProduct,
9
+ } from "../Utils/business.js";
10
+ import { jidNormalizedUser, S_WHATSAPP_NET } from "../WABinary/index.js";
11
+ import { getBinaryNodeChild } from "../WABinary/generic-utils.js";
12
+ import { makeMessagesRecvSocket } from "./messages-recv.js";
13
+ export const makeBusinessSocket = (config) => {
14
+ const sock = makeMessagesRecvSocket(config);
15
+ const { authState, query, waUploadToServer } = sock;
16
+ const updateBussinesProfile = async (args) => {
17
+ const node = [];
18
+ const simpleFields = ["address", "email", "description"];
19
+ node.push(
20
+ ...simpleFields
21
+ .filter((key) => args[key] !== undefined && args[key] !== null)
22
+ .map((key) => ({ tag: key, attrs: {}, content: args[key] })),
23
+ );
24
+ if (args.websites !== undefined) {
25
+ node.push(
26
+ ...args.websites.map((website) => ({
27
+ tag: "website",
28
+ attrs: {},
29
+ content: website,
30
+ })),
31
+ );
32
+ }
33
+ if (args.hours !== undefined) {
34
+ node.push({
35
+ tag: "business_hours",
36
+ attrs: { timezone: args.hours.timezone },
37
+ content: args.hours.days.map((dayConfig) => {
38
+ const base = {
39
+ tag: "business_hours_config",
40
+ attrs: { day_of_week: dayConfig.day, mode: dayConfig.mode },
41
+ };
42
+ if (dayConfig.mode === "specific_hours") {
43
+ return {
44
+ ...base,
45
+ attrs: {
46
+ ...base.attrs,
47
+ open_time: dayConfig.openTimeInMinutes,
48
+ close_time: dayConfig.closeTimeInMinutes,
49
+ },
50
+ };
51
+ }
52
+ return base;
53
+ }),
54
+ });
55
+ }
56
+ const result = await query({
57
+ tag: "iq",
58
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "w:biz" },
59
+ content: [
60
+ {
61
+ tag: "business_profile",
62
+ attrs: { v: "3", mutation_type: "delta" },
63
+ content: node,
64
+ },
65
+ ],
66
+ });
67
+ return result;
68
+ };
69
+ const updateCoverPhoto = async (photo) => {
70
+ const { fileSha256, filePath } = await getRawMediaUploadData(
71
+ photo,
72
+ "biz-cover-photo",
73
+ );
74
+ const fileSha256B64 = fileSha256.toString("base64");
75
+ const { meta_hmac, fbid, ts } = await waUploadToServer(filePath, {
76
+ fileEncSha256B64: fileSha256B64,
77
+ mediaType: "biz-cover-photo",
78
+ });
79
+ await query({
80
+ tag: "iq",
81
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "w:biz" },
82
+ content: [
83
+ {
84
+ tag: "business_profile",
85
+ attrs: { v: "3", mutation_type: "delta" },
86
+ content: [
87
+ {
88
+ tag: "cover_photo",
89
+ attrs: {
90
+ id: String(fbid),
91
+ op: "update",
92
+ token: meta_hmac,
93
+ ts: String(ts),
94
+ },
95
+ },
96
+ ],
97
+ },
98
+ ],
99
+ });
100
+ return fbid;
101
+ };
102
+ const removeCoverPhoto = async (id) => {
103
+ return await query({
104
+ tag: "iq",
105
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "w:biz" },
106
+ content: [
107
+ {
108
+ tag: "business_profile",
109
+ attrs: { v: "3", mutation_type: "delta" },
110
+ content: [{ tag: "cover_photo", attrs: { op: "delete", id: id } }],
111
+ },
112
+ ],
113
+ });
114
+ };
115
+ const getCatalog = async ({ jid, limit, cursor }) => {
116
+ jid = jid || authState.creds.me?.id;
117
+ jid = jidNormalizedUser(jid);
118
+ const queryParamNodes = [
119
+ {
120
+ tag: "limit",
121
+ attrs: {},
122
+ content: Buffer.from((limit || 10).toString()),
123
+ },
124
+ { tag: "width", attrs: {}, content: Buffer.from("100") },
125
+ { tag: "height", attrs: {}, content: Buffer.from("100") },
126
+ ];
127
+ if (cursor) {
128
+ queryParamNodes.push({ tag: "after", attrs: {}, content: cursor });
129
+ }
130
+ const result = await query({
131
+ tag: "iq",
132
+ attrs: { to: S_WHATSAPP_NET, type: "get", xmlns: "w:biz:catalog" },
133
+ content: [
134
+ {
135
+ tag: "product_catalog",
136
+ attrs: { jid: jid, allow_shop_source: "true" },
137
+ content: queryParamNodes,
138
+ },
139
+ ],
140
+ });
141
+ return parseCatalogNode(result);
142
+ };
143
+ const getCollections = async (jid, limit = 51) => {
144
+ jid = jid || authState.creds.me?.id;
145
+ jid = jidNormalizedUser(jid);
146
+ const result = await query({
147
+ tag: "iq",
148
+ attrs: {
149
+ to: S_WHATSAPP_NET,
150
+ type: "get",
151
+ xmlns: "w:biz:catalog",
152
+ smax_id: "35",
153
+ },
154
+ content: [
155
+ {
156
+ tag: "collections",
157
+ attrs: { biz_jid: jid },
158
+ content: [
159
+ {
160
+ tag: "collection_limit",
161
+ attrs: {},
162
+ content: Buffer.from(limit.toString()),
163
+ },
164
+ {
165
+ tag: "item_limit",
166
+ attrs: {},
167
+ content: Buffer.from(limit.toString()),
168
+ },
169
+ { tag: "width", attrs: {}, content: Buffer.from("100") },
170
+ { tag: "height", attrs: {}, content: Buffer.from("100") },
171
+ ],
172
+ },
173
+ ],
174
+ });
175
+ return parseCollectionsNode(result);
176
+ };
177
+ const getOrderDetails = async (orderId, tokenBase64) => {
178
+ const result = await query({
179
+ tag: "iq",
180
+ attrs: {
181
+ to: S_WHATSAPP_NET,
182
+ type: "get",
183
+ xmlns: "fb:thrift_iq",
184
+ smax_id: "5",
185
+ },
186
+ content: [
187
+ {
188
+ tag: "order",
189
+ attrs: { op: "get", id: orderId },
190
+ content: [
191
+ {
192
+ tag: "image_dimensions",
193
+ attrs: {},
194
+ content: [
195
+ { tag: "width", attrs: {}, content: Buffer.from("100") },
196
+ { tag: "height", attrs: {}, content: Buffer.from("100") },
197
+ ],
198
+ },
199
+ { tag: "token", attrs: {}, content: Buffer.from(tokenBase64) },
200
+ ],
201
+ },
202
+ ],
203
+ });
204
+ return parseOrderDetailsNode(result);
205
+ };
206
+ const productUpdate = async (productId, update) => {
207
+ update = await uploadingNecessaryImagesOfProduct(update, waUploadToServer);
208
+ const editNode = toProductNode(productId, update);
209
+ const result = await query({
210
+ tag: "iq",
211
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "w:biz:catalog" },
212
+ content: [
213
+ {
214
+ tag: "product_catalog_edit",
215
+ attrs: { v: "1" },
216
+ content: [
217
+ editNode,
218
+ { tag: "width", attrs: {}, content: "100" },
219
+ { tag: "height", attrs: {}, content: "100" },
220
+ ],
221
+ },
222
+ ],
223
+ });
224
+ const productCatalogEditNode = getBinaryNodeChild(
225
+ result,
226
+ "product_catalog_edit",
227
+ );
228
+ const productNode = getBinaryNodeChild(productCatalogEditNode, "product");
229
+ return parseProductNode(productNode);
230
+ };
231
+ const productCreate = async (create) => {
232
+ // ensure isHidden is defined
233
+ create.isHidden = !!create.isHidden;
234
+ create = await uploadingNecessaryImagesOfProduct(create, waUploadToServer);
235
+ const createNode = toProductNode(undefined, create);
236
+ const result = await query({
237
+ tag: "iq",
238
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "w:biz:catalog" },
239
+ content: [
240
+ {
241
+ tag: "product_catalog_add",
242
+ attrs: { v: "1" },
243
+ content: [
244
+ createNode,
245
+ { tag: "width", attrs: {}, content: "100" },
246
+ { tag: "height", attrs: {}, content: "100" },
247
+ ],
248
+ },
249
+ ],
250
+ });
251
+ const productCatalogAddNode = getBinaryNodeChild(
252
+ result,
253
+ "product_catalog_add",
254
+ );
255
+ const productNode = getBinaryNodeChild(productCatalogAddNode, "product");
256
+ return parseProductNode(productNode);
257
+ };
258
+ const productDelete = async (productIds) => {
259
+ const result = await query({
260
+ tag: "iq",
261
+ attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "w:biz:catalog" },
262
+ content: [
263
+ {
264
+ tag: "product_catalog_delete",
265
+ attrs: { v: "1" },
266
+ content: productIds.map((id) => ({
267
+ tag: "product",
268
+ attrs: {},
269
+ content: [{ tag: "id", attrs: {}, content: Buffer.from(id) }],
270
+ })),
271
+ },
272
+ ],
273
+ });
274
+ const productCatalogDelNode = getBinaryNodeChild(
275
+ result,
276
+ "product_catalog_delete",
277
+ );
278
+ return { deleted: +(productCatalogDelNode?.attrs.deleted_count || 0) };
279
+ };
280
+ return {
281
+ ...sock,
282
+ logger: config.logger,
283
+ getOrderDetails: getOrderDetails,
284
+ getCatalog: getCatalog,
285
+ getCollections: getCollections,
286
+ productCreate: productCreate,
287
+ productDelete: productDelete,
288
+ productUpdate: productUpdate,
289
+ updateBussinesProfile: updateBussinesProfile,
290
+ updateCoverPhoto: updateCoverPhoto,
291
+ removeCoverPhoto: removeCoverPhoto,
292
+ };
293
+ };