@ruthless-imperium/baileys 1.0.2 → 1.0.3

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,437 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const __def = (m) => (m && m.__esModule) ? m.default : m;
4
+ const __exportStar = (m, e) => { for (const k in m) if (k !== "default" && !Object.prototype.hasOwnProperty.call(e, k)) e[k] = m[k]; };
5
+ const { proto } = require("../../WAProto/index.js");
6
+ const { WAMessageStubType } = require("../Types/index.js");
7
+ const { generateMessageID, generateMessageIDV2, unixTimestampSeconds } = require("../Utils/index.js");
8
+ const logger = __def(require("../Utils/logger.js"));
9
+ const { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, jidEncode, jidNormalizedUser } = require("../WABinary/index.js");
10
+ const { makeBusinessSocket } = require("./business.js");
11
+ const makeCommunitiesSocket = (config) => {
12
+ const sock = makeBusinessSocket(config);
13
+ const { authState, ev, query, upsertMessage } = sock;
14
+ const communityQuery = async (jid, type, content) => query({
15
+ tag: 'iq',
16
+ attrs: {
17
+ type,
18
+ xmlns: 'w:g2',
19
+ to: jid
20
+ },
21
+ content
22
+ });
23
+ const communityMetadata = async (jid) => {
24
+ const result = await communityQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
25
+ return extractCommunityMetadata(result);
26
+ };
27
+ const communityFetchAllParticipating = async () => {
28
+ const result = await query({
29
+ tag: 'iq',
30
+ attrs: {
31
+ to: '@g.us',
32
+ xmlns: 'w:g2',
33
+ type: 'get'
34
+ },
35
+ content: [
36
+ {
37
+ tag: 'participating',
38
+ attrs: {},
39
+ content: [
40
+ { tag: 'participants', attrs: {} },
41
+ { tag: 'description', attrs: {} }
42
+ ]
43
+ }
44
+ ]
45
+ });
46
+ const data = {};
47
+ const communitiesChild = getBinaryNodeChild(result, 'communities');
48
+ if (communitiesChild) {
49
+ const communities = getBinaryNodeChildren(communitiesChild, 'community');
50
+ for (const communityNode of communities) {
51
+ const meta = extractCommunityMetadata({
52
+ tag: 'result',
53
+ attrs: {},
54
+ content: [communityNode]
55
+ });
56
+ data[meta.id] = meta;
57
+ }
58
+ }
59
+ sock.ev.emit('groups.update', Object.values(data));
60
+ return data;
61
+ };
62
+ async function parseGroupResult(node) {
63
+ logger.info({ node }, 'parseGroupResult');
64
+ const groupNode = getBinaryNodeChild(node, 'group');
65
+ if (groupNode) {
66
+ try {
67
+ logger.info({ groupNode }, 'groupNode');
68
+ const metadata = await sock.groupMetadata(`${groupNode.attrs.id}@g.us`);
69
+ return metadata ? metadata : Optional.empty();
70
+ }
71
+ catch (error) {
72
+ console.error('Error parsing group metadata:', error);
73
+ return Optional.empty();
74
+ }
75
+ }
76
+ return Optional.empty();
77
+ }
78
+ const Optional = {
79
+ empty: () => null,
80
+ of: (value) => (value !== null ? { value } : null)
81
+ };
82
+ sock.ws.on('CB:ib,,dirty', async (node) => {
83
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
84
+ if (attrs.type !== 'communities') {
85
+ return;
86
+ }
87
+ await communityFetchAllParticipating();
88
+ await sock.cleanDirtyBits('groups');
89
+ });
90
+ return {
91
+ ...sock,
92
+ communityMetadata,
93
+ communityCreate: async (subject, body) => {
94
+ const descriptionId = generateMessageID().substring(0, 12);
95
+ const result = await communityQuery('@g.us', 'set', [
96
+ {
97
+ tag: 'create',
98
+ attrs: { subject },
99
+ content: [
100
+ {
101
+ tag: 'description',
102
+ attrs: { id: descriptionId },
103
+ content: [
104
+ {
105
+ tag: 'body',
106
+ attrs: {},
107
+ content: Buffer.from(body || '', 'utf-8')
108
+ }
109
+ ]
110
+ },
111
+ {
112
+ tag: 'parent',
113
+ attrs: { default_membership_approval_mode: 'request_required' }
114
+ },
115
+ {
116
+ tag: 'allow_non_admin_sub_group_creation',
117
+ attrs: {}
118
+ },
119
+ {
120
+ tag: 'create_general_chat',
121
+ attrs: {}
122
+ }
123
+ ]
124
+ }
125
+ ]);
126
+ return await parseGroupResult(result);
127
+ },
128
+ communityCreateGroup: async (subject, participants, parentCommunityJid) => {
129
+ const key = generateMessageIDV2();
130
+ const result = await communityQuery('@g.us', 'set', [
131
+ {
132
+ tag: 'create',
133
+ attrs: {
134
+ subject,
135
+ key
136
+ },
137
+ content: [
138
+ ...participants.map(jid => ({
139
+ tag: 'participant',
140
+ attrs: { jid }
141
+ })),
142
+ { tag: 'linked_parent', attrs: { jid: parentCommunityJid } }
143
+ ]
144
+ }
145
+ ]);
146
+ return await parseGroupResult(result);
147
+ },
148
+ communityLeave: async (id) => {
149
+ await communityQuery('@g.us', 'set', [
150
+ {
151
+ tag: 'leave',
152
+ attrs: {},
153
+ content: [{ tag: 'community', attrs: { id } }]
154
+ }
155
+ ]);
156
+ },
157
+ communityUpdateSubject: async (jid, subject) => {
158
+ await communityQuery(jid, 'set', [
159
+ {
160
+ tag: 'subject',
161
+ attrs: {},
162
+ content: Buffer.from(subject, 'utf-8')
163
+ }
164
+ ]);
165
+ },
166
+ communityLinkGroup: async (groupJid, parentCommunityJid) => {
167
+ await communityQuery(parentCommunityJid, 'set', [
168
+ {
169
+ tag: 'links',
170
+ attrs: {},
171
+ content: [
172
+ {
173
+ tag: 'link',
174
+ attrs: { link_type: 'sub_group' },
175
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
176
+ }
177
+ ]
178
+ }
179
+ ]);
180
+ },
181
+ communityUnlinkGroup: async (groupJid, parentCommunityJid) => {
182
+ await communityQuery(parentCommunityJid, 'set', [
183
+ {
184
+ tag: 'unlink',
185
+ attrs: { unlink_type: 'sub_group' },
186
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
187
+ }
188
+ ]);
189
+ },
190
+ communityFetchLinkedGroups: async (jid) => {
191
+ let communityJid = jid;
192
+ let isCommunity = false;
193
+ // Try to determine if it is a subgroup or a community
194
+ const metadata = await sock.groupMetadata(jid);
195
+ if (metadata.linkedParent) {
196
+ // It is a subgroup, get the community jid
197
+ communityJid = metadata.linkedParent;
198
+ }
199
+ else {
200
+ // It is a community
201
+ isCommunity = true;
202
+ }
203
+ // Fetch all subgroups of the community
204
+ const result = await communityQuery(communityJid, 'get', [{ tag: 'sub_groups', attrs: {} }]);
205
+ const linkedGroupsData = [];
206
+ const subGroupsNode = getBinaryNodeChild(result, 'sub_groups');
207
+ if (subGroupsNode) {
208
+ const groupNodes = getBinaryNodeChildren(subGroupsNode, 'group');
209
+ for (const groupNode of groupNodes) {
210
+ linkedGroupsData.push({
211
+ id: groupNode.attrs.id ? jidEncode(groupNode.attrs.id, 'g.us') : undefined,
212
+ subject: groupNode.attrs.subject || '',
213
+ creation: groupNode.attrs.creation ? Number(groupNode.attrs.creation) : undefined,
214
+ owner: groupNode.attrs.creator ? jidNormalizedUser(groupNode.attrs.creator) : undefined,
215
+ size: groupNode.attrs.size ? Number(groupNode.attrs.size) : undefined
216
+ });
217
+ }
218
+ }
219
+ return {
220
+ communityJid,
221
+ isCommunity,
222
+ linkedGroups: linkedGroupsData
223
+ };
224
+ },
225
+ communityRequestParticipantsList: async (jid) => {
226
+ const result = await communityQuery(jid, 'get', [
227
+ {
228
+ tag: 'membership_approval_requests',
229
+ attrs: {}
230
+ }
231
+ ]);
232
+ const node = getBinaryNodeChild(result, 'membership_approval_requests');
233
+ const participants = getBinaryNodeChildren(node, 'membership_approval_request');
234
+ return participants.map(v => v.attrs);
235
+ },
236
+ communityRequestParticipantsUpdate: async (jid, participants, action) => {
237
+ const result = await communityQuery(jid, 'set', [
238
+ {
239
+ tag: 'membership_requests_action',
240
+ attrs: {},
241
+ content: [
242
+ {
243
+ tag: action,
244
+ attrs: {},
245
+ content: participants.map(jid => ({
246
+ tag: 'participant',
247
+ attrs: { jid }
248
+ }))
249
+ }
250
+ ]
251
+ }
252
+ ]);
253
+ const node = getBinaryNodeChild(result, 'membership_requests_action');
254
+ const nodeAction = getBinaryNodeChild(node, action);
255
+ const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant');
256
+ return participantsAffected.map(p => {
257
+ return { status: p.attrs.error || '200', jid: p.attrs.jid };
258
+ });
259
+ },
260
+ communityParticipantsUpdate: async (jid, participants, action) => {
261
+ const result = await communityQuery(jid, 'set', [
262
+ {
263
+ tag: action,
264
+ attrs: action === 'remove' ? { linked_groups: 'true' } : {},
265
+ content: participants.map(jid => ({
266
+ tag: 'participant',
267
+ attrs: { jid }
268
+ }))
269
+ }
270
+ ]);
271
+ const node = getBinaryNodeChild(result, action);
272
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
273
+ return participantsAffected.map(p => {
274
+ return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p };
275
+ });
276
+ },
277
+ communityUpdateDescription: async (jid, description) => {
278
+ const metadata = await communityMetadata(jid);
279
+ const prev = metadata.descId ?? null;
280
+ await communityQuery(jid, 'set', [
281
+ {
282
+ tag: 'description',
283
+ attrs: {
284
+ ...(description ? { id: generateMessageID() } : { delete: 'true' }),
285
+ ...(prev ? { prev } : {})
286
+ },
287
+ content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
288
+ }
289
+ ]);
290
+ },
291
+ communityInviteCode: async (jid) => {
292
+ const result = await communityQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
293
+ const inviteNode = getBinaryNodeChild(result, 'invite');
294
+ return inviteNode?.attrs.code;
295
+ },
296
+ communityRevokeInvite: async (jid) => {
297
+ const result = await communityQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
298
+ const inviteNode = getBinaryNodeChild(result, 'invite');
299
+ return inviteNode?.attrs.code;
300
+ },
301
+ communityAcceptInvite: async (code) => {
302
+ const results = await communityQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
303
+ const result = getBinaryNodeChild(results, 'community');
304
+ return result?.attrs.jid;
305
+ },
306
+ /**
307
+ * revoke a v4 invite for someone
308
+ * @param communityJid community jid
309
+ * @param invitedJid jid of person you invited
310
+ * @returns true if successful
311
+ */
312
+ communityRevokeInviteV4: async (communityJid, invitedJid) => {
313
+ const result = await communityQuery(communityJid, 'set', [
314
+ { tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
315
+ ]);
316
+ return !!result;
317
+ },
318
+ /**
319
+ * accept a CommunityInviteMessage
320
+ * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
321
+ * @param inviteMessage the message to accept
322
+ */
323
+ communityAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
324
+ key = typeof key === 'string' ? { remoteJid: key } : key;
325
+ const results = await communityQuery(inviteMessage.groupJid, 'set', [
326
+ {
327
+ tag: 'accept',
328
+ attrs: {
329
+ code: inviteMessage.inviteCode,
330
+ expiration: inviteMessage.inviteExpiration.toString(),
331
+ admin: key.remoteJid
332
+ }
333
+ }
334
+ ]);
335
+ // if we have the full message key
336
+ // update the invite message to be expired
337
+ if (key.id) {
338
+ // create new invite message that is expired
339
+ inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage);
340
+ inviteMessage.inviteExpiration = 0;
341
+ inviteMessage.inviteCode = '';
342
+ ev.emit('messages.update', [
343
+ {
344
+ key,
345
+ update: {
346
+ message: {
347
+ groupInviteMessage: inviteMessage
348
+ }
349
+ }
350
+ }
351
+ ]);
352
+ }
353
+ // generate the community add message
354
+ await upsertMessage({
355
+ key: {
356
+ remoteJid: inviteMessage.groupJid,
357
+ id: generateMessageIDV2(sock.user?.id),
358
+ fromMe: false,
359
+ participant: key.remoteJid // TODO: investigate if this makes any sense at all
360
+ },
361
+ messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
362
+ messageStubParameters: [JSON.stringify(authState.creds.me)],
363
+ participant: key.remoteJid,
364
+ messageTimestamp: unixTimestampSeconds()
365
+ }, 'notify');
366
+ return results.attrs.from;
367
+ }),
368
+ communityGetInviteInfo: async (code) => {
369
+ const results = await communityQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }]);
370
+ return extractCommunityMetadata(results);
371
+ },
372
+ communityToggleEphemeral: async (jid, ephemeralExpiration) => {
373
+ const content = ephemeralExpiration
374
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
375
+ : { tag: 'not_ephemeral', attrs: {} };
376
+ await communityQuery(jid, 'set', [content]);
377
+ },
378
+ communitySettingUpdate: async (jid, setting) => {
379
+ await communityQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
380
+ },
381
+ communityMemberAddMode: async (jid, mode) => {
382
+ await communityQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }]);
383
+ },
384
+ communityJoinApprovalMode: async (jid, mode) => {
385
+ await communityQuery(jid, 'set', [
386
+ { tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'community_join', attrs: { state: mode } }] }
387
+ ]);
388
+ },
389
+ communityFetchAllParticipating
390
+ };
391
+ };
392
+ const extractCommunityMetadata = (result) => {
393
+ const community = getBinaryNodeChild(result, 'community');
394
+ const descChild = getBinaryNodeChild(community, 'description');
395
+ let desc;
396
+ let descId;
397
+ if (descChild) {
398
+ desc = getBinaryNodeChildString(descChild, 'body');
399
+ descId = descChild.attrs.id;
400
+ }
401
+ const communityId = community.attrs.id?.includes('@')
402
+ ? community.attrs.id
403
+ : jidEncode(community.attrs.id || '', 'g.us');
404
+ const eph = getBinaryNodeChild(community, 'ephemeral')?.attrs.expiration;
405
+ const memberAddMode = getBinaryNodeChildString(community, 'member_add_mode') === 'all_member_add';
406
+ const metadata = {
407
+ id: communityId,
408
+ subject: community.attrs.subject || '',
409
+ subjectOwner: community.attrs.s_o,
410
+ subjectTime: Number(community.attrs.s_t || 0),
411
+ size: getBinaryNodeChildren(community, 'participant').length,
412
+ creation: Number(community.attrs.creation || 0),
413
+ owner: community.attrs.creator ? jidNormalizedUser(community.attrs.creator) : undefined,
414
+ desc,
415
+ descId,
416
+ linkedParent: getBinaryNodeChild(community, 'linked_parent')?.attrs.jid || undefined,
417
+ restrict: !!getBinaryNodeChild(community, 'locked'),
418
+ announce: !!getBinaryNodeChild(community, 'announcement'),
419
+ isCommunity: !!getBinaryNodeChild(community, 'parent'),
420
+ isCommunityAnnounce: !!getBinaryNodeChild(community, 'default_sub_community'),
421
+ joinApprovalMode: !!getBinaryNodeChild(community, 'membership_approval_mode'),
422
+ memberAddMode,
423
+ participants: getBinaryNodeChildren(community, 'participant').map(({ attrs }) => {
424
+ return {
425
+ // TODO: IMPLEMENT THE PN/LID FIELDS HERE!!
426
+ id: attrs.jid,
427
+ admin: (attrs.type || null)
428
+ };
429
+ }),
430
+ ephemeralDuration: eph ? +eph : undefined,
431
+ addressingMode: getBinaryNodeChildString(community, 'addressing_mode')
432
+ };
433
+ return metadata;
434
+ };
435
+
436
+ exports.makeCommunitiesSocket = makeCommunitiesSocket;
437
+ exports.extractCommunityMetadata = extractCommunityMetadata;