@crysnovax/baileys 2.6.5 → 2.6.7

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,347 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { WAMessageAddressingMode, WAMessageStubType } from '../Types/index.js';
4
+ import { generateMessageIDV2, unixTimestampSeconds } from '../Utils/index.js';
5
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, isLidUser, isPnUser, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
6
+ import { makeChatsSocket } from './chats.js';
7
+ export const makeGroupsSocket = (config) => {
8
+ const sock = makeChatsSocket(config);
9
+ const { authState, ev, query, upsertMessage } = sock;
10
+ const groupQuery = async (jid, type, content) => query({
11
+ tag: 'iq',
12
+ attrs: {
13
+ type,
14
+ xmlns: 'w:g2',
15
+ to: jid
16
+ },
17
+ content
18
+ });
19
+ const groupMetadata = async (jid) => {
20
+ const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
21
+ return extractGroupMetadata(result);
22
+ };
23
+ const groupFetchAllParticipating = async () => {
24
+ const result = await query({
25
+ tag: 'iq',
26
+ attrs: {
27
+ to: '@g.us',
28
+ xmlns: 'w:g2',
29
+ type: 'get'
30
+ },
31
+ content: [
32
+ {
33
+ tag: 'participating',
34
+ attrs: {},
35
+ content: [
36
+ { tag: 'participants', attrs: {} },
37
+ { tag: 'description', attrs: {} }
38
+ ]
39
+ }
40
+ ]
41
+ });
42
+ const data = {};
43
+ const groupsChild = getBinaryNodeChild(result, 'groups');
44
+ if (groupsChild) {
45
+ const groups = getBinaryNodeChildren(groupsChild, 'group');
46
+ for (const groupNode of groups) {
47
+ const meta = extractGroupMetadata({
48
+ tag: 'result',
49
+ attrs: {},
50
+ content: [groupNode]
51
+ });
52
+ data[meta.id] = meta;
53
+ }
54
+ }
55
+ // TODO: properly parse LID / PN DATA
56
+ sock.ev.emit('groups.update', Object.values(data));
57
+ return data;
58
+ };
59
+ sock.ws.on('CB:ib,,dirty', async (node) => {
60
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
61
+ if (attrs.type !== 'groups') {
62
+ return;
63
+ }
64
+ await groupFetchAllParticipating();
65
+ await sock.cleanDirtyBits('groups');
66
+ });
67
+ return {
68
+ ...sock,
69
+ groupQuery,
70
+ groupMetadata,
71
+ groupCreate: async (subject, participants) => {
72
+ const key = generateMessageIDV2();
73
+ const result = await groupQuery('@g.us', 'set', [
74
+ {
75
+ tag: 'create',
76
+ attrs: {
77
+ subject,
78
+ key
79
+ },
80
+ content: participants.map(jid => ({
81
+ tag: 'participant',
82
+ attrs: { jid }
83
+ }))
84
+ }
85
+ ]);
86
+ return extractGroupMetadata(result);
87
+ },
88
+ groupLeave: async (id) => {
89
+ await groupQuery('@g.us', 'set', [
90
+ {
91
+ tag: 'leave',
92
+ attrs: {},
93
+ content: [{ tag: 'group', attrs: { id } }]
94
+ }
95
+ ]);
96
+ },
97
+ groupUpdateSubject: async (jid, subject) => {
98
+ await groupQuery(jid, 'set', [
99
+ {
100
+ tag: 'subject',
101
+ attrs: {},
102
+ content: Buffer.from(subject, 'utf-8')
103
+ }
104
+ ]);
105
+ },
106
+ groupRequestParticipantsList: async (jid) => {
107
+ const result = await groupQuery(jid, 'get', [
108
+ {
109
+ tag: 'membership_approval_requests',
110
+ attrs: {}
111
+ }
112
+ ]);
113
+ const node = getBinaryNodeChild(result, 'membership_approval_requests');
114
+ const participants = getBinaryNodeChildren(node, 'membership_approval_request');
115
+ return participants.map(v => v.attrs);
116
+ },
117
+ groupRequestParticipantsUpdate: async (jid, participants, action) => {
118
+ const result = await groupQuery(jid, 'set', [
119
+ {
120
+ tag: 'membership_requests_action',
121
+ attrs: {},
122
+ content: [
123
+ {
124
+ tag: action,
125
+ attrs: {},
126
+ content: participants.map(jid => ({
127
+ tag: 'participant',
128
+ attrs: { jid }
129
+ }))
130
+ }
131
+ ]
132
+ }
133
+ ]);
134
+ const node = getBinaryNodeChild(result, 'membership_requests_action');
135
+ const nodeAction = getBinaryNodeChild(node, action);
136
+ const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant');
137
+ return participantsAffected.map(p => {
138
+ return { status: p.attrs.error || '200', jid: p.attrs.jid };
139
+ });
140
+ },
141
+ groupParticipantsUpdate: async (jid, participants, action) => {
142
+ const result = await groupQuery(jid, 'set', [
143
+ {
144
+ tag: action,
145
+ attrs: {},
146
+ content: participants.map(jid => ({
147
+ tag: 'participant',
148
+ attrs: { jid }
149
+ }))
150
+ }
151
+ ]);
152
+ const node = getBinaryNodeChild(result, action);
153
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
154
+ return participantsAffected.map(p => {
155
+ return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p };
156
+ });
157
+ },
158
+ groupUpdateDescription: async (jid, description) => {
159
+ const metadata = await groupMetadata(jid);
160
+ const prev = metadata.descId ?? null;
161
+ await groupQuery(jid, 'set', [
162
+ {
163
+ tag: 'description',
164
+ attrs: {
165
+ ...(description ? { id: generateMessageIDV2() } : { delete: 'true' }),
166
+ ...(prev ? { prev } : {})
167
+ },
168
+ content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
169
+ }
170
+ ]);
171
+ },
172
+ groupInviteCode: async (jid) => {
173
+ const result = await groupQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
174
+ const inviteNode = getBinaryNodeChild(result, 'invite');
175
+ return inviteNode?.attrs.code;
176
+ },
177
+ groupRevokeInvite: async (jid) => {
178
+ const result = await groupQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
179
+ const inviteNode = getBinaryNodeChild(result, 'invite');
180
+ return inviteNode?.attrs.code;
181
+ },
182
+ groupAcceptInvite: async (code) => {
183
+ const results = await groupQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
184
+ const result = getBinaryNodeChild(results, 'group');
185
+ return result?.attrs.jid;
186
+ },
187
+ /**
188
+ * revoke a v4 invite for someone
189
+ * @param groupJid group jid
190
+ * @param invitedJid jid of person you invited
191
+ * @returns true if successful
192
+ */
193
+ groupRevokeInviteV4: async (groupJid, invitedJid) => {
194
+ const result = await groupQuery(groupJid, 'set', [
195
+ { tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
196
+ ]);
197
+ return !!result;
198
+ },
199
+ /**
200
+ * accept a GroupInviteMessage
201
+ * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
202
+ * @param inviteMessage the message to accept
203
+ */
204
+ groupAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
205
+ key = typeof key === 'string' ? { remoteJid: key } : key;
206
+ const results = await groupQuery(inviteMessage.groupJid, 'set', [
207
+ {
208
+ tag: 'accept',
209
+ attrs: {
210
+ code: inviteMessage.inviteCode,
211
+ expiration: inviteMessage.inviteExpiration.toString(),
212
+ admin: key.remoteJid
213
+ }
214
+ }
215
+ ]);
216
+ // if we have the full message key
217
+ // update the invite message to be expired
218
+ if (key.id) {
219
+ // create new invite message that is expired
220
+ inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage);
221
+ inviteMessage.inviteExpiration = 0;
222
+ inviteMessage.inviteCode = '';
223
+ ev.emit('messages.update', [
224
+ {
225
+ key,
226
+ update: {
227
+ message: {
228
+ groupInviteMessage: inviteMessage
229
+ }
230
+ }
231
+ }
232
+ ]);
233
+ }
234
+ // generate the group add message
235
+ await upsertMessage({
236
+ key: {
237
+ remoteJid: inviteMessage.groupJid,
238
+ id: generateMessageIDV2(sock.user?.id),
239
+ fromMe: false,
240
+ participant: key.remoteJid
241
+ },
242
+ messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
243
+ messageStubParameters: [JSON.stringify(authState.creds.me)],
244
+ participant: key.remoteJid,
245
+ messageTimestamp: unixTimestampSeconds()
246
+ }, 'notify');
247
+ return results.attrs.from;
248
+ }),
249
+ groupGetInviteInfo: async (code) => {
250
+ const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }]);
251
+ return extractGroupMetadata(results);
252
+ },
253
+ groupToggleEphemeral: async (jid, ephemeralExpiration) => {
254
+ const content = ephemeralExpiration
255
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
256
+ : { tag: 'not_ephemeral', attrs: {} };
257
+ await groupQuery(jid, 'set', [content]);
258
+ },
259
+ groupSettingUpdate: async (jid, setting) => {
260
+ await groupQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
261
+ },
262
+ groupMemberAddMode: async (jid, mode) => {
263
+ await groupQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }]);
264
+ },
265
+ groupJoinApprovalMode: async (jid, mode) => {
266
+ await groupQuery(jid, 'set', [
267
+ { tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'group_join', attrs: { state: mode } }] }
268
+ ]);
269
+ },
270
+ groupFetchAllParticipating
271
+ };
272
+ };
273
+ export const extractGroupMetadata = (result) => {
274
+ const group = getBinaryNodeChild(result, 'group');
275
+ if (!group) {
276
+ // Mirror WAWeb: surface server/client errors with their code+text instead of crashing.
277
+ const errorNode = getBinaryNodeChild(result, 'error');
278
+ if (errorNode) {
279
+ const code = errorNode.attrs.code ? +errorNode.attrs.code : 500;
280
+ const text = errorNode.attrs.text || 'group metadata query failed';
281
+ throw new Boom(text, { statusCode: code, data: errorNode });
282
+ }
283
+ throw new Boom('Invalid group metadata response: missing <group> node', { data: result });
284
+ }
285
+ if (!group.attrs.id) {
286
+ throw new Boom('Invalid group metadata response: missing group id', { data: group });
287
+ }
288
+ const descChild = getBinaryNodeChild(group, 'description');
289
+ let desc;
290
+ let descId;
291
+ let descOwner;
292
+ let descOwnerPn;
293
+ let descOwnerUsername;
294
+ let descTime;
295
+ if (descChild) {
296
+ desc = getBinaryNodeChildString(descChild, 'body');
297
+ descOwner = descChild.attrs.participant ? jidNormalizedUser(descChild.attrs.participant) : undefined;
298
+ descOwnerPn = descChild.attrs.participant_pn ? jidNormalizedUser(descChild.attrs.participant_pn) : undefined;
299
+ descOwnerUsername = descChild.attrs.participant_username || undefined;
300
+ descTime = +descChild.attrs.t;
301
+ descId = descChild.attrs.id;
302
+ }
303
+ const groupId = group.attrs.id.includes('@') ? group.attrs.id : jidEncode(group.attrs.id, 'g.us');
304
+ const eph = getBinaryNodeChild(group, 'ephemeral')?.attrs.expiration;
305
+ const memberAddMode = getBinaryNodeChildString(group, 'member_add_mode') === 'all_member_add';
306
+ const metadata = {
307
+ id: groupId,
308
+ notify: group.attrs.notify,
309
+ addressingMode: group.attrs.addressing_mode === 'lid' ? WAMessageAddressingMode.LID : WAMessageAddressingMode.PN,
310
+ subject: group.attrs.subject,
311
+ subjectOwner: group.attrs.s_o,
312
+ subjectOwnerPn: group.attrs.s_o_pn,
313
+ subjectOwnerUsername: group.attrs.s_o_username,
314
+ subjectTime: +group.attrs.s_t,
315
+ size: group.attrs.size ? +group.attrs.size : getBinaryNodeChildren(group, 'participant').length,
316
+ creation: +group.attrs.creation,
317
+ owner: group.attrs.creator ? jidNormalizedUser(group.attrs.creator) : undefined,
318
+ ownerPn: group.attrs.creator_pn ? jidNormalizedUser(group.attrs.creator_pn) : undefined,
319
+ ownerUsername: group.attrs.creator_username || undefined,
320
+ owner_country_code: group.attrs.creator_country_code,
321
+ desc,
322
+ descId,
323
+ descOwner,
324
+ descOwnerPn,
325
+ descOwnerUsername,
326
+ descTime,
327
+ linkedParent: getBinaryNodeChild(group, 'linked_parent')?.attrs.jid || undefined,
328
+ restrict: !!getBinaryNodeChild(group, 'locked'),
329
+ announce: !!getBinaryNodeChild(group, 'announcement'),
330
+ isCommunity: !!getBinaryNodeChild(group, 'parent'),
331
+ isCommunityAnnounce: !!getBinaryNodeChild(group, 'default_sub_group'),
332
+ joinApprovalMode: !!getBinaryNodeChild(group, 'membership_approval_mode'),
333
+ memberAddMode,
334
+ participants: getBinaryNodeChildren(group, 'participant').map(({ attrs }) => {
335
+ // TODO: Store LID MAPPINGS
336
+ return {
337
+ id: attrs.jid,
338
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
339
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
340
+ username: attrs.participant_username || attrs.username || undefined,
341
+ admin: (attrs.type || null)
342
+ };
343
+ }),
344
+ ephemeralDuration: eph ? +eph : undefined
345
+ };
346
+ return metadata;
347
+ };
@@ -1400,7 +1400,7 @@ export const makeMessagesSocket = (config) => {
1400
1400
  }
1401
1401
  return fullMsg;
1402
1402
  }
1403
- // crysnovax@LikeThis --- likeThis:true relays the message object exactly as-is,
1403
+ // crysnovax@LikeThis --- likeThis:true relays the message object exactly as-is,
1404
1404
  // bypassing generateWAMessage/generateWAMessageContent entirely.
1405
1405
  // No re-encoding, no normalization, no transformation — what you pass is what WA gets.
1406
1406
  //
@@ -1448,20 +1448,18 @@ export const makeMessagesSocket = (config) => {
1448
1448
  }
1449
1449
  return fullMsg;
1450
1450
  }
1451
- ...(httpRequestOptions || {})
1452
- },
1453
- logger,
1454
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1455
- }),
1456
- //TODO: CACHE
1457
- getProfilePicUrl: sock.profilePictureUrl,
1458
- getCallLink: sock.createCallLink,
1451
+ // ── NORMAL MESSAGE HANDLING ──
1452
+ else {
1453
+ const fullMsg = await generateWAMessage(jid, content, {
1454
+ logger,
1455
+ userJid,
1459
1456
  upload: waUploadToServer,
1460
1457
  mediaCache: config.mediaCache,
1461
1458
  options: config.options,
1462
1459
  ...options,
1463
1460
  messageId: generateMessageIDV2(userJid)
1464
1461
  });
1462
+
1465
1463
  const isNewsletter = isJidNewsletter(jid);
1466
1464
  const isEventMsg = 'event' in content && !!content.event;
1467
1465
  const isDeleteMsg = 'delete' in content && !!content.delete;
@@ -1474,9 +1472,8 @@ export const makeMessagesSocket = (config) => {
1474
1472
  const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1475
1473
  const additionalAttributes = options.additionalAttributes || {};
1476
1474
  const additionalNodes = options.additionalNodes || [];
1477
- // required for delete
1475
+
1478
1476
  if (isDeleteMsg || isKeepMsg) {
1479
- // if the chat is a group, and I am not the author, then delete the message as an admin
1480
1477
  if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1481
1478
  additionalAttributes.edit = '8';
1482
1479
  }
@@ -1497,7 +1494,6 @@ export const makeMessagesSocket = (config) => {
1497
1494
  additionalNodes.push({
1498
1495
  tag: 'meta',
1499
1496
  attrs: {
1500
- // Lia@Note 08-02-26 --- Still a hypothesis regarding PollResult ༎ຶ⁠‿⁠༎ຶ
1501
1497
  polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1502
1498
  contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1503
1499
  },
@@ -1513,7 +1509,6 @@ export const makeMessagesSocket = (config) => {
1513
1509
  content: undefined
1514
1510
  });
1515
1511
  }
1516
- // Lia@Changes 30-01-26 --- Add support for AI label in message when "ai" is true, but works only in private chat
1517
1512
  else if (isAiMsg) {
1518
1513
  if (!(isPnUser(jid) || isLidUser(jid))) {
1519
1514
  throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
@@ -1521,7 +1516,6 @@ export const makeMessagesSocket = (config) => {
1521
1516
  if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1522
1517
  fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1523
1518
  }
1524
- ;
1525
1519
  additionalNodes.push({
1526
1520
  tag: 'bot',
1527
1521
  attrs: {
@@ -1531,6 +1525,7 @@ export const makeMessagesSocket = (config) => {
1531
1525
  });
1532
1526
  delete content.ai;
1533
1527
  }
1528
+
1534
1529
  await relayMessage(jid, fullMsg.message, {
1535
1530
  messageId: fullMsg.key.id,
1536
1531
  useCachedGroupMetadata: options.useCachedGroupMetadata,
@@ -1539,13 +1534,14 @@ export const makeMessagesSocket = (config) => {
1539
1534
  additionalAttributes,
1540
1535
  additionalNodes
1541
1536
  });
1537
+
1542
1538
  if (config.emitOwnEvents) {
1543
1539
  process.nextTick(async () => {
1544
1540
  await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1545
1541
  });
1546
1542
  }
1547
- // Lia@Changes 31-01-26 --- Add support for album messages
1548
- // Lia@Note 06-02-26 --- Refactored to reduce high RSS usage (⁠╥⁠﹏⁠╥⁠)
1543
+
1544
+ // ── ALBUM MESSAGES ──
1549
1545
  if ('album' in content) {
1550
1546
  const { delayMs = 1500 } = options;
1551
1547
  for (const albumMedia of content.album) {
@@ -1582,8 +1578,9 @@ export const makeMessagesSocket = (config) => {
1582
1578
  await delay(delayMs);
1583
1579
  }
1584
1580
  }
1581
+
1585
1582
  return fullMsg;
1586
1583
  }
1587
1584
  }
1588
- };
1589
- };
1585
+ }
1586
+ };