@hiroosy/baileys-lite 0.0.1

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.
Files changed (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,830 @@
1
+ /**
2
+ * Business + Communities socket layers (the outermost wrappers).
3
+ * Combines Socket/business.js and Socket/communities.js:
4
+ *
5
+ * makeMessagesRecvSocket -> makeBusinessSocket -> makeCommunitiesSocket
6
+ *
7
+ * makeCommunitiesSocket is what index.js exports as makeWASocket.
8
+ * (Catalog parse helpers such as parseCatalogNode live in utils/message-processing.js.)
9
+ */
10
+ import { proto } from '../../WAProto/index.js'
11
+ import logger from '../foundation/logger.js'
12
+ import { WAMessageStubType } from '../constants.js'
13
+ import { generateMessageID, generateMessageIDV2, unixTimestampSeconds } from '../utils/wa-protocol-core.js'
14
+ import { getRawMediaUploadData } from '../utils/media.js'
15
+ import {
16
+ parseCatalogNode,
17
+ parseCollectionsNode,
18
+ parseOrderDetailsNode,
19
+ parseProductNode,
20
+ toProductNode,
21
+ uploadingNecessaryImagesOfProduct
22
+ } from '../utils/message-processing.js'
23
+ import {
24
+ getBinaryNodeChild,
25
+ getBinaryNodeChildren,
26
+ getBinaryNodeChildString,
27
+ jidEncode,
28
+ jidNormalizedUser,
29
+ S_WHATSAPP_NET
30
+ } from '../binary/wa-binary.js'
31
+ import { makeMessagesRecvSocket } from './messages-recv.js'
32
+
33
+ export const makeBusinessSocket = (config) => {
34
+ const sock = makeMessagesRecvSocket(config);
35
+ const { authState, query, waUploadToServer } = sock;
36
+ const updateBussinesProfile = async (args) => {
37
+ const node = [];
38
+ const simpleFields = ['address', 'email', 'description'];
39
+ node.push(...simpleFields
40
+ .filter(key => args[key] !== undefined && args[key] !== null)
41
+ .map(key => ({
42
+ tag: key,
43
+ attrs: {},
44
+ content: args[key]
45
+ })));
46
+ if (args.websites !== undefined) {
47
+ node.push(...args.websites.map(website => ({
48
+ tag: 'website',
49
+ attrs: {},
50
+ content: website
51
+ })));
52
+ }
53
+ if (args.hours !== undefined) {
54
+ node.push({
55
+ tag: 'business_hours',
56
+ attrs: { timezone: args.hours.timezone },
57
+ content: args.hours.days.map(dayConfig => {
58
+ const base = {
59
+ tag: 'business_hours_config',
60
+ attrs: {
61
+ day_of_week: dayConfig.day,
62
+ mode: dayConfig.mode
63
+ }
64
+ };
65
+ if (dayConfig.mode === 'specific_hours') {
66
+ return {
67
+ ...base,
68
+ attrs: {
69
+ ...base.attrs,
70
+ open_time: dayConfig.openTimeInMinutes,
71
+ close_time: dayConfig.closeTimeInMinutes
72
+ }
73
+ };
74
+ }
75
+ return base;
76
+ })
77
+ });
78
+ }
79
+ const result = await query({
80
+ tag: 'iq',
81
+ attrs: {
82
+ to: S_WHATSAPP_NET,
83
+ type: 'set',
84
+ xmlns: 'w:biz'
85
+ },
86
+ content: [
87
+ {
88
+ tag: 'business_profile',
89
+ attrs: {
90
+ v: '3',
91
+ mutation_type: 'delta'
92
+ },
93
+ content: node
94
+ }
95
+ ]
96
+ });
97
+ return result;
98
+ };
99
+ const updateCoverPhoto = async (photo) => {
100
+ const { fileSha256, filePath } = await getRawMediaUploadData(photo, 'biz-cover-photo');
101
+ const fileSha256B64 = fileSha256.toString('base64');
102
+ const { meta_hmac, fbid, ts } = await waUploadToServer(filePath, {
103
+ fileEncSha256B64: fileSha256B64,
104
+ mediaType: 'biz-cover-photo'
105
+ });
106
+ await query({
107
+ tag: 'iq',
108
+ attrs: {
109
+ to: S_WHATSAPP_NET,
110
+ type: 'set',
111
+ xmlns: 'w:biz'
112
+ },
113
+ content: [
114
+ {
115
+ tag: 'business_profile',
116
+ attrs: {
117
+ v: '3',
118
+ mutation_type: 'delta'
119
+ },
120
+ content: [
121
+ {
122
+ tag: 'cover_photo',
123
+ attrs: { id: String(fbid), op: 'update', token: meta_hmac, ts: String(ts) }
124
+ }
125
+ ]
126
+ }
127
+ ]
128
+ });
129
+ return fbid;
130
+ };
131
+ const removeCoverPhoto = async (id) => {
132
+ return await query({
133
+ tag: 'iq',
134
+ attrs: {
135
+ to: S_WHATSAPP_NET,
136
+ type: 'set',
137
+ xmlns: 'w:biz'
138
+ },
139
+ content: [
140
+ {
141
+ tag: 'business_profile',
142
+ attrs: {
143
+ v: '3',
144
+ mutation_type: 'delta'
145
+ },
146
+ content: [
147
+ {
148
+ tag: 'cover_photo',
149
+ attrs: { op: 'delete', id }
150
+ }
151
+ ]
152
+ }
153
+ ]
154
+ });
155
+ };
156
+ const getCatalog = async ({ jid, limit, cursor }) => {
157
+ jid = jid || authState.creds.me?.id;
158
+ jid = jidNormalizedUser(jid);
159
+ const queryParamNodes = [
160
+ {
161
+ tag: 'limit',
162
+ attrs: {},
163
+ content: Buffer.from((limit || 10).toString())
164
+ },
165
+ {
166
+ tag: 'width',
167
+ attrs: {},
168
+ content: Buffer.from('100')
169
+ },
170
+ {
171
+ tag: 'height',
172
+ attrs: {},
173
+ content: Buffer.from('100')
174
+ }
175
+ ];
176
+ if (cursor) {
177
+ queryParamNodes.push({
178
+ tag: 'after',
179
+ attrs: {},
180
+ content: cursor
181
+ });
182
+ }
183
+ const result = await query({
184
+ tag: 'iq',
185
+ attrs: {
186
+ to: S_WHATSAPP_NET,
187
+ type: 'get',
188
+ xmlns: 'w:biz:catalog'
189
+ },
190
+ content: [
191
+ {
192
+ tag: 'product_catalog',
193
+ attrs: {
194
+ jid,
195
+ allow_shop_source: 'true'
196
+ },
197
+ content: queryParamNodes
198
+ }
199
+ ]
200
+ });
201
+ return parseCatalogNode(result);
202
+ };
203
+ const getCollections = async (jid, limit = 51) => {
204
+ jid = jid || authState.creds.me?.id;
205
+ jid = jidNormalizedUser(jid);
206
+ const result = await query({
207
+ tag: 'iq',
208
+ attrs: {
209
+ to: S_WHATSAPP_NET,
210
+ type: 'get',
211
+ xmlns: 'w:biz:catalog',
212
+ smax_id: '35'
213
+ },
214
+ content: [
215
+ {
216
+ tag: 'collections',
217
+ attrs: {
218
+ biz_jid: jid
219
+ },
220
+ content: [
221
+ {
222
+ tag: 'collection_limit',
223
+ attrs: {},
224
+ content: Buffer.from(limit.toString())
225
+ },
226
+ {
227
+ tag: 'item_limit',
228
+ attrs: {},
229
+ content: Buffer.from(limit.toString())
230
+ },
231
+ {
232
+ tag: 'width',
233
+ attrs: {},
234
+ content: Buffer.from('100')
235
+ },
236
+ {
237
+ tag: 'height',
238
+ attrs: {},
239
+ content: Buffer.from('100')
240
+ }
241
+ ]
242
+ }
243
+ ]
244
+ });
245
+ return parseCollectionsNode(result);
246
+ };
247
+ const getOrderDetails = async (orderId, tokenBase64) => {
248
+ const result = await query({
249
+ tag: 'iq',
250
+ attrs: {
251
+ to: S_WHATSAPP_NET,
252
+ type: 'get',
253
+ xmlns: 'fb:thrift_iq',
254
+ smax_id: '5'
255
+ },
256
+ content: [
257
+ {
258
+ tag: 'order',
259
+ attrs: {
260
+ op: 'get',
261
+ id: orderId
262
+ },
263
+ content: [
264
+ {
265
+ tag: 'image_dimensions',
266
+ attrs: {},
267
+ content: [
268
+ {
269
+ tag: 'width',
270
+ attrs: {},
271
+ content: Buffer.from('100')
272
+ },
273
+ {
274
+ tag: 'height',
275
+ attrs: {},
276
+ content: Buffer.from('100')
277
+ }
278
+ ]
279
+ },
280
+ {
281
+ tag: 'token',
282
+ attrs: {},
283
+ content: Buffer.from(tokenBase64)
284
+ }
285
+ ]
286
+ }
287
+ ]
288
+ });
289
+ return parseOrderDetailsNode(result);
290
+ };
291
+ const productUpdate = async (productId, update) => {
292
+ update = await uploadingNecessaryImagesOfProduct(update, waUploadToServer);
293
+ const editNode = toProductNode(productId, update);
294
+ const result = await query({
295
+ tag: 'iq',
296
+ attrs: {
297
+ to: S_WHATSAPP_NET,
298
+ type: 'set',
299
+ xmlns: 'w:biz:catalog'
300
+ },
301
+ content: [
302
+ {
303
+ tag: 'product_catalog_edit',
304
+ attrs: { v: '1' },
305
+ content: [
306
+ editNode,
307
+ {
308
+ tag: 'width',
309
+ attrs: {},
310
+ content: '100'
311
+ },
312
+ {
313
+ tag: 'height',
314
+ attrs: {},
315
+ content: '100'
316
+ }
317
+ ]
318
+ }
319
+ ]
320
+ });
321
+ const productCatalogEditNode = getBinaryNodeChild(result, 'product_catalog_edit');
322
+ const productNode = getBinaryNodeChild(productCatalogEditNode, 'product');
323
+ return parseProductNode(productNode);
324
+ };
325
+ const productCreate = async (create) => {
326
+ // ensure isHidden is defined
327
+ create.isHidden = !!create.isHidden;
328
+ create = await uploadingNecessaryImagesOfProduct(create, waUploadToServer);
329
+ const createNode = toProductNode(undefined, create);
330
+ const result = await query({
331
+ tag: 'iq',
332
+ attrs: {
333
+ to: S_WHATSAPP_NET,
334
+ type: 'set',
335
+ xmlns: 'w:biz:catalog'
336
+ },
337
+ content: [
338
+ {
339
+ tag: 'product_catalog_add',
340
+ attrs: { v: '1' },
341
+ content: [
342
+ createNode,
343
+ {
344
+ tag: 'width',
345
+ attrs: {},
346
+ content: '100'
347
+ },
348
+ {
349
+ tag: 'height',
350
+ attrs: {},
351
+ content: '100'
352
+ }
353
+ ]
354
+ }
355
+ ]
356
+ });
357
+ const productCatalogAddNode = getBinaryNodeChild(result, 'product_catalog_add');
358
+ const productNode = getBinaryNodeChild(productCatalogAddNode, 'product');
359
+ return parseProductNode(productNode);
360
+ };
361
+ const productDelete = async (productIds) => {
362
+ const result = await query({
363
+ tag: 'iq',
364
+ attrs: {
365
+ to: S_WHATSAPP_NET,
366
+ type: 'set',
367
+ xmlns: 'w:biz:catalog'
368
+ },
369
+ content: [
370
+ {
371
+ tag: 'product_catalog_delete',
372
+ attrs: { v: '1' },
373
+ content: productIds.map(id => ({
374
+ tag: 'product',
375
+ attrs: {},
376
+ content: [
377
+ {
378
+ tag: 'id',
379
+ attrs: {},
380
+ content: Buffer.from(id)
381
+ }
382
+ ]
383
+ }))
384
+ }
385
+ ]
386
+ });
387
+ const productCatalogDelNode = getBinaryNodeChild(result, 'product_catalog_delete');
388
+ return {
389
+ deleted: +(productCatalogDelNode?.attrs.deleted_count || 0)
390
+ };
391
+ };
392
+ return {
393
+ ...sock,
394
+ logger: config.logger,
395
+ getOrderDetails,
396
+ getCatalog,
397
+ getCollections,
398
+ productCreate,
399
+ productDelete,
400
+ productUpdate,
401
+ updateBussinesProfile,
402
+ updateCoverPhoto,
403
+ removeCoverPhoto
404
+ };
405
+ };
406
+
407
+ export const makeCommunitiesSocket = (config) => {
408
+ const sock = makeBusinessSocket(config);
409
+ const { authState, ev, query, upsertMessage } = sock;
410
+ const communityQuery = async (jid, type, content) => query({
411
+ tag: 'iq',
412
+ attrs: {
413
+ type,
414
+ xmlns: 'w:g2',
415
+ to: jid
416
+ },
417
+ content
418
+ });
419
+ const communityMetadata = async (jid) => {
420
+ const result = await communityQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
421
+ return extractCommunityMetadata(result);
422
+ };
423
+ const communityFetchAllParticipating = async () => {
424
+ const result = await query({
425
+ tag: 'iq',
426
+ attrs: {
427
+ to: '@g.us',
428
+ xmlns: 'w:g2',
429
+ type: 'get'
430
+ },
431
+ content: [
432
+ {
433
+ tag: 'participating',
434
+ attrs: {},
435
+ content: [
436
+ { tag: 'participants', attrs: {} },
437
+ { tag: 'description', attrs: {} }
438
+ ]
439
+ }
440
+ ]
441
+ });
442
+ const data = {};
443
+ const communitiesChild = getBinaryNodeChild(result, 'communities');
444
+ if (communitiesChild) {
445
+ const communities = getBinaryNodeChildren(communitiesChild, 'community');
446
+ for (const communityNode of communities) {
447
+ const meta = extractCommunityMetadata({
448
+ tag: 'result',
449
+ attrs: {},
450
+ content: [communityNode]
451
+ });
452
+ data[meta.id] = meta;
453
+ }
454
+ }
455
+ sock.ev.emit('groups.update', Object.values(data));
456
+ return data;
457
+ };
458
+ async function parseGroupResult(node) {
459
+ logger.info({ node }, 'parseGroupResult');
460
+ const groupNode = getBinaryNodeChild(node, 'group');
461
+ if (groupNode) {
462
+ try {
463
+ logger.info({ groupNode }, 'groupNode');
464
+ const metadata = await sock.groupMetadata(`${groupNode.attrs.id}@g.us`);
465
+ return metadata ? metadata : Optional.empty();
466
+ }
467
+ catch (error) {
468
+ console.error('Error parsing group metadata:', error);
469
+ return Optional.empty();
470
+ }
471
+ }
472
+ return Optional.empty();
473
+ }
474
+ const Optional = {
475
+ empty: () => null,
476
+ of: (value) => (value !== null ? { value } : null)
477
+ };
478
+ sock.ws.on('CB:ib,,dirty', async (node) => {
479
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
480
+ if (attrs.type !== 'communities') {
481
+ return;
482
+ }
483
+ await communityFetchAllParticipating();
484
+ await sock.cleanDirtyBits('groups');
485
+ });
486
+ return {
487
+ ...sock,
488
+ communityMetadata,
489
+ communityCreate: async (subject, body) => {
490
+ const descriptionId = generateMessageID().substring(0, 12);
491
+ const result = await communityQuery('@g.us', 'set', [
492
+ {
493
+ tag: 'create',
494
+ attrs: { subject },
495
+ content: [
496
+ {
497
+ tag: 'description',
498
+ attrs: { id: descriptionId },
499
+ content: [
500
+ {
501
+ tag: 'body',
502
+ attrs: {},
503
+ content: Buffer.from(body || '', 'utf-8')
504
+ }
505
+ ]
506
+ },
507
+ {
508
+ tag: 'parent',
509
+ attrs: { default_membership_approval_mode: 'request_required' }
510
+ },
511
+ {
512
+ tag: 'allow_non_admin_sub_group_creation',
513
+ attrs: {}
514
+ },
515
+ {
516
+ tag: 'create_general_chat',
517
+ attrs: {}
518
+ }
519
+ ]
520
+ }
521
+ ]);
522
+ return await parseGroupResult(result);
523
+ },
524
+ communityCreateGroup: async (subject, participants, parentCommunityJid) => {
525
+ const key = generateMessageIDV2();
526
+ const result = await communityQuery('@g.us', 'set', [
527
+ {
528
+ tag: 'create',
529
+ attrs: {
530
+ subject,
531
+ key
532
+ },
533
+ content: [
534
+ ...participants.map(jid => ({
535
+ tag: 'participant',
536
+ attrs: { jid }
537
+ })),
538
+ { tag: 'linked_parent', attrs: { jid: parentCommunityJid } }
539
+ ]
540
+ }
541
+ ]);
542
+ return await parseGroupResult(result);
543
+ },
544
+ communityLeave: async (id) => {
545
+ await communityQuery('@g.us', 'set', [
546
+ {
547
+ tag: 'leave',
548
+ attrs: {},
549
+ content: [{ tag: 'community', attrs: { id } }]
550
+ }
551
+ ]);
552
+ },
553
+ communityUpdateSubject: async (jid, subject) => {
554
+ await communityQuery(jid, 'set', [
555
+ {
556
+ tag: 'subject',
557
+ attrs: {},
558
+ content: Buffer.from(subject, 'utf-8')
559
+ }
560
+ ]);
561
+ },
562
+ communityLinkGroup: async (groupJid, parentCommunityJid) => {
563
+ await communityQuery(parentCommunityJid, 'set', [
564
+ {
565
+ tag: 'links',
566
+ attrs: {},
567
+ content: [
568
+ {
569
+ tag: 'link',
570
+ attrs: { link_type: 'sub_group' },
571
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
572
+ }
573
+ ]
574
+ }
575
+ ]);
576
+ },
577
+ communityUnlinkGroup: async (groupJid, parentCommunityJid) => {
578
+ await communityQuery(parentCommunityJid, 'set', [
579
+ {
580
+ tag: 'unlink',
581
+ attrs: { unlink_type: 'sub_group' },
582
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
583
+ }
584
+ ]);
585
+ },
586
+ communityFetchLinkedGroups: async (jid) => {
587
+ let communityJid = jid;
588
+ let isCommunity = false;
589
+ // Try to determine if it is a subgroup or a community
590
+ const metadata = await sock.groupMetadata(jid);
591
+ if (metadata.linkedParent) {
592
+ // It is a subgroup, get the community jid
593
+ communityJid = metadata.linkedParent;
594
+ }
595
+ else {
596
+ // It is a community
597
+ isCommunity = true;
598
+ }
599
+ // Fetch all subgroups of the community
600
+ const result = await communityQuery(communityJid, 'get', [{ tag: 'sub_groups', attrs: {} }]);
601
+ const linkedGroupsData = [];
602
+ const subGroupsNode = getBinaryNodeChild(result, 'sub_groups');
603
+ if (subGroupsNode) {
604
+ const groupNodes = getBinaryNodeChildren(subGroupsNode, 'group');
605
+ for (const groupNode of groupNodes) {
606
+ linkedGroupsData.push({
607
+ id: groupNode.attrs.id ? jidEncode(groupNode.attrs.id, 'g.us') : undefined,
608
+ subject: groupNode.attrs.subject || '',
609
+ creation: groupNode.attrs.creation ? Number(groupNode.attrs.creation) : undefined,
610
+ owner: groupNode.attrs.creator ? jidNormalizedUser(groupNode.attrs.creator) : undefined,
611
+ size: groupNode.attrs.size ? Number(groupNode.attrs.size) : undefined
612
+ });
613
+ }
614
+ }
615
+ return {
616
+ communityJid,
617
+ isCommunity,
618
+ linkedGroups: linkedGroupsData
619
+ };
620
+ },
621
+ communityRequestParticipantsList: async (jid) => {
622
+ const result = await communityQuery(jid, 'get', [
623
+ {
624
+ tag: 'membership_approval_requests',
625
+ attrs: {}
626
+ }
627
+ ]);
628
+ const node = getBinaryNodeChild(result, 'membership_approval_requests');
629
+ const participants = getBinaryNodeChildren(node, 'membership_approval_request');
630
+ return participants.map(v => v.attrs);
631
+ },
632
+ communityRequestParticipantsUpdate: async (jid, participants, action) => {
633
+ const result = await communityQuery(jid, 'set', [
634
+ {
635
+ tag: 'membership_requests_action',
636
+ attrs: {},
637
+ content: [
638
+ {
639
+ tag: action,
640
+ attrs: {},
641
+ content: participants.map(jid => ({
642
+ tag: 'participant',
643
+ attrs: { jid }
644
+ }))
645
+ }
646
+ ]
647
+ }
648
+ ]);
649
+ const node = getBinaryNodeChild(result, 'membership_requests_action');
650
+ const nodeAction = getBinaryNodeChild(node, action);
651
+ const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant');
652
+ return participantsAffected.map(p => {
653
+ return { status: p.attrs.error || '200', jid: p.attrs.jid };
654
+ });
655
+ },
656
+ communityParticipantsUpdate: async (jid, participants, action) => {
657
+ const result = await communityQuery(jid, 'set', [
658
+ {
659
+ tag: action,
660
+ attrs: action === 'remove' ? { linked_groups: 'true' } : {},
661
+ content: participants.map(jid => ({
662
+ tag: 'participant',
663
+ attrs: { jid }
664
+ }))
665
+ }
666
+ ]);
667
+ const node = getBinaryNodeChild(result, action);
668
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
669
+ return participantsAffected.map(p => {
670
+ return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p };
671
+ });
672
+ },
673
+ communityUpdateDescription: async (jid, description) => {
674
+ const metadata = await communityMetadata(jid);
675
+ const prev = metadata.descId ?? null;
676
+ await communityQuery(jid, 'set', [
677
+ {
678
+ tag: 'description',
679
+ attrs: {
680
+ ...(description ? { id: generateMessageID() } : { delete: 'true' }),
681
+ ...(prev ? { prev } : {})
682
+ },
683
+ content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
684
+ }
685
+ ]);
686
+ },
687
+ communityInviteCode: async (jid) => {
688
+ const result = await communityQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
689
+ const inviteNode = getBinaryNodeChild(result, 'invite');
690
+ return inviteNode?.attrs.code;
691
+ },
692
+ communityRevokeInvite: async (jid) => {
693
+ const result = await communityQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
694
+ const inviteNode = getBinaryNodeChild(result, 'invite');
695
+ return inviteNode?.attrs.code;
696
+ },
697
+ communityAcceptInvite: async (code) => {
698
+ const results = await communityQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
699
+ const result = getBinaryNodeChild(results, 'community');
700
+ return result?.attrs.jid;
701
+ },
702
+ /**
703
+ * revoke a v4 invite for someone
704
+ * @param communityJid community jid
705
+ * @param invitedJid jid of person you invited
706
+ * @returns true if successful
707
+ */
708
+ communityRevokeInviteV4: async (communityJid, invitedJid) => {
709
+ const result = await communityQuery(communityJid, 'set', [
710
+ { tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
711
+ ]);
712
+ return !!result;
713
+ },
714
+ /**
715
+ * accept a CommunityInviteMessage
716
+ * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
717
+ * @param inviteMessage the message to accept
718
+ */
719
+ communityAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
720
+ key = typeof key === 'string' ? { remoteJid: key } : key;
721
+ const results = await communityQuery(inviteMessage.groupJid, 'set', [
722
+ {
723
+ tag: 'accept',
724
+ attrs: {
725
+ code: inviteMessage.inviteCode,
726
+ expiration: inviteMessage.inviteExpiration.toString(),
727
+ admin: key.remoteJid
728
+ }
729
+ }
730
+ ]);
731
+ // if we have the full message key
732
+ // update the invite message to be expired
733
+ if (key.id) {
734
+ // create new invite message that is expired
735
+ inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage);
736
+ inviteMessage.inviteExpiration = 0;
737
+ inviteMessage.inviteCode = '';
738
+ ev.emit('messages.update', [
739
+ {
740
+ key,
741
+ update: {
742
+ message: {
743
+ groupInviteMessage: inviteMessage
744
+ }
745
+ }
746
+ }
747
+ ]);
748
+ }
749
+ // generate the community add message
750
+ await upsertMessage({
751
+ key: {
752
+ remoteJid: inviteMessage.groupJid,
753
+ id: generateMessageIDV2(sock.user?.id),
754
+ fromMe: false,
755
+ participant: key.remoteJid // TODO: investigate if this makes any sense at all
756
+ },
757
+ messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
758
+ messageStubParameters: [JSON.stringify(authState.creds.me)],
759
+ participant: key.remoteJid,
760
+ messageTimestamp: unixTimestampSeconds()
761
+ }, 'notify');
762
+ return results.attrs.from;
763
+ }),
764
+ communityGetInviteInfo: async (code) => {
765
+ const results = await communityQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }]);
766
+ return extractCommunityMetadata(results);
767
+ },
768
+ communityToggleEphemeral: async (jid, ephemeralExpiration) => {
769
+ const content = ephemeralExpiration
770
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
771
+ : { tag: 'not_ephemeral', attrs: {} };
772
+ await communityQuery(jid, 'set', [content]);
773
+ },
774
+ communitySettingUpdate: async (jid, setting) => {
775
+ await communityQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
776
+ },
777
+ communityMemberAddMode: async (jid, mode) => {
778
+ await communityQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }]);
779
+ },
780
+ communityJoinApprovalMode: async (jid, mode) => {
781
+ await communityQuery(jid, 'set', [
782
+ { tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'community_join', attrs: { state: mode } }] }
783
+ ]);
784
+ },
785
+ communityFetchAllParticipating
786
+ };
787
+ };
788
+ export const extractCommunityMetadata = (result) => {
789
+ const community = getBinaryNodeChild(result, 'community');
790
+ const descChild = getBinaryNodeChild(community, 'description');
791
+ let desc;
792
+ let descId;
793
+ if (descChild) {
794
+ desc = getBinaryNodeChildString(descChild, 'body');
795
+ descId = descChild.attrs.id;
796
+ }
797
+ const communityId = community.attrs.id?.includes('@')
798
+ ? community.attrs.id
799
+ : jidEncode(community.attrs.id || '', 'g.us');
800
+ const eph = getBinaryNodeChild(community, 'ephemeral')?.attrs.expiration;
801
+ const memberAddMode = getBinaryNodeChildString(community, 'member_add_mode') === 'all_member_add';
802
+ const metadata = {
803
+ id: communityId,
804
+ subject: community.attrs.subject || '',
805
+ subjectOwner: community.attrs.s_o,
806
+ subjectTime: Number(community.attrs.s_t || 0),
807
+ size: getBinaryNodeChildren(community, 'participant').length,
808
+ creation: Number(community.attrs.creation || 0),
809
+ owner: community.attrs.creator ? jidNormalizedUser(community.attrs.creator) : undefined,
810
+ desc,
811
+ descId,
812
+ linkedParent: getBinaryNodeChild(community, 'linked_parent')?.attrs.jid || undefined,
813
+ restrict: !!getBinaryNodeChild(community, 'locked'),
814
+ announce: !!getBinaryNodeChild(community, 'announcement'),
815
+ isCommunity: !!getBinaryNodeChild(community, 'parent'),
816
+ isCommunityAnnounce: !!getBinaryNodeChild(community, 'default_sub_community'),
817
+ joinApprovalMode: !!getBinaryNodeChild(community, 'membership_approval_mode'),
818
+ memberAddMode,
819
+ participants: getBinaryNodeChildren(community, 'participant').map(({ attrs }) => {
820
+ return {
821
+ // TODO: IMPLEMENT THE PN/LID FIELDS HERE!!
822
+ id: attrs.jid,
823
+ admin: (attrs.type || null)
824
+ };
825
+ }),
826
+ ephemeralDuration: eph ? +eph : undefined,
827
+ addressingMode: getBinaryNodeChildString(community, 'addressing_mode')
828
+ };
829
+ return metadata;
830
+ };