@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,33 @@
1
+ export var XWAPaths;
2
+ (function (XWAPaths) {
3
+ XWAPaths["xwa2_newsletter_create"] = "xwa2_newsletter_create";
4
+ XWAPaths["xwa2_newsletter_subscribers"] = "xwa2_newsletter_subscribers";
5
+ XWAPaths["xwa2_newsletter_subscribed"] = "xwa2_newsletter_subscribed";
6
+ XWAPaths["xwa2_newsletter_view"] = "xwa2_newsletter_view";
7
+ XWAPaths["xwa2_newsletter_metadata"] = "xwa2_newsletter";
8
+ XWAPaths["xwa2_newsletter_admin_count"] = "xwa2_newsletter_admin";
9
+ XWAPaths["xwa2_newsletter_mute_v2"] = "xwa2_newsletter_mute_v2";
10
+ XWAPaths["xwa2_newsletter_unmute_v2"] = "xwa2_newsletter_unmute_v2";
11
+ XWAPaths["xwa2_newsletter_follow"] = "xwa2_newsletter_follow";
12
+ XWAPaths["xwa2_newsletter_unfollow"] = "xwa2_newsletter_unfollow";
13
+ XWAPaths["xwa2_newsletter_change_owner"] = "xwa2_newsletter_change_owner";
14
+ XWAPaths["xwa2_newsletter_demote"] = "xwa2_newsletter_demote";
15
+ XWAPaths["xwa2_newsletter_delete_v2"] = "xwa2_newsletter_delete_v2";
16
+ })(XWAPaths || (XWAPaths = {}));
17
+ export var QueryIds;
18
+ (function (QueryIds) {
19
+ QueryIds["CREATE"] = "8823471724422422";
20
+ QueryIds["UPDATE_METADATA"] = "24250201037901610";
21
+ QueryIds["METADATA"] = "6563316087068696";
22
+ QueryIds["JOB_MUTATION"] = "7150902998257522";
23
+ QueryIds["SUBSCRIBERS"] = "9783111038412085";
24
+ QueryIds["SUBSCRIBED"] = "6388546374527196";
25
+ QueryIds["FOLLOW"] = "7871414976211147";
26
+ QueryIds["UNFOLLOW"] = "7238632346214362";
27
+ QueryIds["MUTE"] = "29766401636284406";
28
+ QueryIds["UNMUTE"] = "9864994326891137";
29
+ QueryIds["ADMIN_COUNT"] = "7130823597031706";
30
+ QueryIds["CHANGE_OWNER"] = "7341777602580933";
31
+ QueryIds["DEMOTE"] = "6551828931592903";
32
+ QueryIds["DELETE"] = "30062808666639665";
33
+ })(QueryIds || (QueryIds = {}));
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ import { proto } from "../../WAProto/index.js";
@@ -0,0 +1,2 @@
1
+ import { proto } from "../../WAProto/index.js";
2
+ import {} from "./Message.js";
@@ -0,0 +1,15 @@
1
+ import { Boom } from "@hapi/boom";
2
+ export var SyncState;
3
+ (function (SyncState) {
4
+ /** The socket is connecting, but we haven't received pending notifications yet. */
5
+ SyncState[(SyncState["Connecting"] = 0)] = "Connecting";
6
+ /** Pending notifications received. Buffering events until we decide whether to sync or not. */ SyncState[
7
+ (SyncState["AwaitingInitialSync"] = 1)
8
+ ] = "AwaitingInitialSync";
9
+ /** The initial app state sync (history, etc.) is in progress. Buffering continues. */ SyncState[
10
+ (SyncState["Syncing"] = 2)
11
+ ] = "Syncing";
12
+ /** Initial sync is complete, or was skipped. The socket is fully operational and events are processed in real-time. */ SyncState[
13
+ (SyncState["Online"] = 3)
14
+ ] = "Online";
15
+ })(SyncState || (SyncState = {}));
@@ -0,0 +1 @@
1
+ import { USyncUser } from "../WAUSync/index.js";
@@ -0,0 +1,31 @@
1
+ export * from "./Auth.js";
2
+ export * from "./GroupMetadata.js";
3
+ export * from "./Chat.js";
4
+ export * from "./Contact.js";
5
+ export * from "./State.js";
6
+ export * from "./Message.js";
7
+ export * from "./Socket.js";
8
+ export * from "./Events.js";
9
+ export * from "./Product.js";
10
+ export * from "./Call.js";
11
+ export * from "./Signal.js";
12
+ export * from "./Newsletter.js";
13
+ export var DisconnectReason;
14
+ (function (DisconnectReason) {
15
+ DisconnectReason[(DisconnectReason["connectionClosed"] = 428)] =
16
+ "connectionClosed";
17
+ DisconnectReason[(DisconnectReason["connectionLost"] = 408)] =
18
+ "connectionLost";
19
+ DisconnectReason[(DisconnectReason["connectionReplaced"] = 440)] =
20
+ "connectionReplaced";
21
+ DisconnectReason[(DisconnectReason["timedOut"] = 408)] = "timedOut";
22
+ DisconnectReason[(DisconnectReason["loggedOut"] = 401)] = "loggedOut";
23
+ DisconnectReason[(DisconnectReason["badSession"] = 500)] = "badSession";
24
+ DisconnectReason[(DisconnectReason["restartRequired"] = 515)] =
25
+ "restartRequired";
26
+ DisconnectReason[(DisconnectReason["multideviceMismatch"] = 411)] =
27
+ "multideviceMismatch";
28
+ DisconnectReason[(DisconnectReason["forbidden"] = 403)] = "forbidden";
29
+ DisconnectReason[(DisconnectReason["unavailableService"] = 503)] =
30
+ "unavailableService";
31
+ })(DisconnectReason || (DisconnectReason = {}));
@@ -0,0 +1,293 @@
1
+ import NodeCache from "@cacheable/node-cache";
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { Mutex } from "async-mutex";
4
+ import { randomBytes } from "crypto";
5
+ import PQueue from "p-queue";
6
+ import { DEFAULT_CACHE_TTLS } from "../Defaults/index.js";
7
+ import { Curve, signedKeyPair } from "./crypto.js";
8
+ import { delay, generateRegistrationId } from "./generics.js";
9
+ import { PreKeyManager } from "./pre-key-manager.js";
10
+ /**
11
+ * Adds caching capability to a SignalKeyStore
12
+ * @param store the store to add caching to
13
+ * @param logger to log trace events
14
+ * @param _cache cache store to use
15
+ */ export function makeCacheableSignalKeyStore(store, logger, _cache) {
16
+ const cache =
17
+ _cache ||
18
+ new NodeCache({
19
+ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
20
+ useClones: false,
21
+ deleteOnExpire: true,
22
+ });
23
+ // Mutex for protecting cache operations
24
+ const cacheMutex = new Mutex();
25
+ function getUniqueId(type, id) {
26
+ return `${type}.${id}`;
27
+ }
28
+ return {
29
+ async get(type, ids) {
30
+ return cacheMutex.runExclusive(async () => {
31
+ const data = {};
32
+ const idsToFetch = [];
33
+ for (const id of ids) {
34
+ const item = await cache.get(getUniqueId(type, id));
35
+ if (typeof item !== "undefined") {
36
+ data[id] = item;
37
+ } else {
38
+ idsToFetch.push(id);
39
+ }
40
+ }
41
+ if (idsToFetch.length) {
42
+ logger?.trace({ items: idsToFetch.length }, "loading from store");
43
+ const fetched = await store.get(type, idsToFetch);
44
+ for (const id of idsToFetch) {
45
+ const item = fetched[id];
46
+ if (item) {
47
+ data[id] = item;
48
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
49
+ await cache.set(getUniqueId(type, id), item);
50
+ }
51
+ }
52
+ }
53
+ return data;
54
+ });
55
+ },
56
+ async set(data) {
57
+ return cacheMutex.runExclusive(async () => {
58
+ let keys = 0;
59
+ for (const type in data) {
60
+ for (const id in data[type]) {
61
+ await cache.set(getUniqueId(type, id), data[type][id]);
62
+ keys += 1;
63
+ }
64
+ }
65
+ logger?.trace({ keys: keys }, "updated cache");
66
+ await store.set(data);
67
+ });
68
+ },
69
+ async clear() {
70
+ await cache.flushAll();
71
+ await store.clear?.();
72
+ },
73
+ };
74
+ }
75
+ /**
76
+ * Adds DB-like transaction capability to the SignalKeyStore
77
+ * Uses AsyncLocalStorage for automatic context management
78
+ * @param state the key store to apply this capability to
79
+ * @param logger logger to log events
80
+ * @returns SignalKeyStore with transaction capability
81
+ */ export const addTransactionCapability = (
82
+ state,
83
+ logger,
84
+ { maxCommitRetries, delayBetweenTriesMs },
85
+ ) => {
86
+ const txStorage = new AsyncLocalStorage();
87
+ // Queues for concurrency control (keyed by signal data type - bounded set)
88
+ const keyQueues = new Map();
89
+ // Transaction mutexes with reference counting for cleanup
90
+ const txMutexes = new Map();
91
+ const txMutexRefCounts = new Map();
92
+ // Pre-key manager for specialized operations
93
+ const preKeyManager = new PreKeyManager(state, logger);
94
+ /**
95
+ * Get or create a queue for a specific key type
96
+ */ function getQueue(key) {
97
+ if (!keyQueues.has(key)) {
98
+ keyQueues.set(key, new PQueue({ concurrency: 1 }));
99
+ }
100
+ return keyQueues.get(key);
101
+ }
102
+ /**
103
+ * Get or create a transaction mutex
104
+ */ function getTxMutex(key) {
105
+ if (!txMutexes.has(key)) {
106
+ txMutexes.set(key, new Mutex());
107
+ txMutexRefCounts.set(key, 0);
108
+ }
109
+ return txMutexes.get(key);
110
+ }
111
+ /**
112
+ * Acquire a reference to a transaction mutex
113
+ */ function acquireTxMutexRef(key) {
114
+ const count = txMutexRefCounts.get(key) ?? 0;
115
+ txMutexRefCounts.set(key, count + 1);
116
+ }
117
+ /**
118
+ * Release a reference to a transaction mutex and cleanup if no longer needed
119
+ */ function releaseTxMutexRef(key) {
120
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1;
121
+ txMutexRefCounts.set(key, count);
122
+ // Cleanup if no more references and mutex is not locked
123
+ if (count <= 0) {
124
+ const mutex = txMutexes.get(key);
125
+ if (mutex && !mutex.isLocked()) {
126
+ txMutexes.delete(key);
127
+ txMutexRefCounts.delete(key);
128
+ }
129
+ }
130
+ }
131
+ /**
132
+ * Check if currently in a transaction
133
+ */ function isInTransaction() {
134
+ return !!txStorage.getStore();
135
+ }
136
+ /**
137
+ * Commit transaction with retries
138
+ */ async function commitWithRetry(mutations) {
139
+ if (Object.keys(mutations).length === 0) {
140
+ logger.trace("no mutations in transaction");
141
+ return;
142
+ }
143
+ logger.trace("committing transaction");
144
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
145
+ try {
146
+ await state.set(mutations);
147
+ logger.trace(
148
+ { mutationCount: Object.keys(mutations).length },
149
+ "committed transaction",
150
+ );
151
+ return;
152
+ } catch (error) {
153
+ const retriesLeft = maxCommitRetries - attempt - 1;
154
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
155
+ if (retriesLeft === 0) {
156
+ throw error;
157
+ }
158
+ await delay(delayBetweenTriesMs);
159
+ }
160
+ }
161
+ }
162
+ return {
163
+ get: async (type, ids) => {
164
+ const ctx = txStorage.getStore();
165
+ if (!ctx) {
166
+ // No transaction - direct read without exclusive lock for concurrency
167
+ return state.get(type, ids);
168
+ }
169
+ // In transaction - check cache first
170
+ const cached = ctx.cache[type] || {};
171
+ const missing = ids.filter((id) => !(id in cached));
172
+ if (missing.length > 0) {
173
+ ctx.dbQueries++;
174
+ logger.trace(
175
+ { type: type, count: missing.length },
176
+ "fetching missing keys in transaction",
177
+ );
178
+ const fetched = await getTxMutex(type).runExclusive(() =>
179
+ state.get(type, missing),
180
+ );
181
+ // Update cache
182
+ ctx.cache[type] = ctx.cache[type] || {};
183
+ Object.assign(ctx.cache[type], fetched);
184
+ }
185
+ // Return requested ids from cache
186
+ const result = {};
187
+ for (const id of ids) {
188
+ const value = ctx.cache[type]?.[id];
189
+ if (value !== undefined && value !== null) {
190
+ result[id] = value;
191
+ }
192
+ }
193
+ return result;
194
+ },
195
+ set: async (data) => {
196
+ const ctx = txStorage.getStore();
197
+ if (!ctx) {
198
+ // No transaction - direct write with queue protection
199
+ const types = Object.keys(data);
200
+ // Process pre-keys with validation
201
+ for (const type_ of types) {
202
+ const type = type_;
203
+ if (type === "pre-key") {
204
+ await preKeyManager.validateDeletions(data, type);
205
+ }
206
+ }
207
+ // Write all data in parallel
208
+ await Promise.all(
209
+ types.map((type) =>
210
+ getQueue(type).add(async () => {
211
+ const typeData = { [type]: data[type] };
212
+ await state.set(typeData);
213
+ }),
214
+ ),
215
+ );
216
+ return;
217
+ }
218
+ // In transaction - update cache and mutations
219
+ logger.trace({ types: Object.keys(data) }, "caching in transaction");
220
+ for (const key_ in data) {
221
+ const key = key_;
222
+ // Ensure structures exist
223
+ ctx.cache[key] = ctx.cache[key] || {};
224
+ ctx.mutations[key] = ctx.mutations[key] || {};
225
+ // Special handling for pre-keys
226
+ if (key === "pre-key") {
227
+ await preKeyManager.processOperations(
228
+ data,
229
+ key,
230
+ ctx.cache,
231
+ ctx.mutations,
232
+ true,
233
+ );
234
+ } else {
235
+ // Normal key types
236
+ Object.assign(ctx.cache[key], data[key]);
237
+ Object.assign(ctx.mutations[key], data[key]);
238
+ }
239
+ }
240
+ },
241
+ isInTransaction: isInTransaction,
242
+ transaction: async (work, key) => {
243
+ const existing = txStorage.getStore();
244
+ // Nested transaction - reuse existing context
245
+ if (existing) {
246
+ logger.trace("reusing existing transaction context");
247
+ return work();
248
+ }
249
+ // New transaction - acquire mutex and create context
250
+ const mutex = getTxMutex(key);
251
+ acquireTxMutexRef(key);
252
+ try {
253
+ return await mutex.runExclusive(async () => {
254
+ const ctx = { cache: {}, mutations: {}, dbQueries: 0 };
255
+ logger.trace("entering transaction");
256
+ try {
257
+ const result = await txStorage.run(ctx, work);
258
+ // Commit mutations
259
+ await commitWithRetry(ctx.mutations);
260
+ logger.trace({ dbQueries: ctx.dbQueries }, "transaction completed");
261
+ return result;
262
+ } catch (error) {
263
+ logger.error({ error: error }, "transaction failed, rolling back");
264
+ throw error;
265
+ }
266
+ });
267
+ } finally {
268
+ releaseTxMutexRef(key);
269
+ }
270
+ },
271
+ };
272
+ };
273
+ export const initAuthCreds = () => {
274
+ const identityKey = Curve.generateKeyPair();
275
+ return {
276
+ noiseKey: Curve.generateKeyPair(),
277
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
278
+ signedIdentityKey: identityKey,
279
+ signedPreKey: signedKeyPair(identityKey, 1),
280
+ registrationId: generateRegistrationId(),
281
+ advSecretKey: randomBytes(32).toString("base64"),
282
+ processedHistoryMessages: [],
283
+ nextPreKeyId: 1,
284
+ firstUnuploadedPreKeyId: 1,
285
+ accountSyncCounter: 0,
286
+ accountSettings: { unarchiveChats: false },
287
+ registered: false,
288
+ pairingCode: undefined,
289
+ lastPropHash: undefined,
290
+ routingInfo: undefined,
291
+ additionalData: undefined,
292
+ };
293
+ };
@@ -0,0 +1,32 @@
1
+ import { platform, release } from "node:os";
2
+ import { proto } from "../../WAProto/index.js";
3
+ const PLATFORM_MAP = {
4
+ aix: "AIX",
5
+ darwin: "Mac OS",
6
+ win32: "Windows",
7
+ android: "Android",
8
+ freebsd: "FreeBSD",
9
+ openbsd: "OpenBSD",
10
+ sunos: "Solaris",
11
+ linux: undefined,
12
+ haiku: undefined,
13
+ cygwin: undefined,
14
+ netbsd: undefined,
15
+ };
16
+ export const Browsers = {
17
+ ubuntu: (browser) => ["Ubuntu", browser, "22.04.4"],
18
+ macOS: (browser) => ["Mac OS", browser, "14.4.1"],
19
+ baileys: (browser) => ["Baileys", browser, "6.5.0"],
20
+ windows: (browser) => ["Windows", browser, "10.0.22631"],
21
+ android: (browser) => [browser, "Android", ""],
22
+ /** The appropriate browser based on your OS & release */
23
+ appropriate: (browser) => [
24
+ PLATFORM_MAP[platform()] || "Ubuntu",
25
+ browser,
26
+ release(),
27
+ ],
28
+ };
29
+ export const getPlatformId = (browser) => {
30
+ const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()];
31
+ return platformType ? platformType.toString() : "1"; //chrome
32
+ };
@@ -0,0 +1,245 @@
1
+ import { Boom } from "@hapi/boom";
2
+ import { createHash } from "crypto";
3
+ import { createWriteStream, promises as fs } from "fs";
4
+ import { tmpdir } from "os";
5
+ import { join } from "path";
6
+ import {
7
+ getBinaryNodeChild,
8
+ getBinaryNodeChildren,
9
+ getBinaryNodeChildString,
10
+ } from "../WABinary/index.js";
11
+ import { generateMessageIDV2 } from "./generics.js";
12
+ import { getStream, getUrlFromDirectPath } from "./messages-media.js";
13
+ export const parseCatalogNode = (node) => {
14
+ const catalogNode = getBinaryNodeChild(node, "product_catalog");
15
+ const products = getBinaryNodeChildren(catalogNode, "product").map(
16
+ parseProductNode,
17
+ );
18
+ const paging = getBinaryNodeChild(catalogNode, "paging");
19
+ return {
20
+ products: products,
21
+ nextPageCursor: paging
22
+ ? getBinaryNodeChildString(paging, "after")
23
+ : undefined,
24
+ };
25
+ };
26
+ export const parseCollectionsNode = (node) => {
27
+ const collectionsNode = getBinaryNodeChild(node, "collections");
28
+ const collections = getBinaryNodeChildren(collectionsNode, "collection").map(
29
+ (collectionNode) => {
30
+ const id = getBinaryNodeChildString(collectionNode, "id");
31
+ const name = getBinaryNodeChildString(collectionNode, "name");
32
+ const products = getBinaryNodeChildren(collectionNode, "product").map(
33
+ parseProductNode,
34
+ );
35
+ return {
36
+ id: id,
37
+ name: name,
38
+ products: products,
39
+ status: parseStatusInfo(collectionNode),
40
+ };
41
+ },
42
+ );
43
+ return { collections: collections };
44
+ };
45
+ export const parseOrderDetailsNode = (node) => {
46
+ const orderNode = getBinaryNodeChild(node, "order");
47
+ const products = getBinaryNodeChildren(orderNode, "product").map(
48
+ (productNode) => {
49
+ const imageNode = getBinaryNodeChild(productNode, "image");
50
+ return {
51
+ id: getBinaryNodeChildString(productNode, "id"),
52
+ name: getBinaryNodeChildString(productNode, "name"),
53
+ imageUrl: getBinaryNodeChildString(imageNode, "url"),
54
+ price: +getBinaryNodeChildString(productNode, "price"),
55
+ currency: getBinaryNodeChildString(productNode, "currency"),
56
+ quantity: +getBinaryNodeChildString(productNode, "quantity"),
57
+ };
58
+ },
59
+ );
60
+ const priceNode = getBinaryNodeChild(orderNode, "price");
61
+ const orderDetails = {
62
+ price: {
63
+ total: +getBinaryNodeChildString(priceNode, "total"),
64
+ currency: getBinaryNodeChildString(priceNode, "currency"),
65
+ },
66
+ products: products,
67
+ };
68
+ return orderDetails;
69
+ };
70
+ export const toProductNode = (productId, product) => {
71
+ const attrs = {};
72
+ const content = [];
73
+ if (typeof productId !== "undefined") {
74
+ content.push({ tag: "id", attrs: {}, content: Buffer.from(productId) });
75
+ }
76
+ if (typeof product.name !== "undefined") {
77
+ content.push({
78
+ tag: "name",
79
+ attrs: {},
80
+ content: Buffer.from(product.name),
81
+ });
82
+ }
83
+ if (typeof product.description !== "undefined") {
84
+ content.push({
85
+ tag: "description",
86
+ attrs: {},
87
+ content: Buffer.from(product.description),
88
+ });
89
+ }
90
+ if (typeof product.retailerId !== "undefined") {
91
+ content.push({
92
+ tag: "retailer_id",
93
+ attrs: {},
94
+ content: Buffer.from(product.retailerId),
95
+ });
96
+ }
97
+ if (product.images.length) {
98
+ content.push({
99
+ tag: "media",
100
+ attrs: {},
101
+ content: product.images.map((img) => {
102
+ if (!("url" in img)) {
103
+ throw new Boom("Expected img for product to already be uploaded", {
104
+ statusCode: 400,
105
+ });
106
+ }
107
+ return {
108
+ tag: "image",
109
+ attrs: {},
110
+ content: [
111
+ { tag: "url", attrs: {}, content: Buffer.from(img.url.toString()) },
112
+ ],
113
+ };
114
+ }),
115
+ });
116
+ }
117
+ if (typeof product.price !== "undefined") {
118
+ content.push({
119
+ tag: "price",
120
+ attrs: {},
121
+ content: Buffer.from(product.price.toString()),
122
+ });
123
+ }
124
+ if (typeof product.currency !== "undefined") {
125
+ content.push({
126
+ tag: "currency",
127
+ attrs: {},
128
+ content: Buffer.from(product.currency),
129
+ });
130
+ }
131
+ if ("originCountryCode" in product) {
132
+ if (typeof product.originCountryCode === "undefined") {
133
+ attrs["compliance_category"] = "COUNTRY_ORIGIN_EXEMPT";
134
+ } else {
135
+ content.push({
136
+ tag: "compliance_info",
137
+ attrs: {},
138
+ content: [
139
+ {
140
+ tag: "country_code_origin",
141
+ attrs: {},
142
+ content: Buffer.from(product.originCountryCode),
143
+ },
144
+ ],
145
+ });
146
+ }
147
+ }
148
+ if (typeof product.isHidden !== "undefined") {
149
+ attrs["is_hidden"] = product.isHidden.toString();
150
+ }
151
+ const node = { tag: "product", attrs: attrs, content: content };
152
+ return node;
153
+ };
154
+ export const parseProductNode = (productNode) => {
155
+ const isHidden = productNode.attrs.is_hidden === "true";
156
+ const id = getBinaryNodeChildString(productNode, "id");
157
+ const mediaNode = getBinaryNodeChild(productNode, "media");
158
+ const statusInfoNode = getBinaryNodeChild(productNode, "status_info");
159
+ const product = {
160
+ id: id,
161
+ imageUrls: parseImageUrls(mediaNode),
162
+ reviewStatus: {
163
+ whatsapp: getBinaryNodeChildString(statusInfoNode, "status"),
164
+ },
165
+ availability: "in stock",
166
+ name: getBinaryNodeChildString(productNode, "name"),
167
+ retailerId: getBinaryNodeChildString(productNode, "retailer_id"),
168
+ url: getBinaryNodeChildString(productNode, "url"),
169
+ description: getBinaryNodeChildString(productNode, "description"),
170
+ price: +getBinaryNodeChildString(productNode, "price"),
171
+ currency: getBinaryNodeChildString(productNode, "currency"),
172
+ isHidden: isHidden,
173
+ };
174
+ return product;
175
+ };
176
+ /**
177
+ * Uploads images not already uploaded to WA's servers
178
+ */ export async function uploadingNecessaryImagesOfProduct(
179
+ product,
180
+ waUploadToServer,
181
+ timeoutMs = 3e4,
182
+ ) {
183
+ product = {
184
+ ...product,
185
+ images: product.images
186
+ ? await uploadingNecessaryImages(
187
+ product.images,
188
+ waUploadToServer,
189
+ timeoutMs,
190
+ )
191
+ : product.images,
192
+ };
193
+ return product;
194
+ }
195
+ /**
196
+ * Uploads images not already uploaded to WA's servers
197
+ */ export const uploadingNecessaryImages = async (
198
+ images,
199
+ waUploadToServer,
200
+ timeoutMs = 3e4,
201
+ ) => {
202
+ const results = await Promise.all(
203
+ images.map(async (img) => {
204
+ if ("url" in img) {
205
+ const url = img.url.toString();
206
+ if (url.includes(".whatsapp.net")) {
207
+ return { url: url };
208
+ }
209
+ }
210
+ const { stream } = await getStream(img);
211
+ const hasher = createHash("sha256");
212
+ const filePath = join(tmpdir(), "img" + generateMessageIDV2());
213
+ const encFileWriteStream = createWriteStream(filePath);
214
+ for await (const block of stream) {
215
+ hasher.update(block);
216
+ encFileWriteStream.write(block);
217
+ }
218
+ const sha = hasher.digest("base64");
219
+ const { directPath } = await waUploadToServer(filePath, {
220
+ mediaType: "product-catalog-image",
221
+ fileEncSha256B64: sha,
222
+ timeoutMs: timeoutMs,
223
+ });
224
+ await fs
225
+ .unlink(filePath)
226
+ .catch((err) => console.log("Error deleting temp file ", err));
227
+ return { url: getUrlFromDirectPath(directPath) };
228
+ }),
229
+ );
230
+ return results;
231
+ };
232
+ const parseImageUrls = (mediaNode) => {
233
+ const imgNode = getBinaryNodeChild(mediaNode, "image");
234
+ return {
235
+ requested: getBinaryNodeChildString(imgNode, "request_image_url"),
236
+ original: getBinaryNodeChildString(imgNode, "original_image_url"),
237
+ };
238
+ };
239
+ const parseStatusInfo = (mediaNode) => {
240
+ const node = getBinaryNodeChild(mediaNode, "status_info");
241
+ return {
242
+ status: getBinaryNodeChildString(node, "status"),
243
+ canAppeal: getBinaryNodeChildString(node, "can_appeal") === "true",
244
+ };
245
+ };