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