@kanaraa/baileys 3.4.0 → 3.4.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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "version": [2, 3000, 1043857760]
3
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = queueJob;
4
+ const _queueAsyncBuckets = new Map();
5
+ const _gcLimit = 10000;
6
+ async function _asyncQueueExecutor(queue, cleanup) {
7
+ let offt = 0;
8
+ // eslint-disable-next-line no-constant-condition
9
+ while (true) {
10
+ const limit = Math.min(queue.length, _gcLimit);
11
+ for (let i = offt; i < limit; i++) {
12
+ const job = queue[i];
13
+ try {
14
+ job.resolve(await job.awaitable());
15
+ }
16
+ catch (e) {
17
+ job.reject(e);
18
+ }
19
+ }
20
+ if (limit < queue.length) {
21
+ if (limit >= _gcLimit) {
22
+ queue.splice(0, limit);
23
+ offt = 0;
24
+ }
25
+ else {
26
+ offt = limit;
27
+ }
28
+ }
29
+ else {
30
+ break;
31
+ }
32
+ }
33
+ cleanup();
34
+ }
35
+ function queueJob(bucket, awaitable) {
36
+ // Skip name assignment since it's readonly in strict mode
37
+ if (typeof bucket !== 'string') {
38
+ console.warn('Unhandled bucket type (for naming):', typeof bucket, bucket);
39
+ }
40
+ let inactive = false;
41
+ if (!_queueAsyncBuckets.has(bucket)) {
42
+ _queueAsyncBuckets.set(bucket, []);
43
+ inactive = true;
44
+ }
45
+ const queue = _queueAsyncBuckets.get(bucket);
46
+ const job = new Promise((resolve, reject) => {
47
+ queue.push({
48
+ awaitable,
49
+ resolve: resolve,
50
+ reject
51
+ });
52
+ });
53
+ if (inactive) {
54
+ _asyncQueueExecutor(queue, () => _queueAsyncBuckets.delete(bucket));
55
+ }
56
+ return job;
57
+ }
@@ -1165,6 +1165,27 @@ export const makeMessagesSocket = (config) => {
1165
1165
  statusJidList: options.statusJidList,
1166
1166
  additionalNodes
1167
1167
  });
1168
+
1169
+ if (content && typeof content === 'object' && 'richMessage' in content && content.richMessage?.bypassDownload !== false) {
1170
+ const editMsg = {
1171
+ botForwardedMessage: {
1172
+ message: {
1173
+ protocolMessage: {
1174
+ key: {
1175
+ remoteJid: jid,
1176
+ fromMe: true,
1177
+ id: fullMsg.key.id
1178
+ },
1179
+ type: 14,
1180
+ editedMessage: fullMsg.message
1181
+ }
1182
+ }
1183
+ }
1184
+ };
1185
+ await relayMessage(jid, editMsg, {
1186
+ messageId: generateMessageIDV2(authState.creds.me.id)
1187
+ });
1188
+ }
1168
1189
  if (config.emitOwnEvents) {
1169
1190
  process.nextTick(async () => {
1170
1191
  await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeUSyncSocket = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WABinary_1 = require("../WABinary");
6
+ const socket_1 = require("./socket");
7
+ const makeUSyncSocket = (config) => {
8
+ const sock = (0, socket_1.makeSocket)(config);
9
+ const { generateMessageTag, query, } = sock;
10
+ const executeUSyncQuery = async (usyncQuery) => {
11
+ if (usyncQuery.protocols.length === 0) {
12
+ throw new boom_1.Boom('USyncQuery must have at least one protocol');
13
+ }
14
+ // todo: validate users, throw WARNING on no valid users
15
+ // variable below has only validated users
16
+ const validUsers = usyncQuery.users;
17
+ const userNodes = validUsers.map((user) => {
18
+ return {
19
+ tag: 'user',
20
+ attrs: {
21
+ jid: !user.phone ? user.id : undefined,
22
+ },
23
+ content: usyncQuery.protocols
24
+ .map((a) => a.getUserElement(user))
25
+ .filter(a => a !== null)
26
+ };
27
+ });
28
+ const listNode = {
29
+ tag: 'list',
30
+ attrs: {},
31
+ content: userNodes
32
+ };
33
+ const queryNode = {
34
+ tag: 'query',
35
+ attrs: {},
36
+ content: usyncQuery.protocols.map((a) => a.getQueryElement())
37
+ };
38
+ const iq = {
39
+ tag: 'iq',
40
+ attrs: {
41
+ to: WABinary_1.S_WHATSAPP_NET,
42
+ type: 'get',
43
+ xmlns: 'usync',
44
+ },
45
+ content: [
46
+ {
47
+ tag: 'usync',
48
+ attrs: {
49
+ context: usyncQuery.context,
50
+ mode: usyncQuery.mode,
51
+ sid: generateMessageTag(),
52
+ last: 'true',
53
+ index: '0',
54
+ },
55
+ content: [
56
+ queryNode,
57
+ listNode
58
+ ]
59
+ }
60
+ ],
61
+ };
62
+ const result = await query(iq);
63
+ return usyncQuery.parseUSyncQueryResult(result);
64
+ };
65
+ return {
66
+ ...sock,
67
+ executeUSyncQuery,
68
+ };
69
+ };
70
+ exports.makeUSyncSocket = makeUSyncSocket;
@@ -0,0 +1,8 @@
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.makeInMemoryStore = void 0;
7
+ const make_in_memory_store_1 = __importDefault(require("./make-in-memory-store"));
8
+ exports.makeInMemoryStore = make_in_memory_store_1.default;
@@ -0,0 +1,439 @@
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.waLabelAssociationKey = exports.waMessageID = exports.waChatKey = void 0;
7
+ const WAProto_1 = require("../../WAProto");
8
+ const Defaults_1 = require("../Defaults");
9
+ const LabelAssociation_1 = require("../Types/LabelAssociation");
10
+ const Utils_1 = require("../Utils");
11
+ const WABinary_1 = require("../WABinary");
12
+ const make_ordered_dictionary_1 = __importDefault(require("./make-ordered-dictionary"));
13
+ const object_repository_1 = require("./object-repository");
14
+ const waChatKey = (pin) => ({
15
+ key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
16
+ compare: (k1, k2) => k2.localeCompare(k1)
17
+ });
18
+ exports.waChatKey = waChatKey;
19
+ const waMessageID = (m) => m.key.id || '';
20
+ exports.waMessageID = waMessageID;
21
+ exports.waLabelAssociationKey = {
22
+ key: (la) => (la.type === LabelAssociation_1.LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
23
+ compare: (k1, k2) => k2.localeCompare(k1)
24
+ };
25
+ const makeMessagesDictionary = () => (0, make_ordered_dictionary_1.default)(exports.waMessageID);
26
+ exports.default = (config) => {
27
+ const socket = config.socket;
28
+ const chatKey = config.chatKey || (0, exports.waChatKey)(true);
29
+ const labelAssociationKey = config.labelAssociationKey || exports.waLabelAssociationKey;
30
+ const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
31
+ const KeyedDB = require('@adiwajshing/keyed-db').default;
32
+ const chats = new KeyedDB(chatKey, c => c.id);
33
+ const messages = {};
34
+ const contacts = {};
35
+ const groupMetadata = {};
36
+ const presences = {};
37
+ const state = { connection: 'close' };
38
+ const labels = new object_repository_1.ObjectRepository();
39
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
40
+ const assertMessageList = (jid) => {
41
+ if (!messages[jid]) {
42
+ messages[jid] = makeMessagesDictionary();
43
+ }
44
+ return messages[jid];
45
+ };
46
+ const contactsUpsert = (newContacts) => {
47
+ const oldContacts = new Set(Object.keys(contacts));
48
+ for (const contact of newContacts) {
49
+ oldContacts.delete(contact.id);
50
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
51
+ }
52
+ return oldContacts;
53
+ };
54
+ const labelsUpsert = (newLabels) => {
55
+ for (const label of newLabels) {
56
+ labels.upsertById(label.id, label);
57
+ }
58
+ };
59
+ const getValidContacts = () => {
60
+ for (const contact of Object.keys(contacts)) {
61
+ if (contact.indexOf('@') < 0) {
62
+ delete contacts[contact];
63
+ }
64
+ }
65
+ return Object.keys(contacts);
66
+ };
67
+ /**
68
+ * binds to a WileysEventEmitter.
69
+ * It listens to all events and constructs a state that you can query accurate data from.
70
+ * Eg. can use the store to fetch chats, contacts, messages etc.
71
+ * @param ev typically the event emitter from the socket connection
72
+ */
73
+ const bind = (ev) => {
74
+ ev.on('connection.update', update => {
75
+ Object.assign(state, update);
76
+ });
77
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
78
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
79
+ return; // FOR NOW,
80
+ //TODO: HANDLE
81
+ }
82
+ if (isLatest) {
83
+ chats.clear();
84
+ for (const id in messages) {
85
+ delete messages[id];
86
+ }
87
+ }
88
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
89
+ logger.debug({ chatsAdded }, 'synced chats');
90
+ const oldContacts = contactsUpsert(newContacts);
91
+ if (isLatest) {
92
+ for (const jid of oldContacts) {
93
+ delete contacts[jid];
94
+ }
95
+ }
96
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
97
+ for (const msg of newMessages) {
98
+ const jid = msg.key.remoteJid;
99
+ const list = assertMessageList(jid);
100
+ list.upsert(msg, 'prepend');
101
+ }
102
+ logger.debug({ messages: newMessages.length }, 'synced messages');
103
+ });
104
+ ev.on('contacts.upsert', contacts => {
105
+ contactsUpsert(contacts);
106
+ });
107
+ ev.on('contacts.update', async (updates) => {
108
+ var _a;
109
+ for (const update of updates) {
110
+ let contact;
111
+ if (contacts[update.id]) {
112
+ contact = contacts[update.id];
113
+ }
114
+ else {
115
+ const validContacts = getValidContacts();
116
+ const contactHashes = validContacts.map((contactId) => {
117
+ const { user } = (0, WABinary_1.jidDecode)(contactId);
118
+ return [contactId, ((0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
119
+ });
120
+ contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
121
+ }
122
+ if (contact) {
123
+ if (update.imgUrl === 'changed') {
124
+ contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
125
+ }
126
+ else if (update.imgUrl === 'removed') {
127
+ delete contact.imgUrl;
128
+ }
129
+ Object.assign(contacts[contact.id], contact);
130
+ }
131
+ else {
132
+ logger.debug({ update }, 'got update for non-existant contact');
133
+ }
134
+ }
135
+ });
136
+ ev.on('chats.upsert', newChats => {
137
+ chats.upsert(...newChats);
138
+ });
139
+ ev.on('chats.update', updates => {
140
+ for (let update of updates) {
141
+ const result = chats.update(update.id, chat => {
142
+ if (update.unreadCount > 0) {
143
+ update = { ...update };
144
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
145
+ }
146
+ Object.assign(chat, update);
147
+ });
148
+ if (!result) {
149
+ logger.debug({ update }, 'got update for non-existant chat');
150
+ }
151
+ }
152
+ });
153
+ ev.on('labels.edit', (label) => {
154
+ if (label.deleted) {
155
+ return labels.deleteById(label.id);
156
+ }
157
+ // WhatsApp can store only up to 20 labels
158
+ if (labels.count() < 20) {
159
+ return labels.upsertById(label.id, label);
160
+ }
161
+ logger.error('Labels count exceed');
162
+ });
163
+ ev.on('labels.association', ({ type, association }) => {
164
+ switch (type) {
165
+ case 'add':
166
+ labelAssociations.upsert(association);
167
+ break;
168
+ case 'remove':
169
+ labelAssociations.delete(association);
170
+ break;
171
+ default:
172
+ console.error(`unknown operation type [${type}]`);
173
+ }
174
+ });
175
+ ev.on('presence.update', ({ id, presences: update }) => {
176
+ presences[id] = presences[id] || {};
177
+ Object.assign(presences[id], update);
178
+ });
179
+ ev.on('chats.delete', deletions => {
180
+ for (const item of deletions) {
181
+ if (chats.get(item)) {
182
+ chats.deleteById(item);
183
+ }
184
+ }
185
+ });
186
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
187
+ switch (type) {
188
+ case 'append':
189
+ case 'notify':
190
+ for (const msg of newMessages) {
191
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
192
+ const list = assertMessageList(jid);
193
+ list.upsert(msg, 'append');
194
+ if (type === 'notify' && !chats.get(jid)) {
195
+ ev.emit('chats.upsert', [
196
+ {
197
+ id: jid,
198
+ conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
199
+ unreadCount: 1
200
+ }
201
+ ]);
202
+ }
203
+ }
204
+ break;
205
+ }
206
+ });
207
+ ev.on('messages.update', updates => {
208
+ var _a;
209
+ for (const { update, key } of updates) {
210
+ const list = assertMessageList((0, WABinary_1.jidNormalizedUser)(key.remoteJid));
211
+ if (update === null || update === void 0 ? void 0 : update.status) {
212
+ const listStatus = (_a = list.get(key.id)) === null || _a === void 0 ? void 0 : _a.status;
213
+ if (listStatus && (update === null || update === void 0 ? void 0 : update.status) <= listStatus) {
214
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
215
+ delete update.status;
216
+ logger.debug({ update }, 'new update object');
217
+ }
218
+ }
219
+ const result = list.updateAssign(key.id, update);
220
+ if (!result) {
221
+ logger.debug({ update }, 'got update for non-existent message');
222
+ }
223
+ }
224
+ });
225
+ ev.on('messages.delete', item => {
226
+ if ('all' in item) {
227
+ const list = messages[item.jid];
228
+ list === null || list === void 0 ? void 0 : list.clear();
229
+ }
230
+ else {
231
+ const jid = item.keys[0].remoteJid;
232
+ const list = messages[jid];
233
+ if (list) {
234
+ const idSet = new Set(item.keys.map(k => k.id));
235
+ list.filter(m => !idSet.has(m.key.id));
236
+ }
237
+ }
238
+ });
239
+ ev.on('groups.update', updates => {
240
+ for (const update of updates) {
241
+ const id = update.id;
242
+ if (groupMetadata[id]) {
243
+ Object.assign(groupMetadata[id], update);
244
+ }
245
+ else {
246
+ logger.debug({ update }, 'got update for non-existant group metadata');
247
+ }
248
+ }
249
+ });
250
+ ev.on('group-participants.update', ({ id, participants, action }) => {
251
+ const metadata = groupMetadata[id];
252
+ if (metadata) {
253
+ switch (action) {
254
+ case 'add':
255
+ metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })));
256
+ break;
257
+ case 'demote':
258
+ case 'promote':
259
+ for (const participant of metadata.participants) {
260
+ if (participants.includes(participant.id)) {
261
+ participant.isAdmin = action === 'promote';
262
+ }
263
+ }
264
+ break;
265
+ case 'remove':
266
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id));
267
+ break;
268
+ }
269
+ }
270
+ });
271
+ ev.on('message-receipt.update', updates => {
272
+ for (const { key, receipt } of updates) {
273
+ const obj = messages[key.remoteJid];
274
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
275
+ if (msg) {
276
+ (0, Utils_1.updateMessageWithReceipt)(msg, receipt);
277
+ }
278
+ }
279
+ });
280
+ ev.on('messages.reaction', (reactions) => {
281
+ for (const { key, reaction } of reactions) {
282
+ const obj = messages[key.remoteJid];
283
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
284
+ if (msg) {
285
+ (0, Utils_1.updateMessageWithReaction)(msg, reaction);
286
+ }
287
+ }
288
+ });
289
+ };
290
+ const toJSON = () => ({
291
+ chats,
292
+ contacts,
293
+ messages,
294
+ labels,
295
+ labelAssociations
296
+ });
297
+ const fromJSON = (json) => {
298
+ chats.upsert(...json.chats);
299
+ labelAssociations.upsert(...json.labelAssociations || []);
300
+ contactsUpsert(Object.values(json.contacts));
301
+ labelsUpsert(Object.values(json.labels || {}));
302
+ for (const jid in json.messages) {
303
+ const list = assertMessageList(jid);
304
+ for (const msg of json.messages[jid]) {
305
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append');
306
+ }
307
+ }
308
+ };
309
+ return {
310
+ chats,
311
+ contacts,
312
+ messages,
313
+ groupMetadata,
314
+ state,
315
+ presences,
316
+ labels,
317
+ labelAssociations,
318
+ bind,
319
+ /** loads messages from the store, if not found -- uses the legacy connection */
320
+ loadMessages: async (jid, count, cursor) => {
321
+ const list = assertMessageList(jid);
322
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after';
323
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
324
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
325
+ let messages;
326
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
327
+ if (cursorValue) {
328
+ const msgIdx = list.array.findIndex(m => m.key.id === (cursorKey === null || cursorKey === void 0 ? void 0 : cursorKey.id));
329
+ messages = list.array.slice(0, msgIdx);
330
+ }
331
+ else {
332
+ messages = list.array;
333
+ }
334
+ const diff = count - messages.length;
335
+ if (diff < 0) {
336
+ messages = messages.slice(-count); // get the last X messages
337
+ }
338
+ }
339
+ else {
340
+ messages = [];
341
+ }
342
+ return messages;
343
+ },
344
+ /**
345
+ * Get all available labels for profile
346
+ *
347
+ * Keep in mind that the list is formed from predefined tags and tags
348
+ * that were "caught" during their editing.
349
+ */
350
+ getLabels: () => {
351
+ return labels;
352
+ },
353
+ /**
354
+ * Get labels for chat
355
+ *
356
+ * @returns Label IDs
357
+ **/
358
+ getChatLabels: (chatId) => {
359
+ return labelAssociations.filter((la) => la.chatId === chatId).all();
360
+ },
361
+ /**
362
+ * Get labels for message
363
+ *
364
+ * @returns Label IDs
365
+ **/
366
+ getMessageLabels: (messageId) => {
367
+ const associations = labelAssociations
368
+ .filter((la) => la.messageId === messageId)
369
+ .all();
370
+ return associations.map(({ labelId }) => labelId);
371
+ },
372
+ loadMessage: async (jid, id) => { var _a; return (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.get(id); },
373
+ mostRecentMessage: async (jid) => {
374
+ var _a;
375
+ const message = (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.array.slice(-1)[0];
376
+ return message;
377
+ },
378
+ fetchImageUrl: async (jid, sock) => {
379
+ const contact = contacts[jid];
380
+ if (!contact) {
381
+ return sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid);
382
+ }
383
+ if (typeof contact.imgUrl === 'undefined') {
384
+ contact.imgUrl = await (sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid));
385
+ }
386
+ return contact.imgUrl;
387
+ },
388
+ fetchGroupMetadata: async (jid, sock) => {
389
+ if (!groupMetadata[jid]) {
390
+ const metadata = await (sock === null || sock === void 0 ? void 0 : sock.groupMetadata(jid));
391
+ if (metadata) {
392
+ groupMetadata[jid] = metadata;
393
+ }
394
+ }
395
+ return groupMetadata[jid];
396
+ },
397
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
398
+ // if(!groupMetadata[jid]) {
399
+ // const metadata = await sock?.getBroadcastListInfo(jid)
400
+ // if(metadata) {
401
+ // groupMetadata[jid] = metadata
402
+ // }
403
+ // }
404
+ // return groupMetadata[jid]
405
+ // },
406
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
407
+ const list = messages[remoteJid];
408
+ const msg = list === null || list === void 0 ? void 0 : list.get(id);
409
+ return msg === null || msg === void 0 ? void 0 : msg.userReceipt;
410
+ },
411
+ toJSON,
412
+ fromJSON,
413
+ writeToFile: (path) => {
414
+ // require fs here so that in case "fs" is not available -- the app does not crash
415
+ const { writeFileSync } = require('fs');
416
+ writeFileSync(path, JSON.stringify(toJSON()));
417
+ },
418
+ readFromFile: (path) => {
419
+ // require fs here so that in case "fs" is not available -- the app does not crash
420
+ const { readFileSync, existsSync } = require('fs');
421
+ if (existsSync(path)) {
422
+ logger.debug({ path }, 'reading from file');
423
+ try {
424
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' });
425
+ if (jsonStr.trim().length) {
426
+ const json = JSON.parse(jsonStr);
427
+ fromJSON(json);
428
+ }
429
+ else {
430
+ logger.warn({ path }, 'skipping empty json file');
431
+ }
432
+ }
433
+ catch (err) {
434
+ logger.warn({ path, err }, 'failed to parse json from file');
435
+ }
436
+ }
437
+ }
438
+ };
439
+ };
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function makeOrderedDictionary(idGetter) {
4
+ const array = [];
5
+ const dict = {};
6
+ const get = (id) => dict[id];
7
+ const update = (item) => {
8
+ const id = idGetter(item);
9
+ const idx = array.findIndex(i => idGetter(i) === id);
10
+ if (idx >= 0) {
11
+ array[idx] = item;
12
+ dict[id] = item;
13
+ }
14
+ return false;
15
+ };
16
+ const upsert = (item, mode) => {
17
+ const id = idGetter(item);
18
+ if (get(id)) {
19
+ update(item);
20
+ }
21
+ else {
22
+ if (mode === 'append') {
23
+ array.push(item);
24
+ }
25
+ else {
26
+ array.splice(0, 0, item);
27
+ }
28
+ dict[id] = item;
29
+ }
30
+ };
31
+ const remove = (item) => {
32
+ const id = idGetter(item);
33
+ const idx = array.findIndex(i => idGetter(i) === id);
34
+ if (idx >= 0) {
35
+ array.splice(idx, 1);
36
+ delete dict[id];
37
+ return true;
38
+ }
39
+ return false;
40
+ };
41
+ return {
42
+ array,
43
+ get,
44
+ upsert,
45
+ update,
46
+ remove,
47
+ updateAssign: (id, update) => {
48
+ const item = get(id);
49
+ if (item) {
50
+ Object.assign(item, update);
51
+ delete dict[id];
52
+ dict[idGetter(item)] = item;
53
+ return true;
54
+ }
55
+ return false;
56
+ },
57
+ clear: () => {
58
+ array.splice(0, array.length);
59
+ for (const key of Object.keys(dict)) {
60
+ delete dict[key];
61
+ }
62
+ },
63
+ filter: (contain) => {
64
+ let i = 0;
65
+ while (i < array.length) {
66
+ if (!contain(array[i])) {
67
+ delete dict[idGetter(array[i])];
68
+ array.splice(i, 1);
69
+ }
70
+ else {
71
+ i += 1;
72
+ }
73
+ }
74
+ },
75
+ toJSON: () => array,
76
+ fromJSON: (newItems) => {
77
+ array.splice(0, array.length, ...newItems);
78
+ }
79
+ };
80
+ }
81
+ exports.default = makeOrderedDictionary;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ObjectRepository = void 0;
4
+ class ObjectRepository {
5
+ constructor(entities = {}) {
6
+ this.entityMap = new Map(Object.entries(entities));
7
+ }
8
+ findById(id) {
9
+ return this.entityMap.get(id);
10
+ }
11
+ findAll() {
12
+ return Array.from(this.entityMap.values());
13
+ }
14
+ upsertById(id, entity) {
15
+ return this.entityMap.set(id, { ...entity });
16
+ }
17
+ deleteById(id) {
18
+ return this.entityMap.delete(id);
19
+ }
20
+ count() {
21
+ return this.entityMap.size;
22
+ }
23
+ toJSON() {
24
+ return this.findAll();
25
+ }
26
+ }
27
+ exports.ObjectRepository = ObjectRepository;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.XWAPaths = exports.MexOperations = void 0;
4
+ var MexOperations;
5
+ (function (MexOperations) {
6
+ MexOperations["PROMOTE"] = "NotificationNewsletterAdminPromote";
7
+ MexOperations["DEMOTE"] = "NotificationNewsletterAdminDemote";
8
+ MexOperations["UPDATE"] = "NotificationNewsletterUpdate";
9
+ })(MexOperations || (exports.MexOperations = MexOperations = {}));
10
+ var XWAPaths;
11
+ (function (XWAPaths) {
12
+ XWAPaths["PROMOTE"] = "xwa2_notify_newsletter_admin_promote";
13
+ XWAPaths["DEMOTE"] = "xwa2_notify_newsletter_admin_demote";
14
+ XWAPaths["ADMIN_COUNT"] = "xwa2_newsletter_admin";
15
+ XWAPaths["CREATE"] = "xwa2_newsletter_create";
16
+ XWAPaths["NEWSLETTER"] = "xwa2_newsletter";
17
+ XWAPaths["METADATA_UPDATE"] = "xwa2_notify_newsletter_on_metadata_update";
18
+ })(XWAPaths || (exports.XWAPaths = XWAPaths = {}));
@@ -0,0 +1,63 @@
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.readAndEmitEventStream = exports.captureEventStream = void 0;
7
+ const events_1 = __importDefault(require("events"));
8
+ const fs_1 = require("fs");
9
+ const promises_1 = require("fs/promises");
10
+ const readline_1 = require("readline");
11
+ const generics_1 = require("./generics");
12
+ const make_mutex_1 = require("./make-mutex");
13
+ /**
14
+ * Captures events from a wileys event emitter & stores them in a file
15
+ * @param ev The event emitter to read events from
16
+ * @param filename File to save to
17
+ */
18
+ const captureEventStream = (ev, filename) => {
19
+ const oldEmit = ev.emit;
20
+ // write mutex so data is appended in order
21
+ const writeMutex = (0, make_mutex_1.makeMutex)();
22
+ // monkey patch eventemitter to capture all events
23
+ ev.emit = function (...args) {
24
+ const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
25
+ const result = oldEmit.apply(ev, args);
26
+ writeMutex.mutex(async () => {
27
+ await (0, promises_1.writeFile)(filename, content, { flag: 'a' });
28
+ });
29
+ return result;
30
+ };
31
+ };
32
+ exports.captureEventStream = captureEventStream;
33
+ /**
34
+ * Read event file and emit events from there
35
+ * @param filename filename containing event data
36
+ * @param delayIntervalMs delay between each event emit
37
+ */
38
+ const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
39
+ const ev = new events_1.default();
40
+ const fireEvents = async () => {
41
+ // from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
42
+ const fileStream = (0, fs_1.createReadStream)(filename);
43
+ const rl = (0, readline_1.createInterface)({
44
+ input: fileStream,
45
+ crlfDelay: Infinity
46
+ });
47
+ // Note: we use the crlfDelay option to recognize all instances of CR LF
48
+ // ('\r\n') in input.txt as a single line break.
49
+ for await (const line of rl) {
50
+ if (line) {
51
+ const { event, data } = JSON.parse(line);
52
+ ev.emit(event, data);
53
+ delayIntervalMs && await (0, generics_1.delay)(delayIntervalMs);
54
+ }
55
+ }
56
+ fileStream.close();
57
+ };
58
+ return {
59
+ ev,
60
+ task: fireEvents()
61
+ };
62
+ };
63
+ exports.readAndEmitEventStream = readAndEmitEventStream;
@@ -1658,6 +1658,32 @@ export const generateWAMessageContent = async (message, options) => {
1658
1658
  sections.push(newLayout(layout, suggest.length === 1 ? suggest[0] : suggest));
1659
1659
  }
1660
1660
 
1661
+ if (rich.widget) {
1662
+ const w = rich.widget;
1663
+ sections.push(newLayout('Single', {
1664
+ title: w.title ?? '',
1665
+ sections: w.sections ?? [],
1666
+ actions: (w.actions ?? []).map(a => ({
1667
+ label: a.label ?? '',
1668
+ kind: a.kind ?? 'OTHER',
1669
+ state: a.state ?? 'PENDING',
1670
+ id: a.id ?? ''
1671
+ })),
1672
+ __typename: 'GenAIWidgetCardPrimitive'
1673
+ }));
1674
+ }
1675
+
1676
+ if (rich.footerAction || rich.footerBtn) {
1677
+ const fa = rich.footerAction || rich.footerBtn;
1678
+ sections.push(newLayout('Single', {
1679
+ action: {
1680
+ text: fa.text ?? '',
1681
+ url: fa.url ?? ''
1682
+ },
1683
+ __typename: 'GenAIFooterActionPrimitive'
1684
+ }));
1685
+ }
1686
+
1661
1687
  if (rich.footer) {
1662
1688
  sections.push(newLayout('Single', { text: rich.footer, __typename: 'GenAIMetadataTextPrimitive' }));
1663
1689
  }
@@ -1673,17 +1699,53 @@ export const generateWAMessageContent = async (message, options) => {
1673
1699
  }));
1674
1700
  }
1675
1701
 
1702
+ if (rich.customSections && Array.isArray(rich.customSections)) {
1703
+ sections.push(...rich.customSections);
1704
+ }
1705
+
1706
+ const generateVerificationMetadata = () => {
1707
+ const signatureMaterial = Buffer.from(
1708
+ 'NIXEL.MessageBuilderV4.7-VerificationSignature.Metadata'
1709
+ );
1710
+ const certificateMaterial = Buffer.from(
1711
+ 'NIXEL.MessageBuilderV4.7-CertificateChain.Metadata'
1712
+ );
1713
+ const signature = Buffer.concat([
1714
+ signatureMaterial,
1715
+ randomBytes(64 - signatureMaterial.length)
1716
+ ]).toString('base64');
1717
+ const certificateChain = [
1718
+ Buffer.concat([certificateMaterial, randomBytes(684 - certificateMaterial.length)]).toString('base64'),
1719
+ Buffer.concat([certificateMaterial, randomBytes(892 - certificateMaterial.length)]).toString('base64')
1720
+ ];
1721
+ return {
1722
+ proofs: [
1723
+ {
1724
+ version: 1,
1725
+ useCase: 1,
1726
+ signature,
1727
+ certificateChain
1728
+ }
1729
+ ]
1730
+ };
1731
+ };
1732
+
1676
1733
  const [resolvedSections, resolvedSubmessages] = await Promise.all([
1677
1734
  Toolkit.waitAllPromises(sections),
1678
1735
  Toolkit.waitAllPromises(submessages)
1679
1736
  ]);
1680
1737
 
1738
+ const unifiedJsonStr = JSON.stringify({ response_id: randomUUID(), sections: resolvedSections });
1739
+ const unifiedDataBase64 = Buffer.from(unifiedJsonStr).toString('base64');
1740
+
1681
1741
  m = {
1682
1742
  messageContextInfo: {
1683
1743
  deviceListMetadata: {},
1684
1744
  deviceListMetadataVersion: 2,
1685
1745
  botMetadata: {
1686
1746
  messageDisclaimerText: rich.title ?? '',
1747
+ verificationMetadata: generateVerificationMetadata(),
1748
+ botResponseId: randomUUID(),
1687
1749
  richResponseSourcesMetadata: { sources: richResponseSources }
1688
1750
  }
1689
1751
  },
@@ -1693,12 +1755,12 @@ export const generateWAMessageContent = async (message, options) => {
1693
1755
  messageType: 1,
1694
1756
  submessages: resolvedSubmessages,
1695
1757
  unifiedResponse: {
1696
- data: Buffer.from(JSON.stringify({ response_id: randomUUID(), sections: resolvedSections })).toString('base64')
1758
+ data: unifiedDataBase64
1697
1759
  },
1698
1760
  contextInfo: {
1699
1761
  forwardingScore: 1,
1700
1762
  isForwarded: true,
1701
- forwardedAiBotMessageInfo: { botJid: '0@bot' },
1763
+ forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
1702
1764
  forwardOrigin: 4,
1703
1765
  ...(rich.contextInfo ?? {})
1704
1766
  }
@@ -1991,7 +2053,7 @@ export const generateWAMessageFromContent = (jid, message, options) => {
1991
2053
  }
1992
2054
  }
1993
2055
 
1994
- if (key !== "protocolMessage" && key !== "ephemeralMessage" && !isJidNewsletter(jid)) {
2056
+ if (key !== "protocolMessage" && key !== "ephemeralMessage" && key !== "botForwardedMessage" && !isJidNewsletter(jid)) {
1995
2057
  message.messageContextInfo = {
1996
2058
  threadId: threadId.length > 0 ? threadId : [],
1997
2059
  messageSecret: randomBytes(32),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kanaraa/baileys",
3
3
  "type": "module",
4
- "version": "3.4.0",
4
+ "version": "3.4.2",
5
5
  "description": "Modded Baileys v7, Rebuilt on top of official @whiskeysockets/baileys 7.0.0-rc13, with the interactive & rich-message content types (buttons, lists, carousel, cards, shop/collection, native flow, AI rich response, sticker packs, admin invite, payments, etc.).",
6
6
  "keywords": [
7
7
  "whatsapp",