@alannxd/baileys 6.1.4 → 6.1.6

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 (50) hide show
  1. package/LICENSE +4 -1
  2. package/README.md +202 -277
  3. package/lib/Defaults/index.js +1 -1
  4. package/lib/Socket/graphql.js +716 -0
  5. package/lib/Socket/index.js +7 -1
  6. package/lib/Socket/interop.js +463 -0
  7. package/lib/Socket/messages-send.js +7 -6
  8. package/lib/Socket/mex.js +51 -39
  9. package/lib/Socket/newsletter.js +725 -258
  10. package/lib/Socket/privacy.js +318 -0
  11. package/lib/Socket/socket.js +143 -17
  12. package/lib/Socket/username.js +225 -136
  13. package/lib/Store/make-in-memory-store.js +47 -1
  14. package/lib/Types/Mex.js +76 -2
  15. package/lib/Utils/messages-media.js +82 -0
  16. package/lib/Utils/messages.js +86 -2
  17. package/lib/Utils/sticker.js +110 -0
  18. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  19. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  20. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -50
  21. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +55 -52
  22. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +28 -25
  23. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  24. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  25. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  26. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  27. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -36
  28. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  29. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -23
  30. package/lib/WAUSync/Protocols/index.js +12 -6
  31. package/lib/WAUSync/USyncQuery.js +149 -96
  32. package/lib/WAUSync/USyncUser.js +54 -29
  33. package/lib/WAUSync/index.js +3 -4
  34. package/lib/index.js +2 -3
  35. package/package.json +19 -20
  36. package/WAProto/fix-import.js +0 -29
  37. package/lib/Defaults/baileys-version.json +0 -3
  38. package/lib/Defaults/phonenumber-mcc.json +0 -223
  39. package/lib/Signal/Group/queue-job.js +0 -57
  40. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  41. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  42. package/lib/Socket/Client/web-socket-client.js +0 -62
  43. package/lib/Socket/community.js +0 -392
  44. package/lib/Socket/dugong.js +0 -637
  45. package/lib/Socket/registration.js +0 -167
  46. package/lib/Socket/usync.js +0 -69
  47. package/lib/Types/Newsletter.js +0 -38
  48. package/lib/Utils/baileys-event-stream.js +0 -63
  49. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  50. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
@@ -1,12 +1,18 @@
1
1
  import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
2
2
  import { makeCommunitiesSocket } from './communities.js';
3
+ import { makeInteropSocket } from './interop.js'
4
+ import { makePrivacySocket } from './privacy.js'
5
+ import { makeGraphQLSocket } from './graphql.js'
3
6
  // export the last socket layer
4
7
  const makeWASocket = (config) => {
5
8
  const newConfig = {
6
9
  ...DEFAULT_CONNECTION_CONFIG,
7
10
  ...config
8
11
  };
9
- return makeCommunitiesSocket(newConfig);
12
+ const satu = makeCommunitiesSocket(newConfig);
13
+ const dua = makeInteropSocket(satu);
14
+ const tiga = makePrivacySocket(dua);
15
+ return makeGraphQLSocket(tiga);
10
16
  };
11
17
  export default makeWASocket;
12
18
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,463 @@
1
+ import { getBinaryNodeChild, getBinaryNodeChildren, S_WHATSAPP_NET } from '../WABinary/index.js'
2
+ import { executeWMexQuery } from './mex.js'
3
+
4
+ /**
5
+ * w:mex query IDs for interop group and privacy operations.
6
+ *
7
+ * Source: whatsapp-android-mex_client_persist_ids.json (WA 2.26.26.4 APK assets)
8
+ */
9
+ const INTEROP_MEX_QUERY_IDS = {
10
+ CREATE_GROUP: '25726817620301611', // GroupsCreateInteropGroup
11
+ LEAVE_GROUP: '25346167795013271', // LeaveInteropGroup
12
+ ADD_PARTICIPANTS: '25732168276369451', // AddParticipantsToInteropGroup
13
+ QUERY_GROUP_INFO: '32734144032867938', // QueryInteropGroupInfo
14
+ PRIVACY_SETTINGS_QUERY: '24849123668112654', // InteropPrivacySettingsQuery
15
+ PRIVACY_SETTINGS_UPDATE: '25421856497452763', // InteropPrivacySettingsUpdate
16
+ PRIVACY_SETTINGS_WITH_CONTACT_LIST: '24913399124998598' // InteropPrivacySettingWithContactListUpdate
17
+ }
18
+
19
+ /**
20
+ * Known integrator IDs (assigned by WhatsApp).
21
+ * BirdyChat → identifier_type="email"
22
+ * Haiket → identifier_type="pn"
23
+ */
24
+ const INTEGRATOR_BIRDYCHAT = 12
25
+ const INTEGRATOR_HAIKET = 13
26
+
27
+ /**
28
+ * TOS trackable results sent by WA on first interop opt-in.
29
+ * 105 = TOS shown, 160 = TOS accepted.
30
+ */
31
+ const TOS_TRACKABLE_ID = '20240306'
32
+ const TOS_RESULT_SHOWN = '105'
33
+ const TOS_RESULT_ACCEPTED = '160'
34
+
35
+ /** Maximum users per batch lookup (enforced server-side too). */
36
+ const INTEROP_BATCH_MAX = 256
37
+
38
+ export const makeInteropSocket = sock => {
39
+ const { query, generateMessageTag, logger, signalRepository } = sock
40
+
41
+ const mexQuery = (variables, queryId, dataPath) =>
42
+ executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag)
43
+
44
+ /**
45
+ * Fetch all available interop integrators from the server.
46
+ */
47
+ const fetchIntegrators = async () => {
48
+ const result = await query({
49
+ tag: 'iq',
50
+ attrs: {
51
+ type: 'get',
52
+ xmlns: 'w:interop',
53
+ to: S_WHATSAPP_NET
54
+ },
55
+ content: [{ tag: 'integrator', attrs: { fetch: 'all' } }]
56
+ })
57
+ const listNode = getBinaryNodeChild(result, 'integrator_list')
58
+ if (!listNode) return []
59
+ const globalOptedIn = listNode.attrs?.opted_in === 'true'
60
+ return getBinaryNodeChildren(listNode, 'integrator').map(node => {
61
+ const featuresNode = getBinaryNodeChild(node, 'features')
62
+ return {
63
+ id: parseInt(node.attrs.id, 10),
64
+ name: node.attrs.name,
65
+ // "active" | "onboarding" | "removed"
66
+ status: node.attrs.status,
67
+ icon: node.attrs.icon,
68
+ // "email" | "pn" | "username"
69
+ identifierType: node.attrs.identifier_type,
70
+ // Whether we are already opted-in to this integrator
71
+ optedIn: node.attrs.opted_in === 'true' || globalOptedIn,
72
+ features: {
73
+ groupMessaging: featuresNode?.attrs?.group_messaging === 'true'
74
+ }
75
+ }
76
+ })
77
+ }
78
+
79
+ /** Send a single TOS trackable item (shown or accepted). */
80
+ const sendTOSTrackable = async (id, result) => {
81
+ await query({
82
+ tag: 'iq',
83
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'tos' },
84
+ content: [{ tag: 'trackable', attrs: { id, result } }]
85
+ })
86
+ }
87
+
88
+ /**
89
+ * Accept TOS for interop.
90
+ * Sends two trackable items: shown (105) then accepted (160).
91
+ */
92
+ const acceptInteropTOS = async () => {
93
+ await sendTOSTrackable(TOS_TRACKABLE_ID, TOS_RESULT_SHOWN)
94
+ await sendTOSTrackable(TOS_TRACKABLE_ID, TOS_RESULT_ACCEPTED)
95
+ }
96
+
97
+ /**
98
+ * Opt in to a list of integrators (by numeric ID).
99
+ */
100
+ const optInIntegrators = async (integratorIds = [INTEGRATOR_BIRDYCHAT, INTEGRATOR_HAIKET]) => {
101
+ await query({
102
+ tag: 'iq',
103
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
104
+ content: [
105
+ {
106
+ tag: 'opt_integrators',
107
+ attrs: {},
108
+ content: [
109
+ {
110
+ tag: 'integrator_list',
111
+ attrs: {},
112
+ content: integratorIds.map(id => ({
113
+ tag: 'integrator',
114
+ attrs: { id: id.toString() }
115
+ }))
116
+ }
117
+ ]
118
+ }
119
+ ]
120
+ })
121
+ }
122
+
123
+ /**
124
+ * Opt out of a list of integrators (by numeric ID).
125
+ */
126
+ const optOutIntegrators = async (integratorIds = [INTEGRATOR_BIRDYCHAT, INTEGRATOR_HAIKET]) => {
127
+ await query({
128
+ tag: 'iq',
129
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
130
+ content: [
131
+ {
132
+ tag: 'opt_out_integrators',
133
+ attrs: {},
134
+ content: [
135
+ {
136
+ tag: 'integrator_list',
137
+ attrs: {},
138
+ content: integratorIds.map(id => ({
139
+ tag: 'integrator',
140
+ attrs: { id: id.toString() }
141
+ }))
142
+ }
143
+ ]
144
+ }
145
+ ]
146
+ })
147
+ }
148
+
149
+ /**
150
+ * Resolve one or more interop users by external ID in a single IQ.
151
+ */
152
+ const resolveInteropUsers = async users => {
153
+ if (!users || users.length === 0) return []
154
+ if (users.length > INTEROP_BATCH_MAX) {
155
+ throw new Error(`resolveInteropUsers: max ${INTEROP_BATCH_MAX} users per request`)
156
+ }
157
+ const result = await query({
158
+ tag: 'iq',
159
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
160
+ content: [
161
+ {
162
+ tag: 'users',
163
+ attrs: {},
164
+ content: users.map(({ externalId, integratorId }) => ({
165
+ tag: 'user',
166
+ attrs: {
167
+ external_id: externalId,
168
+ integrator_id: integratorId.toString()
169
+ }
170
+ }))
171
+ }
172
+ ]
173
+ })
174
+ const usersNode = getBinaryNodeChild(result, 'users')
175
+ if (!usersNode) return []
176
+ return getBinaryNodeChildren(usersNode, 'user').map(userNode => {
177
+ const errorNode = getBinaryNodeChild(userNode, 'error')
178
+ if (errorNode) {
179
+ return {
180
+ externalId: userNode.attrs.external_id,
181
+ integratorId: parseInt(userNode.attrs.integrator_id, 10),
182
+ error: {
183
+ code: parseInt(errorNode.attrs.code, 10),
184
+ text: errorNode.attrs.text
185
+ }
186
+ }
187
+ }
188
+ return {
189
+ jid: userNode.attrs.jid,
190
+ externalId: userNode.attrs.external_id,
191
+ normalizedExternalId: userNode.attrs.normalized_external_id,
192
+ integratorId: parseInt(userNode.attrs.integrator_id, 10)
193
+ }
194
+ })
195
+ }
196
+
197
+ /**
198
+ * Convenience wrapper: resolve a single interop user.
199
+ */
200
+ const resolveInteropUser = async (externalId, integratorId) => {
201
+ const results = await resolveInteropUsers([{ externalId, integratorId }])
202
+ return results[0]?? null
203
+ }
204
+
205
+ /**
206
+ * Get reachability settings for interop contacts.
207
+ */
208
+ const getReachabilitySettings = async () => {
209
+ const result = await query({
210
+ tag: 'iq',
211
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
212
+ content: [{ tag: 'reachability_settings', attrs: {} }]
213
+ })
214
+ const settingsNode = getBinaryNodeChild(result, 'reachability_settings')
215
+ if (!settingsNode) return null
216
+ return {
217
+ enabled: settingsNode.attrs?.enabled,
218
+ users: getBinaryNodeChildren(settingsNode, 'user').map(n => ({
219
+ externalId: n.attrs.external_id,
220
+ integratorId: parseInt(n.attrs.integrator_id, 10),
221
+ jid: n.attrs.jid
222
+ }))
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Set reachability settings (subscribe to presence) for interop contacts.
228
+ */
229
+ const setReachabilitySettings = async (users, enabled = 'true') => {
230
+ await query({
231
+ tag: 'iq',
232
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
233
+ content: [
234
+ {
235
+ tag: 'reachability_settings',
236
+ attrs: { enabled },
237
+ content: users.map(({ externalId, integratorId }) => ({
238
+ tag: 'user',
239
+ attrs: {
240
+ external_id: externalId,
241
+ integrator_id: integratorId.toString()
242
+ }
243
+ }))
244
+ }
245
+ ]
246
+ })
247
+ }
248
+
249
+ /**
250
+ * Block or unblock an interop user via the w:interop blocklist.
251
+ */
252
+ const updateInteropBlockStatus = async (jid, action) => {
253
+ await query({
254
+ tag: 'iq',
255
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
256
+ content: [
257
+ {
258
+ tag: 'blocklist',
259
+ attrs: {},
260
+ content: [{ tag: 'item', attrs: { action, jid } }]
261
+ }
262
+ ]
263
+ })
264
+ }
265
+
266
+ const blockInteropUser = jid => updateInteropBlockStatus(jid, 'block')
267
+ const unblockInteropUser = jid => updateInteropBlockStatus(jid, 'unblock')
268
+
269
+ /**
270
+ * Report an interop contact as spam.
271
+ */
272
+ const reportInteropSpam = async (jid, spamFlow = 'account_info_block') => {
273
+ await query({
274
+ tag: 'iq',
275
+ attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
276
+ content: [{ tag: 'spam_list', attrs: { jid, spam_flow: spamFlow } }]
277
+ })
278
+ }
279
+
280
+ /**
281
+ * Mark an interop JID as trusted_contact in privacy tokens.
282
+ */
283
+ const trustInteropContact = async jid => {
284
+ const t = Math.floor(Date.now() / 1000).toString()
285
+ await query({
286
+ tag: 'iq',
287
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'privacy', type: 'set' },
288
+ content: [
289
+ {
290
+ tag: 'tokens',
291
+ attrs: {},
292
+ content: [{ tag: 'token', attrs: { jid, type: 'trusted_contact', t } }]
293
+ }
294
+ ]
295
+ })
296
+ }
297
+
298
+ /**
299
+ * Full interop initialization sequence matching WA Web.
300
+ */
301
+ const initInterop = async () => {
302
+ let integrators
303
+ try {
304
+ integrators = await fetchIntegrators()
305
+ } catch (err) {
306
+ logger.warn({ err }, 'interop: failed to fetch integrators')
307
+ return []
308
+ }
309
+ const toOptIn = integrators.filter(i => i.status === 'active' || i.status === 'onboarding')
310
+ if (toOptIn.length === 0) return integrators
311
+ try {
312
+ await acceptInteropTOS()
313
+ } catch (err) {
314
+ logger.warn({ err }, 'interop: failed to accept TOS')
315
+ }
316
+ try {
317
+ await optInIntegrators(toOptIn.map(i => i.id))
318
+ } catch (err) {
319
+ logger.warn({ err }, 'interop: failed to opt-in integrators')
320
+ }
321
+ logger.info({ integrators: toOptIn.map(i => i.name) }, 'interop: initialized')
322
+ return integrators
323
+ }
324
+
325
+ /**
326
+ * Reset the Signal session with an interop contact and force a fresh pkmsg handshake.
327
+ */
328
+ const resetInteropSession = async jid => {
329
+ await signalRepository.deleteSession([jid])
330
+ logger.info({ jid }, '[interop] session reset — next send will use pkmsg')
331
+ }
332
+
333
+ /**
334
+ * Create an interop group via MEX.
335
+ */
336
+ const createInteropGroup = async participants => {
337
+ const result = await mexQuery(
338
+ { input: { participants: participants.map(jid => ({ jid })) } },
339
+ INTEROP_MEX_QUERY_IDS.CREATE_GROUP,
340
+ 'xwa2_interop_group_create'
341
+ )
342
+ logger.info({ participants }, '[interop] group created via MEX')
343
+ return result
344
+ }
345
+
346
+ /**
347
+ * Leave one or more interop groups via MEX.
348
+ */
349
+ const leaveInteropGroup = async jids => {
350
+ const ids = Array.isArray(jids)? jids : [jids]
351
+ const result = await mexQuery(
352
+ { input: { groups_to_leave: ids.map(jid => ({ gid: jid.split('@')[0] })) } },
353
+ INTEROP_MEX_QUERY_IDS.LEAVE_GROUP,
354
+ 'xwa2_interop_group_leave'
355
+ )
356
+ logger.info({ jids: ids }, '[interop] left group(s) via MEX')
357
+ return result
358
+ }
359
+
360
+ /**
361
+ * Add participants to an existing interop group via MEX.
362
+ */
363
+ const addParticipantsToInteropGroup = async (groupJid, participants) => {
364
+ const gid = groupJid.split('@')[0]
365
+ return mexQuery(
366
+ { input: { gid, participants: participants.map(jid => ({ jid })) } },
367
+ INTEROP_MEX_QUERY_IDS.ADD_PARTICIPANTS,
368
+ 'xwa2_interop_add_participants_to_group'
369
+ )
370
+ }
371
+
372
+ /**
373
+ * Query info about an interop group via MEX.
374
+ */
375
+ const queryInteropGroupInfo = async groupJid => {
376
+ const gid = groupJid.split('@')[0]
377
+ return mexQuery({ group_input: { gid } }, INTEROP_MEX_QUERY_IDS.QUERY_GROUP_INFO, 'xwa2_interop_group_query_by_id')
378
+ }
379
+
380
+ /**
381
+ * Update an interop privacy setting via MEX.
382
+ */
383
+ const updateInteropPrivacySetting = async (feature, setting) => {
384
+ return mexQuery(
385
+ { feature, setting },
386
+ INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_UPDATE,
387
+ 'xwa2_interop_privacy_setting_update'
388
+ )
389
+ }
390
+
391
+ /**
392
+ * Update an interop privacy setting with an explicit contact list via MEX.
393
+ */
394
+ const updateInteropPrivacySettingWithContactList = async (
395
+ feature,
396
+ setting,
397
+ contacts,
398
+ contactListType,
399
+ dhash = 'none'
400
+ ) => {
401
+ return mexQuery(
402
+ { feature, setting, contacts, contact_list_type: contactListType, dhash },
403
+ INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_WITH_CONTACT_LIST,
404
+ 'xwa2_interop_privacy_setting_with_contact_list_update'
405
+ )
406
+ }
407
+
408
+ /**
409
+ * Check whether an interop user allows being added to groups (GROUPADD privacy).
410
+ */
411
+ const getInteropGroupAddPrivacy = async (jid, integratorId) => {
412
+ const result = await query({
413
+ tag: 'iq',
414
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
415
+ content: [
416
+ {
417
+ tag: 'privacy',
418
+ attrs: { feature: 'GROUPADD' },
419
+ content: [
420
+ {
421
+ tag: 'user',
422
+ attrs: {
423
+ jid,
424
+ integrator_id: integratorId.toString()
425
+ }
426
+ }
427
+ ]
428
+ }
429
+ ]
430
+ })
431
+ const privacyNode = getBinaryNodeChild(result, 'privacy')
432
+ const userNode = getBinaryNodeChild(privacyNode, 'user')
433
+ return userNode?.attrs?.result === 'allowed'
434
+ }
435
+
436
+ return {
437
+ ...sock,
438
+ fetchIntegrators,
439
+ acceptInteropTOS,
440
+ optInIntegrators,
441
+ optOutIntegrators,
442
+ resolveInteropUser,
443
+ resolveInteropUsers,
444
+ getReachabilitySettings,
445
+ setReachabilitySettings,
446
+ blockInteropUser,
447
+ unblockInteropUser,
448
+ reportInteropSpam,
449
+ trustInteropContact,
450
+ initInterop,
451
+ resetInteropSession,
452
+ createInteropGroup,
453
+ leaveInteropGroup,
454
+ addParticipantsToInteropGroup,
455
+ queryInteropGroupInfo,
456
+ updateInteropPrivacySetting,
457
+ updateInteropPrivacySettingWithContactList,
458
+ getInteropGroupAddPrivacy,
459
+ INTEGRATOR_BIRDYCHAT,
460
+ INTEGRATOR_HAIKET,
461
+ INTEROP_MEX_QUERY_IDS
462
+ }
463
+ }
@@ -2,20 +2,20 @@ import NodeCache from '@cacheable/node-cache';
2
2
  import { Boom } from '@hapi/boom';
3
3
  import { proto } from '../../WAProto/index.js';
4
4
  import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
- import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds, setBotMessageSecret } from '../Utils/index.js';
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateIOSMessageID, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds, setBotMessageSecret } from '../Utils/index.js';
6
6
  import { getUrlInfo } from '../Utils/link-preview.js';
7
7
  import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
8
  import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
9
  import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
10
  import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET, getAdditionalNode, getBinaryNodeFilter, getBinaryFilteredBizBot, isInteropUser } from '../WABinary/index.js';
11
11
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
- import { makeNewsletterSocket } from './newsletter.js';
12
+ import { makeUsernameSocket } from './username.js';
13
13
  import imup from './luxu.js';
14
14
  import * as Utils_1 from '../Utils/index.js';
15
15
  import { randomBytes } from 'crypto';
16
16
  export const makeMessagesSocket = (config) => {
17
17
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount, aiLabel } = config;
18
- const sock = makeNewsletterSocket(config);
18
+ const sock = makeUsernameSocket(config);
19
19
  const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
20
20
  const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
21
21
  /**
@@ -433,10 +433,10 @@ export const makeMessagesSocket = (config) => {
433
433
  message,
434
434
  {
435
435
  messageId: msgId,
436
- participant = false,
436
+ participant = false,
437
437
  additionalAttributes,
438
438
  additionalNodes,
439
- useUserDevicesCache,
439
+ useUserDevicesCache,
440
440
  useCachedGroupMetadata,
441
441
  statusJidList
442
442
  }
@@ -454,7 +454,8 @@ export const makeMessagesSocket = (config) => {
454
454
  const isInterop = isInteropUser(jid)
455
455
  const isGroupOrStatus = isGroup || isStatus
456
456
  const finalJid = jid
457
- msgId = msgId || generateMessageIDV2(meId)
457
+ const iosBros = config.browser[0] === "iOS" || config.browser[1] === "Safari";
458
+ msgId = iosBros ? generateIOSMessageID() : msgId ?? generateMessageIDV2(meId)
458
459
  useUserDevicesCache = useUserDevicesCache!== false
459
460
  useCachedGroupMetadata = useCachedGroupMetadata!== false &&!isStatus
460
461
  const participants = []
package/lib/Socket/mex.js CHANGED
@@ -1,42 +1,54 @@
1
- import { Boom } from '@hapi/boom';
2
- import { getBinaryNodeChild, S_WHATSAPP_NET } from '../WABinary/index.js';
1
+ import { Boom } from '@hapi/boom'
2
+ import { S_WHATSAPP_NET, getBinaryNodeChild } from '../WABinary/index.js'
3
+
3
4
  const wMexQuery = (variables, queryId, query, generateMessageTag) => {
4
- return query({
5
- tag: 'iq',
6
- attrs: {
7
- id: generateMessageTag(),
8
- type: 'get',
9
- to: S_WHATSAPP_NET,
10
- xmlns: 'w:mex'
11
- },
12
- content: [
13
- {
14
- tag: 'query',
15
- attrs: { query_id: queryId },
16
- content: Buffer.from(JSON.stringify({ variables }), 'utf-8')
17
- }
18
- ]
19
- });
20
- };
5
+ return query({
6
+ tag: 'iq',
7
+ attrs: {
8
+ id: generateMessageTag(),
9
+ type: 'get',
10
+ to: S_WHATSAPP_NET,
11
+ xmlns: 'w:mex'
12
+ },
13
+ content: [
14
+ {
15
+ tag: 'query',
16
+ attrs: { query_id: queryId },
17
+ content: Buffer.from(JSON.stringify({ variables }), 'utf-8')
18
+ }
19
+ ]
20
+ })
21
+ }
22
+
21
23
  export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
22
- const result = await wMexQuery(variables, queryId, query, generateMessageTag);
23
- const child = getBinaryNodeChild(result, 'result');
24
- if (child?.content) {
25
- const data = JSON.parse(child.content.toString());
26
- if (data.errors && data.errors.length > 0) {
27
- const errorMessages = data.errors.map((err) => err.message || 'Unknown error').join(', ');
28
- const firstError = data.errors[0];
29
- const errorCode = firstError.extensions?.error_code || 400;
30
- throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError });
31
- }
32
- const response = dataPath ? data?.data?.[dataPath] : data?.data;
33
- if (typeof response !== 'undefined') {
34
- return response;
35
- }
24
+ const result = await wMexQuery(variables, queryId, query, generateMessageTag)
25
+ const child = getBinaryNodeChild(result, 'result')
26
+ if (child?.content) {
27
+ const str = child.content.toString('utf-8').replace(/^\x00+/, '').trim()
28
+ let data
29
+ try {
30
+ data = JSON.parse(str)
31
+ } catch {
32
+ data = str
36
33
  }
37
- const action = (dataPath || '').startsWith('xwa2_')
38
- ? dataPath.substring(5).replace(/_/g, ' ')
39
- : dataPath?.replace(/_/g, ' ');
40
- throw new Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result });
41
- };
42
- //# sourceMappingURL=mex.js.map
34
+ if (typeof data === 'string') {
35
+ return data
36
+ }
37
+ if (data.errors && data.errors.length > 0) {
38
+ const errorMessages = data.errors.map(err => err.message || 'Unknown error').join(', ')
39
+ const firstError = data.errors[0]
40
+ const errorCode = firstError.extensions?.error_code || 400
41
+ throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError })
42
+ }
43
+
44
+ const response = dataPath ? data?.data?.[dataPath] : data?.data
45
+ if (typeof response !== 'undefined') {
46
+ return response
47
+ }
48
+ }
49
+
50
+ const action = (dataPath || '').startsWith('xwa2_')
51
+ ? dataPath.substring(5).replace(/_/g, '')
52
+ : dataPath?.replace(/_/g, '')
53
+ throw new Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result })
54
+ }