@badzz88/baileys 8.5.7 → 8.5.8

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 (142) hide show
  1. package/README.md +337 -1055
  2. package/WAProto/WAProto.proto +284 -264
  3. package/WAProto/index.js +5 -5
  4. package/engine-requirements.js +7 -15
  5. package/lib/Defaults/index.js +130 -187
  6. package/lib/Signal/Group/ciphertext-message.js +11 -14
  7. package/lib/Signal/Group/group-session-builder.js +29 -91
  8. package/lib/Signal/Group/group_cipher.js +81 -88
  9. package/lib/Signal/Group/index.js +12 -136
  10. package/lib/Signal/Group/keyhelper.js +15 -70
  11. package/lib/Signal/Group/sender-chain-key.js +25 -31
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -65
  13. package/lib/Signal/Group/sender-key-message.js +65 -68
  14. package/lib/Signal/Group/sender-key-name.js +41 -43
  15. package/lib/Signal/Group/sender-key-record.js +40 -43
  16. package/lib/Signal/Group/sender-key-state.js +83 -96
  17. package/lib/Signal/Group/sender-message-key.js +25 -29
  18. package/lib/Signal/libsignal.js +425 -453
  19. package/lib/Signal/lid-mapping.js +276 -259
  20. package/lib/Socket/Client/index.js +3 -30
  21. package/lib/Socket/Client/types.js +10 -12
  22. package/lib/Socket/Client/websocket.js +53 -61
  23. package/lib/Socket/business.js +379 -422
  24. package/lib/Socket/chats.js +1193 -1816
  25. package/lib/Socket/communities.js +431 -549
  26. package/lib/Socket/graphql.js +672 -612
  27. package/lib/Socket/groups.js +374 -764
  28. package/lib/Socket/index.js +17 -38
  29. package/lib/Socket/interop.js +417 -503
  30. package/lib/Socket/messages-recv.js +1915 -2441
  31. package/lib/Socket/messages-send.js +1213 -1630
  32. package/lib/Socket/mex.js +9 -15
  33. package/lib/Socket/newsletter.js +747 -808
  34. package/lib/Socket/privacy.js +310 -441
  35. package/lib/Socket/socket.js +1025 -1022
  36. package/lib/Socket/username.js +8 -15
  37. package/lib/Store/index.js +10 -36
  38. package/lib/Store/make-cache-manager-store.js +80 -85
  39. package/lib/Store/make-in-memory-store.js +231 -591
  40. package/lib/Store/make-ordered-dictionary.js +72 -78
  41. package/lib/Store/object-repository.js +28 -25
  42. package/lib/Types/Auth.js +2 -38
  43. package/lib/Types/Bussines.js +2 -2
  44. package/lib/Types/Call.js +2 -2
  45. package/lib/Types/Chat.js +8 -4
  46. package/lib/Types/Contact.js +2 -2
  47. package/lib/Types/Events.js +2 -2
  48. package/lib/Types/GroupMetadata.js +2 -2
  49. package/lib/Types/Label.js +24 -26
  50. package/lib/Types/LabelAssociation.js +6 -8
  51. package/lib/Types/Message.js +11 -95
  52. package/lib/Types/Mex.js +111 -112
  53. package/lib/Types/Product.js +2 -2
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.js +3 -2
  56. package/lib/Types/State.js +56 -70
  57. package/lib/Types/USync.js +2 -2
  58. package/lib/Types/index.js +26 -55
  59. package/lib/Utils/auth-utils.js +288 -292
  60. package/lib/Utils/browser-utils.js +47 -113
  61. package/lib/Utils/business.js +224 -240
  62. package/lib/Utils/chat-utils.js +869 -1205
  63. package/lib/Utils/companion-reg-client-utils.js +34 -41
  64. package/lib/Utils/crypto.js +107 -144
  65. package/lib/Utils/decode-wa-message.js +308 -518
  66. package/lib/Utils/event-buffer.js +611 -596
  67. package/lib/Utils/generics.js +355 -515
  68. package/lib/Utils/history.js +134 -244
  69. package/lib/Utils/identity-change-handler.js +49 -51
  70. package/lib/Utils/index.js +23 -57
  71. package/lib/Utils/link-preview.js +77 -135
  72. package/lib/Utils/logger.js +3 -9
  73. package/lib/Utils/lt-hash.js +6 -37
  74. package/lib/Utils/make-mutex.js +33 -36
  75. package/lib/Utils/message-composer.js +233 -439
  76. package/lib/Utils/message-retry-manager.js +260 -265
  77. package/lib/Utils/messages-media.js +829 -855
  78. package/lib/Utils/messages.js +961 -2528
  79. package/lib/Utils/noise-handler.js +200 -195
  80. package/lib/Utils/offline-node-processor.js +33 -35
  81. package/lib/Utils/pre-key-manager.js +102 -103
  82. package/lib/Utils/process-message.js +560 -978
  83. package/lib/Utils/reporting-utils.js +253 -257
  84. package/lib/Utils/signal.js +195 -218
  85. package/lib/Utils/stanza-ack.js +29 -31
  86. package/lib/Utils/sticker.js +109 -144
  87. package/lib/Utils/sync-action-utils.js +45 -50
  88. package/lib/Utils/tc-token-utils.js +139 -137
  89. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  90. package/lib/Utils/validate-connection.js +202 -218
  91. package/lib/WABinary/constants.js +1299 -1302
  92. package/lib/WABinary/decode.js +262 -343
  93. package/lib/WABinary/encode.js +4 -12
  94. package/lib/WABinary/generic-utils.js +187 -223
  95. package/lib/WABinary/index.js +6 -33
  96. package/lib/WABinary/jid-utils.js +88 -351
  97. package/lib/WABinary/types.js +2 -2
  98. package/lib/WAM/BinaryInfo.js +9 -12
  99. package/lib/WAM/constants.js +22853 -39486
  100. package/lib/WAM/encode.js +140 -132
  101. package/lib/WAM/index.js +4 -31
  102. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +21 -23
  103. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +9 -9
  104. package/lib/WAUSync/Protocols/USyncContactProtocol.js +7 -7
  105. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +10 -10
  106. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +7 -7
  107. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +11 -12
  108. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +4 -5
  109. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +7 -7
  110. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +7 -8
  111. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -7
  112. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +8 -8
  113. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +7 -7
  114. package/lib/WAUSync/Protocols/index.js +12 -39
  115. package/lib/WAUSync/USyncQuery.js +67 -49
  116. package/lib/WAUSync/USyncUser.js +11 -5
  117. package/lib/WAUSync/index.js +3 -31
  118. package/lib/index.js +15 -48
  119. package/package.json +129 -99
  120. package/LICENSE +0 -21
  121. package/lib/Defaults/phonenumber-mcc.json +0 -223
  122. package/lib/Socket/aigroups.js +0 -240
  123. package/lib/Socket/interactive-handler.js +0 -522
  124. package/lib/Socket/managed-account.js +0 -183
  125. package/lib/Socket/registration.js +0 -427
  126. package/lib/Socket/text-router.js +0 -83
  127. package/lib/Types/Newsletter.js +0 -121
  128. package/lib/Utils/command-loader.d.ts +0 -31
  129. package/lib/Utils/command-loader.js +0 -100
  130. package/lib/Utils/consumer-application.js +0 -107
  131. package/lib/Utils/curve25519-js.js +0 -275
  132. package/lib/Utils/group-history.js +0 -60
  133. package/lib/Utils/jid-display-normalization.js +0 -218
  134. package/lib/Utils/meta-ai-msmsg.js +0 -262
  135. package/lib/Utils/native-bridge.js +0 -82
  136. package/lib/Utils/session-pool.d.ts +0 -16
  137. package/lib/Utils/session-pool.js +0 -94
  138. package/lib/Utils/sticker.d.ts +0 -17
  139. package/lib/Utils/view-once-cache.d.ts +0 -9
  140. package/lib/Utils/view-once-cache.js +0 -79
  141. package/lib/Utils/voip-rekey.js +0 -22
  142. package/lib/antiban.js +0 -4637
@@ -1,549 +1,431 @@
1
- 'use strict'
2
- var __importDefault =
3
- (this && this.__importDefault) ||
4
- function (mod) {
5
- return mod && mod.__esModule ? mod : { default: mod }
6
- }
7
- Object.defineProperty(exports, '__esModule', { value: true })
8
- exports.extractCommunityMetadata = exports.makeCommunitiesSocket = void 0
9
- const index_js_1 = require('../../WAProto/index.js')
10
- const Types_1 = require('../Types')
11
- const Utils_1 = require('../Utils')
12
- const logger_1 = __importDefault(require('../Utils/logger'))
13
- const WABinary_1 = require('../WABinary')
14
- const business_1 = require('./business')
15
- const mex_1 = require('./mex')
16
-
17
- const COMMUNITY_MEX_QUERY_IDS = {
18
- QUERY_PARTICIPANT_COUNT: '31981537024824320', // QueryCommunityParticipantCount
19
- QUERY_SUBGROUPS: '25554052094203120', // QuerySubgroups (shared with groups)
20
- QUERY_SUBGROUP_PARTICIPANT_COUNT: '24784259781196780', // QuerySubgroupParticipantCount
21
- UPDATE_OWNER: '24781435194845316' // UpdateCommunityOwner
22
- }
23
-
24
- const makeCommunitiesSocket = config => {
25
- const sock = (0, business_1.makeBusinessSocket)(config)
26
- const { authState, ev, query, generateMessageTag, upsertMessage } = sock
27
-
28
- const mexQuery = (variables, queryId, dataPath) =>
29
- (0, mex_1.executeWMexQuery)(variables, queryId, dataPath, query, generateMessageTag)
30
- const communityQuery = async (jid, type, content) =>
31
- query({
32
- tag: 'iq',
33
- attrs: {
34
- type,
35
- xmlns: 'w:g2',
36
- to: jid
37
- },
38
- content
39
- })
40
- const communityMetadata = async jid => {
41
- const result = await communityQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
42
- return (0, exports.extractCommunityMetadata)(result)
43
- }
44
- const communityFetchAllParticipating = async () => {
45
- const result = await query({
46
- tag: 'iq',
47
- attrs: {
48
- to: '@g.us',
49
- xmlns: 'w:g2',
50
- type: 'get'
51
- },
52
- content: [
53
- {
54
- tag: 'participating',
55
- attrs: {},
56
- content: [
57
- { tag: 'participants', attrs: {} },
58
- { tag: 'description', attrs: {} }
59
- ]
60
- }
61
- ]
62
- })
63
- const data = {}
64
- const communitiesChild = (0, WABinary_1.getBinaryNodeChild)(result, 'communities')
65
- if (communitiesChild) {
66
- const communities = (0, WABinary_1.getBinaryNodeChildren)(communitiesChild, 'community')
67
- for (const communityNode of communities) {
68
- const meta = (0, exports.extractCommunityMetadata)({
69
- tag: 'result',
70
- attrs: {},
71
- content: [communityNode]
72
- })
73
- data[meta.id] = meta
74
- }
75
- }
76
- sock.ev.emit('groups.update', Object.values(data))
77
- return data
78
- }
79
- async function parseGroupResult(node) {
80
- logger_1.default.info({ node }, 'parseGroupResult')
81
- const groupNode = (0, WABinary_1.getBinaryNodeChild)(node, 'group')
82
- if (groupNode) {
83
- try {
84
- const metadata = await sock.groupMetadata(`${groupNode.attrs.id}@g.us`)
85
- return metadata ? metadata : Optional.empty()
86
- } catch (error) {
87
- logger_1.default.error({ error }, 'Error fetching community group metadata')
88
- return Optional.empty()
89
- }
90
- }
91
- return Optional.empty()
92
- }
93
- const Optional = {
94
- empty: () => null,
95
- of: value => (value !== null ? { value } : null)
96
- }
97
- sock.ws.on('CB:ib,,dirty', async node => {
98
- const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty')
99
- if (attrs.type !== 'communities') {
100
- return
101
- }
102
- await communityFetchAllParticipating()
103
- await sock.cleanDirtyBits('groups')
104
- })
105
- return {
106
- ...sock,
107
- communityMetadata,
108
- communityCreate: async (subject, body) => {
109
- const descriptionId = (0, Utils_1.generateMessageID)().substring(0, 12)
110
- const result = await communityQuery('@g.us', 'set', [
111
- {
112
- tag: 'create',
113
- attrs: { subject },
114
- content: [
115
- {
116
- tag: 'description',
117
- attrs: { id: descriptionId },
118
- content: [
119
- {
120
- tag: 'body',
121
- attrs: {},
122
- content: Buffer.from(body || '', 'utf-8')
123
- }
124
- ]
125
- },
126
- {
127
- tag: 'parent',
128
- attrs: { default_membership_approval_mode: 'request_required' }
129
- },
130
- {
131
- tag: 'allow_non_admin_sub_group_creation',
132
- attrs: {}
133
- },
134
- {
135
- tag: 'create_general_chat',
136
- attrs: {}
137
- }
138
- ]
139
- }
140
- ])
141
- return await parseGroupResult(result)
142
- },
143
- communityCreateGroup: async (subject, participants, parentCommunityJid) => {
144
- const key = (0, Utils_1.generateMessageIDV2)()
145
- const result = await communityQuery('@g.us', 'set', [
146
- {
147
- tag: 'create',
148
- attrs: {
149
- subject,
150
- key
151
- },
152
- content: [
153
- ...participants.map(jid => ({
154
- tag: 'participant',
155
- attrs: { jid }
156
- })),
157
- { tag: 'linked_parent', attrs: { jid: parentCommunityJid } }
158
- ]
159
- }
160
- ])
161
- return await parseGroupResult(result)
162
- },
163
- communityLeave: async id => {
164
- await communityQuery('@g.us', 'set', [
165
- {
166
- tag: 'leave',
167
- attrs: {},
168
- content: [{ tag: 'community', attrs: { id } }]
169
- }
170
- ])
171
- },
172
- communityUpdateSubject: async (jid, subject) => {
173
- await communityQuery(jid, 'set', [
174
- {
175
- tag: 'subject',
176
- attrs: {},
177
- content: Buffer.from(subject, 'utf-8')
178
- }
179
- ])
180
- },
181
- communityLinkGroup: async (groupJid, parentCommunityJid) => {
182
- await communityQuery(parentCommunityJid, 'set', [
183
- {
184
- tag: 'links',
185
- attrs: {},
186
- content: [
187
- {
188
- tag: 'link',
189
- attrs: { link_type: 'sub_group' },
190
- content: [{ tag: 'group', attrs: { jid: groupJid } }]
191
- }
192
- ]
193
- }
194
- ])
195
- },
196
- communityUnlinkGroup: async (groupJid, parentCommunityJid) => {
197
- await communityQuery(parentCommunityJid, 'set', [
198
- {
199
- tag: 'unlink',
200
- attrs: { unlink_type: 'sub_group' },
201
- content: [{ tag: 'group', attrs: { jid: groupJid } }]
202
- }
203
- ])
204
- },
205
- communityFetchLinkedGroups: async jid => {
206
- let communityJid = jid
207
- let isCommunity = false
208
- // Try to determine if it is a subgroup or a community
209
- const metadata = await sock.groupMetadata(jid)
210
- if (metadata.linkedParent) {
211
- // It is a subgroup, get the community jid
212
- communityJid = metadata.linkedParent
213
- } else {
214
- // It is a community
215
- isCommunity = true
216
- }
217
- // Fetch all subgroups of the community
218
- const result = await communityQuery(communityJid, 'get', [{ tag: 'sub_groups', attrs: {} }])
219
- const linkedGroupsData = []
220
- const subGroupsNode = (0, WABinary_1.getBinaryNodeChild)(result, 'sub_groups')
221
- if (subGroupsNode) {
222
- const groupNodes = (0, WABinary_1.getBinaryNodeChildren)(subGroupsNode, 'group')
223
- for (const groupNode of groupNodes) {
224
- linkedGroupsData.push({
225
- id: groupNode.attrs.id ? (0, WABinary_1.jidEncode)(groupNode.attrs.id, 'g.us') : undefined,
226
- subject: groupNode.attrs.subject || '',
227
- creation: groupNode.attrs.creation ? Number(groupNode.attrs.creation) : undefined,
228
- owner: groupNode.attrs.creator ? (0, WABinary_1.jidNormalizedUser)(groupNode.attrs.creator) : undefined,
229
- size: groupNode.attrs.size ? Number(groupNode.attrs.size) : undefined
230
- })
231
- }
232
- }
233
- return {
234
- communityJid,
235
- isCommunity,
236
- linkedGroups: linkedGroupsData
237
- }
238
- },
239
- communityRequestParticipantsList: async jid => {
240
- const result = await communityQuery(jid, 'get', [
241
- {
242
- tag: 'membership_approval_requests',
243
- attrs: {}
244
- }
245
- ])
246
- const node = (0, WABinary_1.getBinaryNodeChild)(result, 'membership_approval_requests')
247
- const participants = (0, WABinary_1.getBinaryNodeChildren)(node, 'membership_approval_request')
248
- return participants.map(v => v.attrs)
249
- },
250
- communityRequestParticipantsUpdate: async (jid, participants, action) => {
251
- const result = await communityQuery(jid, 'set', [
252
- {
253
- tag: 'membership_requests_action',
254
- attrs: {},
255
- content: [
256
- {
257
- tag: action,
258
- attrs: {},
259
- content: participants.map(jid => ({
260
- tag: 'participant',
261
- attrs: { jid }
262
- }))
263
- }
264
- ]
265
- }
266
- ])
267
- const node = (0, WABinary_1.getBinaryNodeChild)(result, 'membership_requests_action')
268
- const nodeAction = (0, WABinary_1.getBinaryNodeChild)(node, action)
269
- const participantsAffected = (0, WABinary_1.getBinaryNodeChildren)(nodeAction, 'participant')
270
- return participantsAffected.map(p => {
271
- return { status: p.attrs.error || '200', jid: p.attrs.jid }
272
- })
273
- },
274
- communityParticipantsUpdate: async (jid, participants, action) => {
275
- const result = await communityQuery(jid, 'set', [
276
- {
277
- tag: action,
278
- attrs: action === 'remove' ? { linked_groups: 'true' } : {},
279
- content: participants.map(jid => ({
280
- tag: 'participant',
281
- attrs: { jid }
282
- }))
283
- }
284
- ])
285
- const node = (0, WABinary_1.getBinaryNodeChild)(result, action)
286
- const participantsAffected = (0, WABinary_1.getBinaryNodeChildren)(node, 'participant')
287
- return participantsAffected.map(p => {
288
- return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p }
289
- })
290
- },
291
- communityUpdateDescription: async (jid, description) => {
292
- const metadata = await communityMetadata(jid)
293
- const prev = metadata.descId ?? null
294
- await communityQuery(jid, 'set', [
295
- {
296
- tag: 'description',
297
- attrs: {
298
- ...(description ? { id: (0, Utils_1.generateMessageID)() } : { delete: 'true' }),
299
- ...(prev ? { prev } : {})
300
- },
301
- content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
302
- }
303
- ])
304
- },
305
- communityInviteCode: async jid => {
306
- const result = await communityQuery(jid, 'get', [{ tag: 'invite', attrs: {} }])
307
- const inviteNode = (0, WABinary_1.getBinaryNodeChild)(result, 'invite')
308
- return inviteNode?.attrs.code
309
- },
310
- communityRevokeInvite: async jid => {
311
- const result = await communityQuery(jid, 'set', [{ tag: 'invite', attrs: {} }])
312
- const inviteNode = (0, WABinary_1.getBinaryNodeChild)(result, 'invite')
313
- return inviteNode?.attrs.code
314
- },
315
- communityAcceptInvite: async code => {
316
- const results = await communityQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }])
317
- const result = (0, WABinary_1.getBinaryNodeChild)(results, 'community')
318
- return result?.attrs.jid
319
- },
320
- /**
321
- * revoke a v4 invite for someone
322
- * @param communityJid community jid
323
- * @param invitedJid jid of person you invited
324
- * @returns true if successful
325
- */
326
- communityRevokeInviteV4: async (communityJid, invitedJid) => {
327
- const result = await communityQuery(communityJid, 'set', [
328
- { tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
329
- ])
330
- return !!result
331
- },
332
- /**
333
- * accept a CommunityInviteMessage
334
- * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
335
- * @param inviteMessage the message to accept
336
- */
337
- communityAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
338
- key = typeof key === 'string' ? { remoteJid: key } : key
339
- const results = await communityQuery(inviteMessage.groupJid, 'set', [
340
- {
341
- tag: 'accept',
342
- attrs: {
343
- code: inviteMessage.inviteCode,
344
- expiration: inviteMessage.inviteExpiration.toString(),
345
- admin: key.remoteJid
346
- }
347
- }
348
- ])
349
- // if we have the full message key
350
- // update the invite message to be expired
351
- if (key.id) {
352
- // create new invite message that is expired
353
- inviteMessage = index_js_1.proto.Message.GroupInviteMessage.fromObject(inviteMessage)
354
- inviteMessage.inviteExpiration = 0
355
- inviteMessage.inviteCode = ''
356
- ev.emit('messages.update', [
357
- {
358
- key,
359
- update: {
360
- message: {
361
- groupInviteMessage: inviteMessage
362
- }
363
- }
364
- }
365
- ])
366
- }
367
- // generate the community add message
368
- await upsertMessage(
369
- {
370
- key: {
371
- remoteJid: inviteMessage.groupJid,
372
- id: (0, Utils_1.generateMessageIDV2)(sock.user?.id),
373
- fromMe: false,
374
- participant: key.remoteJid // TODO: investigate if this makes any sense at all
375
- },
376
- messageStubType: Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD,
377
- messageStubParameters: [JSON.stringify(authState.creds.me)],
378
- participant: key.remoteJid,
379
- messageTimestamp: (0, Utils_1.unixTimestampSeconds)()
380
- },
381
- 'notify'
382
- )
383
- return results.attrs.from
384
- }),
385
- communityGetInviteInfo: async code => {
386
- const results = await communityQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
387
- return (0, exports.extractCommunityMetadata)(results)
388
- },
389
- communityToggleEphemeral: async (jid, ephemeralExpiration) => {
390
- const content = ephemeralExpiration
391
- ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
392
- : { tag: 'not_ephemeral', attrs: {} }
393
- await communityQuery(jid, 'set', [content])
394
- },
395
- communitySettingUpdate: async (jid, setting) => {
396
- await communityQuery(jid, 'set', [{ tag: setting, attrs: {} }])
397
- },
398
- communityMemberAddMode: async (jid, mode) => {
399
- await communityQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }])
400
- },
401
- communityJoinApprovalMode: async (jid, mode) => {
402
- await communityQuery(jid, 'set', [
403
- { tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'community_join', attrs: { state: mode } }] }
404
- ])
405
- },
406
- /**
407
- * Update community profile picture
408
- */
409
- communityUpdatePicture: async (jid, content) => {
410
- const { img } = await (0, Utils_1.generateProfilePicture)(content)
411
- await communityQuery(jid, 'set', [
412
- {
413
- tag: 'picture',
414
- attrs: { type: 'image' },
415
- content: img
416
- }
417
- ])
418
- },
419
- /**
420
- * Remove community profile picture
421
- */
422
- communityRemovePicture: async jid => {
423
- await communityQuery(jid, 'set', [{ tag: 'picture', attrs: { type: 'delete' } }])
424
- },
425
- /**
426
- * Update community settings (announce-only, etc.)
427
- */
428
- communitySettingUpdate: async (jid, setting) => {
429
- await communityQuery(jid, 'set', [{ tag: setting, attrs: {} }])
430
- },
431
- /**
432
- * Deactivate/delete a community
433
- */
434
- communityDeactivate: async jid => {
435
- await communityQuery(jid, 'set', [{ tag: 'delete_parent', attrs: {} }])
436
- },
437
- /**
438
- * Get info about a community from an invite link code
439
- */
440
- communityGetInviteInfo: async code => {
441
- const results = await communityQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
442
- return (0, exports.extractCommunityMetadata)(results)
443
- },
444
- /**
445
- * Toggle ephemeral messages for the whole community
446
- */
447
- communityToggleEphemeral: async (jid, ephemeralExpiration) => {
448
- const content = ephemeralExpiration
449
- ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
450
- : { tag: 'not_ephemeral', attrs: {} }
451
- await communityQuery(jid, 'set', [content])
452
- },
453
- communityFetchAllParticipating,
454
-
455
- // ── MEX queries (JSON responses) ──────────────────────────────────────
456
-
457
- /**
458
- * Fetch total participant count of a community via MEX.
459
- * @param {string} jid - Community JID
460
- */
461
- communityParticipantCount: jid =>
462
- mexQuery(
463
- { group_input: { group_id: jid } },
464
- COMMUNITY_MEX_QUERY_IDS.QUERY_PARTICIPANT_COUNT,
465
- 'xwa2_group_query_by_id'
466
- ),
467
-
468
- /**
469
- * Fetch subgroups of a community via MEX (includes hidden_group, join approval state, etc.)
470
- * @param {string} jid - Community JID
471
- */
472
- communitySubgroupsMex: jid =>
473
- mexQuery({ group_input: { group_id: jid } }, COMMUNITY_MEX_QUERY_IDS.QUERY_SUBGROUPS, 'xwa2_group_query_by_id'),
474
-
475
- /**
476
- * Fetch participant count of a specific subgroup within a community.
477
- * @param {string} subgroupJid - Subgroup JID
478
- */
479
- communitySubgroupParticipantCount: subgroupJid =>
480
- mexQuery(
481
- { group_input: { group_id: subgroupJid } },
482
- COMMUNITY_MEX_QUERY_IDS.QUERY_SUBGROUP_PARTICIPANT_COUNT,
483
- 'xwa2_group_query_by_id'
484
- ),
485
-
486
- /**
487
- * Transfer community ownership to a new owner via MEX.
488
- * Sends role_updates: [{ user_jid, new_role: "SUPERADMIN_MEMBER" }]
489
- * @param {string} communityJid - Community JID
490
- * @param {string} newOwnerJid - JID of the new owner
491
- */
492
- communityTransferOwnershipMex: (communityJid, newOwnerJid) =>
493
- mexQuery(
494
- {
495
- group_id: communityJid,
496
- role_updates: [{ user_jid: newOwnerJid, new_role: 'SUPERADMIN_MEMBER' }]
497
- },
498
- COMMUNITY_MEX_QUERY_IDS.UPDATE_OWNER,
499
- 'xwa2_community_update_owner'
500
- ),
501
-
502
- COMMUNITY_MEX_QUERY_IDS
503
- }
504
- }
505
- exports.makeCommunitiesSocket = makeCommunitiesSocket
506
- const extractCommunityMetadata = result => {
507
- const community = (0, WABinary_1.getBinaryNodeChild)(result, 'community')
508
- const descChild = (0, WABinary_1.getBinaryNodeChild)(community, 'description')
509
- let desc
510
- let descId
511
- if (descChild) {
512
- desc = (0, WABinary_1.getBinaryNodeChildString)(descChild, 'body')
513
- descId = descChild.attrs.id
514
- }
515
- const communityId = community.attrs.id?.includes('@')
516
- ? community.attrs.id
517
- : (0, WABinary_1.jidEncode)(community.attrs.id || '', 'g.us')
518
- const eph = (0, WABinary_1.getBinaryNodeChild)(community, 'ephemeral')?.attrs.expiration
519
- const memberAddMode = (0, WABinary_1.getBinaryNodeChildString)(community, 'member_add_mode') === 'all_member_add'
520
- const metadata = {
521
- id: communityId,
522
- subject: community.attrs.subject || '',
523
- subjectOwner: community.attrs.s_o,
524
- subjectTime: Number(community.attrs.s_t || 0),
525
- size: (0, WABinary_1.getBinaryNodeChildren)(community, 'participant').length,
526
- creation: Number(community.attrs.creation || 0),
527
- owner: community.attrs.creator ? (0, WABinary_1.jidNormalizedUser)(community.attrs.creator) : undefined,
528
- desc,
529
- descId,
530
- linkedParent: (0, WABinary_1.getBinaryNodeChild)(community, 'linked_parent')?.attrs.jid || undefined,
531
- restrict: !!(0, WABinary_1.getBinaryNodeChild)(community, 'locked'),
532
- announce: !!(0, WABinary_1.getBinaryNodeChild)(community, 'announcement'),
533
- isCommunity: !!(0, WABinary_1.getBinaryNodeChild)(community, 'parent'),
534
- isCommunityAnnounce: !!(0, WABinary_1.getBinaryNodeChild)(community, 'default_sub_community'),
535
- joinApprovalMode: !!(0, WABinary_1.getBinaryNodeChild)(community, 'membership_approval_mode'),
536
- memberAddMode,
537
- participants: (0, WABinary_1.getBinaryNodeChildren)(community, 'participant').map(({ attrs }) => {
538
- return {
539
- // TODO: IMPLEMENT THE PN/LID FIELDS HERE!!
540
- id: attrs.jid,
541
- admin: attrs.type || null
542
- }
543
- }),
544
- ephemeralDuration: eph ? +eph : undefined,
545
- addressingMode: (0, WABinary_1.getBinaryNodeChildString)(community, 'addressing_mode')
546
- }
547
- return metadata
548
- }
549
- exports.extractCommunityMetadata = extractCommunityMetadata
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { WAMessageStubType } from '../Types/index.js';
3
+ import { generateMessageID, generateMessageIDV2, unixTimestampSeconds } from '../Utils/index.js';
4
+ import logger from '../Utils/logger.js';
5
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
6
+ import { makeBusinessSocket } from './business.js';
7
+ export const makeCommunitiesSocket = (config) => {
8
+ const sock = makeBusinessSocket(config);
9
+ const { authState, ev, query, upsertMessage } = sock;
10
+ const communityQuery = 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 communityMetadata = async (jid) => {
20
+ const result = await communityQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
21
+ return extractCommunityMetadata(result);
22
+ };
23
+ const communityFetchAllParticipating = 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 communitiesChild = getBinaryNodeChild(result, 'communities');
44
+ if (communitiesChild) {
45
+ const communities = getBinaryNodeChildren(communitiesChild, 'community');
46
+ for (const communityNode of communities) {
47
+ const meta = extractCommunityMetadata({
48
+ tag: 'result',
49
+ attrs: {},
50
+ content: [communityNode]
51
+ });
52
+ data[meta.id] = meta;
53
+ }
54
+ }
55
+ sock.ev.emit('groups.update', Object.values(data));
56
+ return data;
57
+ };
58
+ async function parseGroupResult(node) {
59
+ logger.info({ node }, 'parseGroupResult');
60
+ const groupNode = getBinaryNodeChild(node, 'group');
61
+ if (groupNode) {
62
+ try {
63
+ logger.info({ groupNode }, 'groupNode');
64
+ const metadata = await sock.groupMetadata(`${groupNode.attrs.id}@g.us`);
65
+ return metadata ? metadata : Optional.empty();
66
+ }
67
+ catch (error) {
68
+ console.error('Error parsing group metadata:', error);
69
+ return Optional.empty();
70
+ }
71
+ }
72
+ return Optional.empty();
73
+ }
74
+ const Optional = {
75
+ empty: () => null,
76
+ of: (value) => (value !== null ? { value } : null)
77
+ };
78
+ sock.ws.on('CB:ib,,dirty', async (node) => {
79
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
80
+ if (attrs.type !== 'communities') {
81
+ return;
82
+ }
83
+ await communityFetchAllParticipating();
84
+ await sock.cleanDirtyBits('groups');
85
+ });
86
+ return {
87
+ ...sock,
88
+ communityMetadata,
89
+ communityCreate: async (subject, body) => {
90
+ const descriptionId = generateMessageID().substring(0, 12);
91
+ const result = await communityQuery('@g.us', 'set', [
92
+ {
93
+ tag: 'create',
94
+ attrs: { subject },
95
+ content: [
96
+ {
97
+ tag: 'description',
98
+ attrs: { id: descriptionId },
99
+ content: [
100
+ {
101
+ tag: 'body',
102
+ attrs: {},
103
+ content: Buffer.from(body || '', 'utf-8')
104
+ }
105
+ ]
106
+ },
107
+ {
108
+ tag: 'parent',
109
+ attrs: { default_membership_approval_mode: 'request_required' }
110
+ },
111
+ {
112
+ tag: 'allow_non_admin_sub_group_creation',
113
+ attrs: {}
114
+ },
115
+ {
116
+ tag: 'create_general_chat',
117
+ attrs: {}
118
+ }
119
+ ]
120
+ }
121
+ ]);
122
+ return await parseGroupResult(result);
123
+ },
124
+ communityCreateGroup: async (subject, participants, parentCommunityJid) => {
125
+ const key = generateMessageIDV2();
126
+ const result = await communityQuery('@g.us', 'set', [
127
+ {
128
+ tag: 'create',
129
+ attrs: {
130
+ subject,
131
+ key
132
+ },
133
+ content: [
134
+ ...participants.map(jid => ({
135
+ tag: 'participant',
136
+ attrs: { jid }
137
+ })),
138
+ { tag: 'linked_parent', attrs: { jid: parentCommunityJid } }
139
+ ]
140
+ }
141
+ ]);
142
+ return await parseGroupResult(result);
143
+ },
144
+ communityLeave: async (id) => {
145
+ await communityQuery('@g.us', 'set', [
146
+ {
147
+ tag: 'leave',
148
+ attrs: {},
149
+ content: [{ tag: 'community', attrs: { id } }]
150
+ }
151
+ ]);
152
+ },
153
+ communityUpdateSubject: async (jid, subject) => {
154
+ await communityQuery(jid, 'set', [
155
+ {
156
+ tag: 'subject',
157
+ attrs: {},
158
+ content: Buffer.from(subject, 'utf-8')
159
+ }
160
+ ]);
161
+ },
162
+ communityLinkGroup: async (groupJid, parentCommunityJid) => {
163
+ await communityQuery(parentCommunityJid, 'set', [
164
+ {
165
+ tag: 'links',
166
+ attrs: {},
167
+ content: [
168
+ {
169
+ tag: 'link',
170
+ attrs: { link_type: 'sub_group' },
171
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
172
+ }
173
+ ]
174
+ }
175
+ ]);
176
+ },
177
+ communityUnlinkGroup: async (groupJid, parentCommunityJid) => {
178
+ await communityQuery(parentCommunityJid, 'set', [
179
+ {
180
+ tag: 'unlink',
181
+ attrs: { unlink_type: 'sub_group' },
182
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
183
+ }
184
+ ]);
185
+ },
186
+ communityFetchLinkedGroups: async (jid) => {
187
+ let communityJid = jid;
188
+ let isCommunity = false;
189
+ // Try to determine if it is a subgroup or a community
190
+ const metadata = await sock.groupMetadata(jid);
191
+ if (metadata.linkedParent) {
192
+ // It is a subgroup, get the community jid
193
+ communityJid = metadata.linkedParent;
194
+ }
195
+ else {
196
+ // It is a community
197
+ isCommunity = true;
198
+ }
199
+ // Fetch all subgroups of the community
200
+ const result = await communityQuery(communityJid, 'get', [{ tag: 'sub_groups', attrs: {} }]);
201
+ const linkedGroupsData = [];
202
+ const subGroupsNode = getBinaryNodeChild(result, 'sub_groups');
203
+ if (subGroupsNode) {
204
+ const groupNodes = getBinaryNodeChildren(subGroupsNode, 'group');
205
+ for (const groupNode of groupNodes) {
206
+ linkedGroupsData.push({
207
+ id: groupNode.attrs.id ? jidEncode(groupNode.attrs.id, 'g.us') : undefined,
208
+ subject: groupNode.attrs.subject || '',
209
+ creation: groupNode.attrs.creation ? Number(groupNode.attrs.creation) : undefined,
210
+ owner: groupNode.attrs.creator ? jidNormalizedUser(groupNode.attrs.creator) : undefined,
211
+ size: groupNode.attrs.size ? Number(groupNode.attrs.size) : undefined
212
+ });
213
+ }
214
+ }
215
+ return {
216
+ communityJid,
217
+ isCommunity,
218
+ linkedGroups: linkedGroupsData
219
+ };
220
+ },
221
+ communityRequestParticipantsList: async (jid) => {
222
+ const result = await communityQuery(jid, 'get', [
223
+ {
224
+ tag: 'membership_approval_requests',
225
+ attrs: {}
226
+ }
227
+ ]);
228
+ const node = getBinaryNodeChild(result, 'membership_approval_requests');
229
+ const participants = getBinaryNodeChildren(node, 'membership_approval_request');
230
+ return participants.map(v => v.attrs);
231
+ },
232
+ communityRequestParticipantsUpdate: async (jid, participants, action) => {
233
+ const result = await communityQuery(jid, 'set', [
234
+ {
235
+ tag: 'membership_requests_action',
236
+ attrs: {},
237
+ content: [
238
+ {
239
+ tag: action,
240
+ attrs: {},
241
+ content: participants.map(jid => ({
242
+ tag: 'participant',
243
+ attrs: { jid }
244
+ }))
245
+ }
246
+ ]
247
+ }
248
+ ]);
249
+ const node = getBinaryNodeChild(result, 'membership_requests_action');
250
+ const nodeAction = getBinaryNodeChild(node, action);
251
+ const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant');
252
+ return participantsAffected.map(p => {
253
+ return { status: p.attrs.error || '200', jid: p.attrs.jid };
254
+ });
255
+ },
256
+ communityParticipantsUpdate: async (jid, participants, action) => {
257
+ const result = await communityQuery(jid, 'set', [
258
+ {
259
+ tag: action,
260
+ attrs: action === 'remove' ? { linked_groups: 'true' } : {},
261
+ content: participants.map(jid => ({
262
+ tag: 'participant',
263
+ attrs: { jid }
264
+ }))
265
+ }
266
+ ]);
267
+ const node = getBinaryNodeChild(result, action);
268
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
269
+ return participantsAffected.map(p => {
270
+ return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p };
271
+ });
272
+ },
273
+ communityUpdateDescription: async (jid, description) => {
274
+ const metadata = await communityMetadata(jid);
275
+ const prev = metadata.descId ?? null;
276
+ await communityQuery(jid, 'set', [
277
+ {
278
+ tag: 'description',
279
+ attrs: {
280
+ ...(description ? { id: generateMessageID() } : { delete: 'true' }),
281
+ ...(prev ? { prev } : {})
282
+ },
283
+ content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
284
+ }
285
+ ]);
286
+ },
287
+ communityInviteCode: async (jid) => {
288
+ const result = await communityQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
289
+ const inviteNode = getBinaryNodeChild(result, 'invite');
290
+ return inviteNode?.attrs.code;
291
+ },
292
+ communityRevokeInvite: async (jid) => {
293
+ const result = await communityQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
294
+ const inviteNode = getBinaryNodeChild(result, 'invite');
295
+ return inviteNode?.attrs.code;
296
+ },
297
+ communityAcceptInvite: async (code) => {
298
+ const results = await communityQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
299
+ const result = getBinaryNodeChild(results, 'community');
300
+ return result?.attrs.jid;
301
+ },
302
+ /**
303
+ * revoke a v4 invite for someone
304
+ * @param communityJid community jid
305
+ * @param invitedJid jid of person you invited
306
+ * @returns true if successful
307
+ */
308
+ communityRevokeInviteV4: async (communityJid, invitedJid) => {
309
+ const result = await communityQuery(communityJid, 'set', [
310
+ { tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
311
+ ]);
312
+ return !!result;
313
+ },
314
+ /**
315
+ * accept a CommunityInviteMessage
316
+ * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
317
+ * @param inviteMessage the message to accept
318
+ */
319
+ communityAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
320
+ key = typeof key === 'string' ? { remoteJid: key } : key;
321
+ const results = await communityQuery(inviteMessage.groupJid, 'set', [
322
+ {
323
+ tag: 'accept',
324
+ attrs: {
325
+ code: inviteMessage.inviteCode,
326
+ expiration: inviteMessage.inviteExpiration.toString(),
327
+ admin: key.remoteJid
328
+ }
329
+ }
330
+ ]);
331
+ // if we have the full message key
332
+ // update the invite message to be expired
333
+ if (key.id) {
334
+ // create new invite message that is expired
335
+ inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage);
336
+ inviteMessage.inviteExpiration = 0;
337
+ inviteMessage.inviteCode = '';
338
+ ev.emit('messages.update', [
339
+ {
340
+ key,
341
+ update: {
342
+ message: {
343
+ groupInviteMessage: inviteMessage
344
+ }
345
+ }
346
+ }
347
+ ]);
348
+ }
349
+ // generate the community add message
350
+ await upsertMessage({
351
+ key: {
352
+ remoteJid: inviteMessage.groupJid,
353
+ id: generateMessageIDV2(sock.user?.id),
354
+ fromMe: false,
355
+ participant: key.remoteJid // TODO: investigate if this makes any sense at all
356
+ },
357
+ messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
358
+ messageStubParameters: [JSON.stringify(authState.creds.me)],
359
+ participant: key.remoteJid,
360
+ messageTimestamp: unixTimestampSeconds()
361
+ }, 'notify');
362
+ return results.attrs.from;
363
+ }),
364
+ communityGetInviteInfo: async (code) => {
365
+ const results = await communityQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }]);
366
+ return extractCommunityMetadata(results);
367
+ },
368
+ communityToggleEphemeral: async (jid, ephemeralExpiration) => {
369
+ const content = ephemeralExpiration
370
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
371
+ : { tag: 'not_ephemeral', attrs: {} };
372
+ await communityQuery(jid, 'set', [content]);
373
+ },
374
+ communitySettingUpdate: async (jid, setting) => {
375
+ await communityQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
376
+ },
377
+ communityMemberAddMode: async (jid, mode) => {
378
+ await communityQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }]);
379
+ },
380
+ communityJoinApprovalMode: async (jid, mode) => {
381
+ await communityQuery(jid, 'set', [
382
+ { tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'community_join', attrs: { state: mode } }] }
383
+ ]);
384
+ },
385
+ communityFetchAllParticipating
386
+ };
387
+ };
388
+ export const extractCommunityMetadata = (result) => {
389
+ const community = getBinaryNodeChild(result, 'community');
390
+ const descChild = getBinaryNodeChild(community, 'description');
391
+ let desc;
392
+ let descId;
393
+ if (descChild) {
394
+ desc = getBinaryNodeChildString(descChild, 'body');
395
+ descId = descChild.attrs.id;
396
+ }
397
+ const communityId = community.attrs.id?.includes('@')
398
+ ? community.attrs.id
399
+ : jidEncode(community.attrs.id || '', 'g.us');
400
+ const eph = getBinaryNodeChild(community, 'ephemeral')?.attrs.expiration;
401
+ const memberAddMode = getBinaryNodeChildString(community, 'member_add_mode') === 'all_member_add';
402
+ const metadata = {
403
+ id: communityId,
404
+ subject: community.attrs.subject || '',
405
+ subjectOwner: community.attrs.s_o,
406
+ subjectTime: Number(community.attrs.s_t || 0),
407
+ size: getBinaryNodeChildren(community, 'participant').length,
408
+ creation: Number(community.attrs.creation || 0),
409
+ owner: community.attrs.creator ? jidNormalizedUser(community.attrs.creator) : undefined,
410
+ desc,
411
+ descId,
412
+ linkedParent: getBinaryNodeChild(community, 'linked_parent')?.attrs.jid || undefined,
413
+ restrict: !!getBinaryNodeChild(community, 'locked'),
414
+ announce: !!getBinaryNodeChild(community, 'announcement'),
415
+ isCommunity: !!getBinaryNodeChild(community, 'parent'),
416
+ isCommunityAnnounce: !!getBinaryNodeChild(community, 'default_sub_community'),
417
+ joinApprovalMode: !!getBinaryNodeChild(community, 'membership_approval_mode'),
418
+ memberAddMode,
419
+ participants: getBinaryNodeChildren(community, 'participant').map(({ attrs }) => {
420
+ return {
421
+ // TODO: IMPLEMENT THE PN/LID FIELDS HERE!!
422
+ id: attrs.jid,
423
+ admin: (attrs.type || null)
424
+ };
425
+ }),
426
+ ephemeralDuration: eph ? +eph : undefined,
427
+ addressingMode: getBinaryNodeChildString(community, 'addressing_mode')
428
+ };
429
+ return metadata;
430
+ };
431
+ //# sourceMappingURL=communities.js.map