@pontalabs/baileys 1.0.10 → 1.1.0

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 (119) hide show
  1. package/README.md +96 -85
  2. package/lib/Defaults/connection.js +39 -0
  3. package/lib/Defaults/constants.js +50 -0
  4. package/lib/Defaults/history.js +13 -0
  5. package/lib/Defaults/index.js +36 -151
  6. package/lib/Defaults/media.js +43 -0
  7. package/lib/Defaults/phonenumber-mcc.json +221 -221
  8. package/lib/Defaults/prefix.js +12 -0
  9. package/lib/Defaults/vialeys-version.json +7 -0
  10. package/lib/Signal/Group/ciphertext-message.js +10 -15
  11. package/lib/Signal/Group/group-session-builder.js +34 -60
  12. package/lib/Signal/Group/group_cipher.js +69 -76
  13. package/lib/Signal/Group/index.js +41 -60
  14. package/lib/Signal/Group/keyhelper.js +12 -57
  15. package/lib/Signal/Group/sender-chain-key.js +20 -33
  16. package/lib/Signal/Group/sender-key-distribution-message.js +43 -48
  17. package/lib/Signal/Group/sender-key-message.js +58 -53
  18. package/lib/Signal/Group/sender-key-name.js +21 -31
  19. package/lib/Signal/Group/sender-key-record.js +21 -34
  20. package/lib/Signal/Group/sender-key-state.js +59 -106
  21. package/lib/Signal/Group/sender-message-key.js +16 -21
  22. package/lib/Signal/libsignal.js +282 -203
  23. package/lib/Signal/lid-mapping.js +164 -184
  24. package/lib/Socket/Client/index.js +31 -22
  25. package/lib/Socket/Client/types.js +9 -15
  26. package/lib/Socket/Client/websocket.js +42 -37
  27. package/lib/Socket/business.js +212 -336
  28. package/lib/Socket/chats.js +696 -940
  29. package/lib/Socket/community.js +454 -369
  30. package/lib/Socket/groups.js +278 -280
  31. package/lib/Socket/index.js +9 -21
  32. package/lib/Socket/messages-recv.js +1027 -1570
  33. package/lib/Socket/messages-send.js +1180 -1136
  34. package/lib/Socket/mex.js +59 -0
  35. package/lib/Socket/newsletter.js +193 -251
  36. package/lib/Socket/socket.js +758 -898
  37. package/lib/Store/index.js +35 -24
  38. package/lib/Store/make-cache-manager-store.js +53 -66
  39. package/lib/Store/make-in-memory-store.js +319 -325
  40. package/lib/Store/make-ordered-dictionary.js +49 -57
  41. package/lib/Store/object-repository.js +10 -15
  42. package/lib/Types/Auth.js +2 -3
  43. package/lib/Types/Bussines.js +2 -3
  44. package/lib/Types/Call.js +2 -3
  45. package/lib/Types/Chat.js +10 -9
  46. package/lib/Types/Contact.js +2 -3
  47. package/lib/Types/Events.js +2 -3
  48. package/lib/Types/GroupMetadata.js +2 -3
  49. package/lib/Types/Label.js +6 -12
  50. package/lib/Types/LabelAssociation.js +4 -13
  51. package/lib/Types/Message.js +10 -18
  52. package/lib/Types/MexUpdates.js +15 -18
  53. package/lib/Types/Newsletter.js +26 -34
  54. package/lib/Types/Product.js +2 -3
  55. package/lib/Types/Signal.js +2 -3
  56. package/lib/Types/Socket.js +2 -3
  57. package/lib/Types/State.js +8 -13
  58. package/lib/Types/USync.js +2 -3
  59. package/lib/Types/index.js +49 -40
  60. package/lib/Utils/auth-utils.js +190 -495
  61. package/lib/Utils/browser-utils.js +29 -0
  62. package/lib/Utils/business.js +177 -199
  63. package/lib/Utils/chat-utils.js +711 -624
  64. package/lib/Utils/crypto.js +116 -161
  65. package/lib/Utils/decode-wa-message.js +225 -321
  66. package/lib/Utils/event-buffer.js +363 -405
  67. package/lib/Utils/generics.js +318 -472
  68. package/lib/Utils/history.js +72 -76
  69. package/lib/Utils/index.js +49 -41
  70. package/lib/Utils/link-preview.js +59 -103
  71. package/lib/Utils/logger.js +4 -7
  72. package/lib/Utils/lt-hash.js +29 -42
  73. package/lib/Utils/make-mutex.js +26 -42
  74. package/lib/Utils/message-retry-manager.js +134 -160
  75. package/lib/Utils/messages-media.js +665 -731
  76. package/lib/Utils/messages.js +518 -1
  77. package/lib/Utils/noise-handler.js +127 -125
  78. package/lib/Utils/pre-key-manager.js +86 -0
  79. package/lib/Utils/process-message.js +739 -351
  80. package/lib/Utils/signal.js +146 -129
  81. package/lib/Utils/use-multi-file-auth-state.js +68 -135
  82. package/lib/Utils/validate-connection.js +183 -142
  83. package/lib/Utils/vialeys-event-stream.js +41 -0
  84. package/lib/WABinary/constants.js +1281 -1289
  85. package/lib/WABinary/decode.js +145 -200
  86. package/lib/WABinary/encode.js +149 -202
  87. package/lib/WABinary/generic-utils.js +79 -97
  88. package/lib/WABinary/index.js +36 -25
  89. package/lib/WABinary/jid-utils.js +91 -123
  90. package/lib/WABinary/types.js +2 -3
  91. package/lib/WAM/BinaryInfo.js +8 -13
  92. package/lib/WAM/constants.js +16584 -11464
  93. package/lib/WAM/encode.js +117 -133
  94. package/lib/WAM/index.js +34 -23
  95. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -69
  96. package/lib/WAUSync/Protocols/USyncContactProtocol.js +11 -25
  97. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +32 -44
  98. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +13 -23
  99. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -38
  100. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +17 -31
  101. package/lib/WAUSync/Protocols/index.js +37 -26
  102. package/lib/WAUSync/USyncQuery.js +66 -66
  103. package/lib/WAUSync/USyncUser.js +13 -18
  104. package/lib/WAUSync/index.js +34 -23
  105. package/lib/index.js +95 -28
  106. package/package.json +4 -3
  107. package/lib/Defaults/baileys-version.json +0 -3
  108. package/lib/Signal/Group/queue-job.d.ts +0 -1
  109. package/lib/Signal/Group/queue-job.js +0 -57
  110. package/lib/Socket/usync.d.ts +0 -37
  111. package/lib/Socket/usync.js +0 -83
  112. package/lib/Utils/baileys-event-stream.d.ts +0 -18
  113. package/lib/Utils/baileys-event-stream.js +0 -70
  114. package/lib/Utils/signal-housekeeping.d.ts +0 -19
  115. package/lib/Utils/signal-housekeeping.js +0 -73
  116. package/lib/Utils/use-mongo-file-auth-state.d.ts +0 -6
  117. package/lib/Utils/use-mongo-file-auth-state.js +0 -84
  118. package/lib/Utils/use-single-file-auth-state.d.ts +0 -13
  119. package/lib/Utils/use-single-file-auth-state.js +0 -80
@@ -1,369 +1,454 @@
1
- "use strict"
2
- Object.defineProperty(exports, "__esModule", { value: true })
3
-
4
- const WAProto_1 = require("../../WAProto")
5
- const Types_1 = require("../Types")
6
- const Utils_1 = require("../Utils")
7
- const WABinary_1 = require("../WABinary")
8
- const business_1 = require("./business")
9
-
10
- const makeCommunitiesSocket = (config) => {
11
- const sock = business_1.makeBusinessSocket(config)
12
- const { authState, ev, query, groupMetadata, upsertMessage } = sock
13
-
14
- const communityQuery = async (jid, type, content) => (query({
15
- tag: 'iq',
16
- attrs: {
17
- type,
18
- xmlns: 'w:g2',
19
- to: jid,
20
- },
21
- content
22
- }))
23
-
24
- const communityMetadata = async (jid) => {
25
- const result = await communityQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
26
- return extractCommunityMetadata(result)
27
- }
28
-
29
- const communityFetchAllParticipating = async () => {
30
- const result = await query({
31
- tag: 'iq',
32
- attrs: {
33
- to: '@g.us',
34
- xmlns: 'w:g2',
35
- type: 'get',
36
- },
37
- content: [
38
- {
39
- tag: 'participating',
40
- attrs: {},
41
- content: [
42
- { tag: 'participants', attrs: {} },
43
- { tag: 'description', attrs: {} }
44
- ]
45
- }
46
- ]
47
- })
48
-
49
- const data = {}
50
- const communitiesChild = WABinary_1.getBinaryNodeChild(result, 'communities')
51
-
52
- if (communitiesChild) {
53
- const communities = WABinary_1.getBinaryNodeChildren(communitiesChild, 'community')
54
- for (const communityNode of communities) {
55
- const meta = extractCommunityMetadata({
56
- tag: 'result',
57
- attrs: {},
58
- content: [communityNode]
59
- })
60
- data[meta.id] = meta
61
- }
62
- }
63
-
64
- sock.ev.emit('groups.update', Object.values(data))
65
- return data
66
- }
67
-
68
- sock.ws.on('CB:ib,,dirty', async (node) => {
69
- const { attrs } = WABinary_1.getBinaryNodeChild(node, 'dirty')
70
-
71
- if (attrs.type !== 'communities') {
72
- return
73
- }
74
-
75
- await communityFetchAllParticipating()
76
- await sock.cleanDirtyBits('groups')
77
- })
78
-
79
- return {
80
- ...sock,
81
- communityQuery,
82
- communityMetadata,
83
- communityCreate: async (subject, body) => {
84
- const descriptionId = Utils_1.generateMessageID().substring(0, 12)
85
-
86
- const result = await communityQuery('@g.us', 'set', [
87
- {
88
- tag: 'create',
89
- attrs: { subject },
90
- content: [{
91
- tag: 'description',
92
- attrs: {
93
- id: descriptionId
94
- },
95
- content: [{
96
- tag: 'body',
97
- attrs: {},
98
- content: Buffer.from(body || '', 'utf-8')
99
- }]
100
- },
101
- {
102
- tag: 'parent',
103
- attrs: {
104
- default_membership_approval_mode: 'request_required'
105
- }
106
- },
107
- {
108
- tag: 'allow_non_admin_sub_group_creation',
109
- attrs: {}
110
- },
111
- {
112
- tag: 'create_general_chat',
113
- attrs: {}
114
- }]
115
- }
116
- ])
117
-
118
- return extractCommunityMetadata(result)
119
- },
120
- communityLeave: async (id) => {
121
- await communityQuery('@g.us', 'set', [
122
- {
123
- tag: 'leave',
124
- attrs: {},
125
- content: [
126
- { tag: 'community', attrs: { id } }
127
- ]
128
- }
129
- ])
130
- },
131
- communityUpdateSubject: async (jid, subject) => {
132
- await communityQuery(jid, 'set', [
133
- {
134
- tag: 'subject',
135
- attrs: {},
136
- content: Buffer.from(subject, 'utf-8')
137
- }
138
- ])
139
- },
140
- communityRequestParticipantsList: async (jid) => {
141
- const result = await communityQuery(jid, 'get', [
142
- {
143
- tag: 'membership_approval_requests',
144
- attrs: {}
145
- }
146
- ])
147
-
148
- const node = WABinary_1.getBinaryNodeChild(result, 'membership_approval_requests')
149
- const participants = WABinary_1.getBinaryNodeChildren(node, 'membership_approval_request')
150
-
151
- return participants.map(v => v.attrs)
152
- },
153
- communityRequestParticipantsUpdate: async (jid, participants, action) => {
154
- const result = await communityQuery(jid, 'set', [{
155
- tag: 'membership_requests_action',
156
- attrs: {},
157
- content: [
158
- {
159
- tag: action,
160
- attrs: {},
161
- content: participants.map(jid => ({
162
- tag: 'participant',
163
- attrs: { jid }
164
- }))
165
- }
166
- ]
167
- }])
168
-
169
- const node = WABinary_1.getBinaryNodeChild(result, 'membership_requests_action')
170
- const nodeAction = WABinary_1.getBinaryNodeChild(node, action)
171
- const participantsAffected = WABinary_1.getBinaryNodeChildren(nodeAction, 'participant')
172
-
173
- return participantsAffected.map(p => {
174
- return { status: p.attrs.error || '200', jid: p.attrs.jid }
175
- })
176
- },
177
- communityParticipantsUpdate: async (jid, participants, action) => {
178
- const result = await communityQuery(jid, 'set', [
179
- {
180
- tag: action,
181
- attrs: {},
182
- content: participants.map(jid => ({
183
- tag: 'participant',
184
- attrs: { jid }
185
- }))
186
- }
187
- ])
188
- const node = WABinary_1.getBinaryNodeChild(result, action)
189
- const participantsAffected = WABinary_1.getBinaryNodeChildren(node, 'participant')
190
-
191
- return participantsAffected.map(p => {
192
- return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p }
193
- })
194
- },
195
- communityUpdateDescription: async (jid, description) => {
196
- const metadata = await communityMetadata(jid)
197
- const prev = metadata.descId ? metadata.descId : null
198
-
199
- await communityQuery(jid, 'set', [
200
- {
201
- tag: 'description',
202
- attrs: {
203
- ...(description ? { id: Utils_1.generateMessageID() } : { delete: 'true' }),
204
- ...(prev ? { prev } : {})
205
- },
206
- content: description ? [
207
- { tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }
208
- ] : undefined
209
- }
210
- ])
211
- },
212
- communityInviteCode: async (jid) => {
213
- const result = await communityQuery(jid, 'get', [{ tag: 'invite', attrs: {} }])
214
- const inviteNode = WABinary_1.getBinaryNodeChild(result, 'invite')
215
-
216
- return inviteNode?.attrs?.code
217
- },
218
- communityRevokeInvite: async (jid) => {
219
- const result = await communityQuery(jid, 'set', [{ tag: 'invite', attrs: {} }])
220
- const inviteNode = WABinary_1.getBinaryNodeChild(result, 'invite')
221
-
222
- return inviteNode?.attrs?.code
223
- },
224
- communityAcceptInvite: async (code) => {
225
- const results = await communityQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }])
226
- const result = WABinary_1.getBinaryNodeChild(results, 'community')
227
-
228
- return result?.attrs?.jid
229
- },
230
- /**
231
- * revoke a v4 invite for someone
232
- * @param communityJid community jid
233
- * @param invitedJid jid of person you invited
234
- * @returns true if successful
235
- */
236
- communityRevokeInviteV4: async (communityJid, invitedJid) => {
237
- const result = await communityQuery(communityJid, 'set', [{ tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }])
238
-
239
- return !!result
240
- },
241
- /**
242
- * accept a GroupInviteMessage
243
- * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
244
- * @param inviteMessage the message to accept
245
- */
246
- communityAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
247
- key = typeof key === 'string' ? { remoteJid: key } : key
248
- const results = await communityQuery(inviteMessage.groupJid, 'set', [{
249
- tag: 'accept',
250
- attrs: {
251
- code: inviteMessage.inviteCode,
252
- expiration: inviteMessage.inviteExpiration.toString(),
253
- admin: key.remoteJid
254
- }
255
- }])
256
-
257
- // if we have the full message key
258
- // update the invite message to be expired
259
- if (key.id) {
260
- // create new invite message that is expired
261
- inviteMessage = WAProto_1.proto.Message.GroupInviteMessage.fromObject(inviteMessage)
262
- inviteMessage.inviteExpiration = 0
263
- inviteMessage.inviteCode = ''
264
- ev.emit('messages.update', [
265
- {
266
- key,
267
- update: {
268
- message: {
269
- groupInviteMessage: inviteMessage
270
- }
271
- }
272
- }
273
- ])
274
- }
275
-
276
- // generate the group add message
277
- await upsertMessage({
278
- key: {
279
- remoteJid: inviteMessage.groupJid,
280
- id: Utils_1.generateMessageID(authState.creds.me?.id),
281
- fromMe: false,
282
- participant: key.remoteJid,
283
- },
284
- messageStubType: Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD,
285
- messageStubParameters: [
286
- authState.creds.me.id
287
- ],
288
- participant: key.remoteJid,
289
- messageTimestamp: Utils_1.unixTimestampSeconds()
290
- }, 'notify')
291
-
292
- return results.attrs.from
293
- }),
294
- communityGetInviteInfo: async (code) => {
295
- const results = await communityQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
296
-
297
- return extractCommunityMetadata(results)
298
- },
299
- communityToggleEphemeral: async (jid, ephemeralExpiration) => {
300
- const content = ephemeralExpiration ?
301
- { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } } :
302
- { tag: 'not_ephemeral', attrs: {} }
303
- await communityQuery(jid, 'set', [content])
304
- },
305
- communitySettingUpdate: async (jid, setting) => {
306
- await communityQuery(jid, 'set', [{ tag: setting, attrs: {} }])
307
- },
308
- communityMemberAddMode: async (jid, mode) => {
309
- await communityQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }])
310
- },
311
- communityJoinApprovalMode: async (jid, mode) => {
312
- await communityQuery(jid, 'set', [{ tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'community_join', attrs: { state: mode } }] }])
313
- },
314
- communityFetchAllParticipating
315
- }
316
- }
317
-
318
- const extractCommunityMetadata = (result) => {
319
- const community = WABinary_1.getBinaryNodeChild(result, 'group')
320
- const descChild = WABinary_1.getBinaryNodeChild(community, 'description')
321
-
322
- let desc
323
- let descId
324
-
325
- if (descChild) {
326
- desc = WABinary_1.getBinaryNodeChildString(descChild, 'body')
327
- descId = descChild.attrs.id
328
- }
329
-
330
- const mode = community.attrs.addressing_mode
331
- const communityId = community.attrs.id.includes('@') ? community.attrs.id : WABinary_1.jidEncode(community.attrs.id, 'g.us')
332
- const eph = WABinary_1.getBinaryNodeChild(community, 'ephemeral')?.attrs.expiration
333
- const memberAddMode = WABinary_1.getBinaryNodeChildString(community, 'member_add_mode') === 'all_member_add'
334
-
335
- const metadata = {
336
- id: communityId,
337
- addressingMode: mode,
338
- subject: community.attrs.subject,
339
- subjectOwner: mode === 'lid' ? community.attrs.s_o_pn : community.attrs.s_o,
340
- subjectTime: +community.attrs.s_t,
341
- size: community.attrs?.size ? +community.attrs.size : WABinary_1.getBinaryNodeChildren(community, 'participant').length,
342
- creation: +community.attrs.creation,
343
- owner: community.attrs.creator ? WABinary_1.jidNormalizedUser(mode === 'lid' ? community.attrs.creator_pn : community.attrs.creator) : undefined,
344
- desc,
345
- descId,
346
- linkedParent: WABinary_1.getBinaryNodeChild(community, 'linked_parent')?.attrs.jid || undefined,
347
- restrict: !!WABinary_1.getBinaryNodeChild(community, 'locked'),
348
- announce: !!WABinary_1.getBinaryNodeChild(community, 'announcement'),
349
- isCommunity: !!WABinary_1.getBinaryNodeChild(community, 'parent'),
350
- isCommunityAnnounce: !!WABinary_1.getBinaryNodeChild(community, 'default_sub_group'),
351
- joinApprovalMode: !!WABinary_1.getBinaryNodeChild(community, 'membership_approval_mode'),
352
- memberAddMode,
353
- participants: WABinary_1.getBinaryNodeChildren(community, 'participant').map(({ attrs }) => {
354
- return {
355
- id: mode === 'lid' ? community.phone_number : attrs.jid,
356
- lid: mode === 'lid' ? community.jid : attrs.lid,
357
- admin: (attrs.type || null),
358
- }
359
- }),
360
- ephemeralDuration: eph ? +eph : undefined,
361
- }
362
-
363
- return metadata
364
- }
365
-
366
- module.exports = {
367
- makeCommunitiesSocket,
368
- extractCommunityMetadata
369
- }
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { proto: proto } = require("../../WAProto");
4
+ const { default: logger } = require("../Utils/logger");
5
+ const {
6
+ WAMessageStubType: WAMessageStubType,
7
+ WAMessageAddressingMode: WAMessageAddressingMode,
8
+ } = require("../Types");
9
+ const {
10
+ generateMessageID: generateMessageID,
11
+ unixTimestampSeconds: unixTimestampSeconds,
12
+ } = require("../Utils");
13
+ const {
14
+ getBinaryNodeChild: getBinaryNodeChild,
15
+ getBinaryNodeChildren: getBinaryNodeChildren,
16
+ getBinaryNodeChildString: getBinaryNodeChildString,
17
+ jidEncode: jidEncode,
18
+ jidNormalizedUser: jidNormalizedUser,
19
+ } = require("../WABinary");
20
+ const { makeBusinessSocket: makeBusinessSocket } = require("./business");
21
+ const makeCommunitiesSocket = (config) => {
22
+ const conn = makeBusinessSocket(config);
23
+ const {
24
+ authState: authState,
25
+ ev: ev,
26
+ query: query,
27
+ groupMetadata: groupMetadata,
28
+ upsertMessage: upsertMessage,
29
+ cleanDirtyBits: cleanDirtyBits,
30
+ } = conn;
31
+ const communityQuery = async (jid, type, content) =>
32
+ query({
33
+ tag: "iq",
34
+ attrs: { type: type, xmlns: "w:g2", to: jid },
35
+ content: content,
36
+ });
37
+ const communityMetadata = async (jid) => {
38
+ const result = await communityQuery(jid, "get", [
39
+ { tag: "query", attrs: { request: "interactive" } },
40
+ ]);
41
+ return extractCommunityMetadata(result);
42
+ };
43
+ const communityFetchAllParticipating = async () => {
44
+ const result = await query({
45
+ tag: "iq",
46
+ attrs: { to: "@g.us", xmlns: "w:g2", type: "get" },
47
+ content: [
48
+ {
49
+ tag: "participating",
50
+ attrs: {},
51
+ content: [
52
+ { tag: "participants", attrs: {} },
53
+ { tag: "description", attrs: {} },
54
+ ],
55
+ },
56
+ ],
57
+ });
58
+ const data = {};
59
+ const communitiesChild = getBinaryNodeChild(result, "communities");
60
+ if (communitiesChild) {
61
+ const communities = getBinaryNodeChildren(communitiesChild, "community");
62
+ for (const communityNode of communities) {
63
+ const meta = extractCommunityMetadata({
64
+ tag: "result",
65
+ attrs: {},
66
+ content: [communityNode],
67
+ });
68
+ data[meta.id] = meta;
69
+ }
70
+ }
71
+ conn.ev.emit("groups.update", Object.values(data));
72
+ return data;
73
+ };
74
+ async function parseGroupResult(node) {
75
+ logger.info({ node: node }, "parseGroupResult");
76
+ const groupNode = getBinaryNodeChild(node, "group");
77
+ if (groupNode) {
78
+ try {
79
+ logger.info({ groupNode: groupNode }, "groupNode");
80
+ const metadata = await groupMetadata(`${groupNode.attrs.id}@g.us`);
81
+ return metadata ? metadata : null;
82
+ } catch (error) {
83
+ logger.warn({ error: error }, "Error parsing group metadata");
84
+ return null;
85
+ }
86
+ }
87
+ return null;
88
+ }
89
+ conn.ws.on("CB:ib,,dirty", async (node) => {
90
+ const { attrs: attrs } = getBinaryNodeChild(node, "dirty");
91
+ if (attrs.type !== "communities") {
92
+ return;
93
+ }
94
+ await communityFetchAllParticipating();
95
+ await cleanDirtyBits("groups");
96
+ });
97
+ return {
98
+ ...conn,
99
+ communityQuery: communityQuery,
100
+ communityMetadata: communityMetadata,
101
+ communityCreate: async (subject, body) => {
102
+ const descriptionId = generateMessageID().substring(0, 12);
103
+ const result = await communityQuery("@g.us", "set", [
104
+ {
105
+ tag: "create",
106
+ attrs: { subject: subject },
107
+ content: [
108
+ {
109
+ tag: "description",
110
+ attrs: { id: descriptionId },
111
+ content: [
112
+ {
113
+ tag: "body",
114
+ attrs: {},
115
+ content: Buffer.from(body || "", "utf-8"),
116
+ },
117
+ ],
118
+ },
119
+ {
120
+ tag: "parent",
121
+ attrs: { default_membership_approval_mode: "request_required" },
122
+ },
123
+ { tag: "allow_non_admin_sub_group_creation", attrs: {} },
124
+ { tag: "create_general_chat", attrs: {} },
125
+ ],
126
+ },
127
+ ]);
128
+ return await parseGroupResult(result);
129
+ },
130
+ communityCreateGroup: async (subject, participants, parentCommunityJid) => {
131
+ const key = generateMessageID();
132
+ const result = await communityQuery("@g.us", "set", [
133
+ {
134
+ tag: "create",
135
+ attrs: { subject: subject, key: key },
136
+ content: [
137
+ ...participants.map((jid) => ({
138
+ tag: "participant",
139
+ attrs: { jid: jid },
140
+ })),
141
+ { tag: "linked_parent", attrs: { jid: parentCommunityJid } },
142
+ ],
143
+ },
144
+ ]);
145
+ return await parseGroupResult(result);
146
+ },
147
+ communityLeave: async (id) => {
148
+ await communityQuery("@g.us", "set", [
149
+ {
150
+ tag: "leave",
151
+ attrs: {},
152
+ content: [{ tag: "community", attrs: { id: id } }],
153
+ },
154
+ ]);
155
+ },
156
+ communityUpdateSubject: async (jid, subject) => {
157
+ await communityQuery(jid, "set", [
158
+ { tag: "subject", attrs: {}, content: Buffer.from(subject, "utf-8") },
159
+ ]);
160
+ },
161
+ communityLinkGroup: async (groupJid, parentCommunityJid) => {
162
+ await communityQuery(parentCommunityJid, "set", [
163
+ {
164
+ tag: "links",
165
+ attrs: {},
166
+ content: [
167
+ {
168
+ tag: "link",
169
+ attrs: { link_type: "sub_group" },
170
+ content: [{ tag: "group", attrs: { jid: groupJid } }],
171
+ },
172
+ ],
173
+ },
174
+ ]);
175
+ },
176
+ communityUnlinkGroup: async (groupJid, parentCommunityJid) => {
177
+ await communityQuery(parentCommunityJid, "set", [
178
+ {
179
+ tag: "unlink",
180
+ attrs: { unlink_type: "sub_group" },
181
+ content: [{ tag: "group", attrs: { jid: groupJid } }],
182
+ },
183
+ ]);
184
+ },
185
+ communityFetchLinkedGroups: async (jid) => {
186
+ let communityJid = jid;
187
+ let isCommunity = false;
188
+ const metadata = await groupMetadata(jid);
189
+ if (metadata.linkedParent) {
190
+ communityJid = metadata.linkedParent;
191
+ } else {
192
+ isCommunity = true;
193
+ }
194
+ const result = await communityQuery(communityJid, "get", [
195
+ { tag: "sub_groups", attrs: {} },
196
+ ]);
197
+ const linkedGroupsData = [];
198
+ const subGroupsNode = getBinaryNodeChild(result, "sub_groups");
199
+ if (subGroupsNode) {
200
+ const groupNodes = getBinaryNodeChildren(subGroupsNode, "group");
201
+ for (const groupNode of groupNodes) {
202
+ linkedGroupsData.push({
203
+ id: groupNode.attrs.id ? jidEncode(groupNode.attrs.id, "g.us") : undefined,
204
+ subject: groupNode.attrs.subject || "",
205
+ creation: groupNode.attrs.creation
206
+ ? Number(groupNode.attrs.creation)
207
+ : undefined,
208
+ owner: groupNode.attrs.creator
209
+ ? jidNormalizedUser(groupNode.attrs.creator)
210
+ : undefined,
211
+ size: groupNode.attrs.size ? Number(groupNode.attrs.size) : undefined,
212
+ });
213
+ }
214
+ }
215
+ return {
216
+ communityJid: communityJid,
217
+ isCommunity: isCommunity,
218
+ linkedGroups: linkedGroupsData,
219
+ };
220
+ },
221
+ communityRequestParticipantsList: async (jid) => {
222
+ const result = await communityQuery(jid, "get", [
223
+ { tag: "membership_approval_requests", attrs: {} },
224
+ ]);
225
+ const node = getBinaryNodeChild(result, "membership_approval_requests");
226
+ const participants = getBinaryNodeChildren(node, "membership_approval_request");
227
+ return participants.map((v) => v.attrs);
228
+ },
229
+ communityRequestParticipantsUpdate: async (jid, participants, action) => {
230
+ const result = await communityQuery(jid, "set", [
231
+ {
232
+ tag: "membership_requests_action",
233
+ attrs: {},
234
+ content: [
235
+ {
236
+ tag: action,
237
+ attrs: {},
238
+ content: participants.map((jid) => ({
239
+ tag: "participant",
240
+ attrs: { jid: jid },
241
+ })),
242
+ },
243
+ ],
244
+ },
245
+ ]);
246
+ const node = getBinaryNodeChild(result, "membership_requests_action");
247
+ const nodeAction = getBinaryNodeChild(node, action);
248
+ const participantsAffected = getBinaryNodeChildren(nodeAction, "participant");
249
+ return participantsAffected.map((p) => ({
250
+ status: p.attrs.error || "200",
251
+ jid: p.attrs.jid,
252
+ }));
253
+ },
254
+ communityParticipantsUpdate: async (jid, participants, action) => {
255
+ const result = await communityQuery(jid, "set", [
256
+ {
257
+ tag: action,
258
+ attrs: action === "remove" ? { linked_groups: "true" } : {},
259
+ content: participants.map((jid) => ({
260
+ tag: "participant",
261
+ attrs: { jid: jid },
262
+ })),
263
+ },
264
+ ]);
265
+ const node = getBinaryNodeChild(result, action);
266
+ const participantsAffected = getBinaryNodeChildren(node, "participant");
267
+ return participantsAffected.map((p) => ({
268
+ status: p.attrs.error || "200",
269
+ jid: p.attrs.jid,
270
+ 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: prev } : {}),
282
+ },
283
+ content: description
284
+ ? [
285
+ {
286
+ tag: "body",
287
+ attrs: {},
288
+ content: Buffer.from(description, "utf-8"),
289
+ },
290
+ ]
291
+ : undefined,
292
+ },
293
+ ]);
294
+ },
295
+ communityInviteCode: async (jid) => {
296
+ const result = await communityQuery(jid, "get", [{ tag: "invite", attrs: {} }]);
297
+ const inviteNode = getBinaryNodeChild(result, "invite");
298
+ return inviteNode?.attrs.code;
299
+ },
300
+ communityRevokeInvite: async (jid) => {
301
+ const result = await communityQuery(jid, "set", [{ tag: "invite", attrs: {} }]);
302
+ const inviteNode = getBinaryNodeChild(result, "invite");
303
+ return inviteNode?.attrs.code;
304
+ },
305
+ communityAcceptInvite: async (code) => {
306
+ const results = await communityQuery("@g.us", "set", [
307
+ { tag: "invite", attrs: { code: code } },
308
+ ]);
309
+ const result = getBinaryNodeChild(results, "community");
310
+ return result?.attrs.jid;
311
+ },
312
+ communityRevokeInviteV4: async (communityJid, invitedJid) => {
313
+ const result = await communityQuery(communityJid, "set", [
314
+ {
315
+ tag: "revoke",
316
+ attrs: {},
317
+ content: [{ tag: "participant", attrs: { jid: invitedJid } }],
318
+ },
319
+ ]);
320
+ return !!result;
321
+ },
322
+ communityAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
323
+ key = typeof key === "string" ? { remoteJid: key } : key;
324
+ const results = await communityQuery(inviteMessage.groupJid, "set", [
325
+ {
326
+ tag: "accept",
327
+ attrs: {
328
+ code: inviteMessage.inviteCode,
329
+ expiration: inviteMessage.inviteExpiration.toString(),
330
+ admin: key.remoteJid,
331
+ },
332
+ },
333
+ ]);
334
+ if (key.id) {
335
+ inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage);
336
+ inviteMessage.inviteExpiration = 0;
337
+ inviteMessage.inviteCode = "";
338
+ ev.emit("messages.update", [
339
+ {
340
+ key: key,
341
+ update: { message: { groupInviteMessage: inviteMessage } },
342
+ },
343
+ ]);
344
+ }
345
+ await upsertMessage(
346
+ {
347
+ key: {
348
+ remoteJid: inviteMessage.groupJid,
349
+ id: generateMessageID(conn.user?.id),
350
+ fromMe: false,
351
+ participant: key.remoteJid,
352
+ },
353
+ messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
354
+ messageStubParameters: [JSON.stringify(authState.creds.me)],
355
+ participant: key.remoteJid,
356
+ messageTimestamp: unixTimestampSeconds(),
357
+ },
358
+ "notify"
359
+ );
360
+ return results.attrs.from;
361
+ }),
362
+ communityGetInviteInfo: async (code) => {
363
+ const results = await communityQuery("@g.us", "get", [
364
+ { tag: "invite", attrs: { code: code } },
365
+ ]);
366
+ return extractCommunityMetadata(results);
367
+ },
368
+ communityToggleEphemeral: async (jid, ephemeralExpiration) => {
369
+ const content = ephemeralExpiration
370
+ ? {
371
+ tag: "ephemeral",
372
+ attrs: { expiration: ephemeralExpiration.toString() },
373
+ }
374
+ : { tag: "not_ephemeral", attrs: {} };
375
+ await communityQuery(jid, "set", [content]);
376
+ },
377
+ communitySettingUpdate: async (jid, setting) => {
378
+ await communityQuery(jid, "set", [{ tag: setting, attrs: {} }]);
379
+ },
380
+ communityMemberAddMode: async (jid, mode) => {
381
+ await communityQuery(jid, "set", [
382
+ { tag: "member_add_mode", attrs: {}, content: mode },
383
+ ]);
384
+ },
385
+ communityJoinApprovalMode: async (jid, mode) => {
386
+ await communityQuery(jid, "set", [
387
+ {
388
+ tag: "membership_approval_mode",
389
+ attrs: {},
390
+ content: [{ tag: "community_join", attrs: { state: mode } }],
391
+ },
392
+ ]);
393
+ },
394
+ communityFetchAllParticipating: communityFetchAllParticipating,
395
+ };
396
+ };
397
+ const extractCommunityMetadata = (result) => {
398
+ const community = getBinaryNodeChild(result, "group");
399
+ const descChild = getBinaryNodeChild(community, "description");
400
+ let desc;
401
+ let descId;
402
+ if (descChild) {
403
+ desc = getBinaryNodeChildString(descChild, "body");
404
+ descId = descChild.attrs.id;
405
+ }
406
+ const mode = community.attrs.addressing_mode;
407
+ const communityId = community.attrs.id.includes("@")
408
+ ? community.attrs.id
409
+ : jidEncode(community.attrs.id, "g.us");
410
+ const eph = getBinaryNodeChild(community, "ephemeral")?.attrs.expiration;
411
+ const memberAddMode =
412
+ getBinaryNodeChildString(community, "member_add_mode") === "all_member_add";
413
+ const metadata = {
414
+ id: communityId,
415
+ subject: community.attrs.subject,
416
+ subjectOwner: community.attrs.s_o,
417
+ subjectOwnerAlt: community.attrs?.s_o_pn ? community.attrs.s_o_pn : community.attrs.s_o,
418
+ subjectTime: Number(community.attrs.s_t || 0),
419
+ size: Number(
420
+ community.attrs?.size
421
+ ? community.attrs.size
422
+ : getBinaryNodeChildren(community, "participant").length
423
+ ),
424
+ creation: Number(community.attrs.creation || 0),
425
+ owner: community.attrs.creator ? jidNormalizedUser(community.attrs.creator) : undefined,
426
+ ownerAlt: community.attrs.creator
427
+ ? jidNormalizedUser(
428
+ community.attrs?.creator_pn ? community.attrs.creator_pn : community.attrs.creator
429
+ )
430
+ : undefined,
431
+ ownerCountry: community.attrs.creator_country_code,
432
+ desc: desc,
433
+ descId: descId,
434
+ linkedParent: getBinaryNodeChild(community, "linked_parent")?.attrs.jid || undefined,
435
+ restrict: !!getBinaryNodeChild(community, "locked"),
436
+ announce: !!getBinaryNodeChild(community, "announcement"),
437
+ isCommunity: !!getBinaryNodeChild(community, "parent"),
438
+ isCommunityAnnounce: !!getBinaryNodeChild(community, "default_sub_group"),
439
+ joinApprovalMode: !!getBinaryNodeChild(community, "membership_approval_mode"),
440
+ memberAddMode: memberAddMode,
441
+ participants: getBinaryNodeChildren(community, "participant").map(({ attrs: attrs }) => ({
442
+ id: mode === WAMessageAddressingMode.LID ? community.phone_number : attrs.jid,
443
+ lid: mode === WAMessageAddressingMode.LID ? community.jid : attrs.lid,
444
+ admin: attrs.type || null,
445
+ })),
446
+ ephemeralDuration: eph ? Number(ph) : undefined,
447
+ addressingMode: mode,
448
+ };
449
+ return metadata;
450
+ };
451
+ module.exports = {
452
+ makeCommunitiesSocket: makeCommunitiesSocket,
453
+ extractCommunityMetadata: extractCommunityMetadata,
454
+ };