@langitdeveloper/baileys 2.0.7 → 2.0.9

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 (126) hide show
  1. package/WAProto/index.js +131281 -59270
  2. package/lib/Defaults/baileys-version.json +3 -1
  3. package/lib/Defaults/index.js +6 -6
  4. package/lib/Function/Download/tiktok.js +19 -0
  5. package/lib/Function/Tools/bypass.js +19 -0
  6. package/lib/Function/index.js +13 -0
  7. package/lib/Signal/libsignal.js +0 -15
  8. package/lib/Socket/chats.js +48 -16
  9. package/lib/Socket/dugong.js +165 -12
  10. package/lib/Socket/messages-send.js +576 -1213
  11. package/lib/Socket/newsletter.js +212 -99
  12. package/lib/Socket/socket.js +1 -1
  13. package/lib/Types/index.js +0 -2
  14. package/lib/Utils/generics.js +79 -4
  15. package/lib/Utils/index.js +0 -4
  16. package/lib/Utils/messages.js +4 -33
  17. package/lib/WAUSync/Protocols/index.js +0 -2
  18. package/lib/index.js +10 -12
  19. package/package.json +7 -6
  20. package/lib/Defaults/index.d.ts +0 -53
  21. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  22. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  23. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  24. package/lib/Signal/Group/index.d.ts +0 -11
  25. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  26. package/lib/Signal/Group/queue-job.d.ts +0 -1
  27. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  28. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  29. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  30. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  31. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  32. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  33. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  34. package/lib/Signal/libsignal.d.ts +0 -3
  35. package/lib/Signal/lid-mapping.js +0 -164
  36. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  37. package/lib/Socket/Client/index.d.ts +0 -3
  38. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  39. package/lib/Socket/Client/types.js +0 -12
  40. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  41. package/lib/Socket/Client/websocket.js +0 -67
  42. package/lib/Socket/business.d.ts +0 -171
  43. package/lib/Socket/chats.d.ts +0 -267
  44. package/lib/Socket/community.js +0 -454
  45. package/lib/Socket/dugong.d.ts +0 -254
  46. package/lib/Socket/groups.d.ts +0 -115
  47. package/lib/Socket/index.d.ts +0 -173
  48. package/lib/Socket/messages-recv.d.ts +0 -161
  49. package/lib/Socket/messages-send.d.ts +0 -149
  50. package/lib/Socket/mex.js +0 -54
  51. package/lib/Socket/newsletter.d.ts +0 -134
  52. package/lib/Socket/registration.d.ts +0 -267
  53. package/lib/Socket/socket.d.ts +0 -43
  54. package/lib/Socket/usync.d.ts +0 -36
  55. package/lib/Store/index.d.ts +0 -3
  56. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  57. package/lib/Store/make-in-memory-store.d.ts +0 -118
  58. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  59. package/lib/Store/object-repository.d.ts +0 -10
  60. package/lib/Types/Auth.d.ts +0 -110
  61. package/lib/Types/Bussines.js +0 -2
  62. package/lib/Types/Call.d.ts +0 -13
  63. package/lib/Types/Chat.d.ts +0 -102
  64. package/lib/Types/Contact.d.ts +0 -19
  65. package/lib/Types/Events.d.ts +0 -157
  66. package/lib/Types/GroupMetadata.d.ts +0 -55
  67. package/lib/Types/Label.d.ts +0 -35
  68. package/lib/Types/LabelAssociation.d.ts +0 -29
  69. package/lib/Types/Message.d.ts +0 -273
  70. package/lib/Types/MexUpdates.js +0 -15
  71. package/lib/Types/Newsletter.d.ts +0 -103
  72. package/lib/Types/Product.d.ts +0 -78
  73. package/lib/Types/Signal.d.ts +0 -57
  74. package/lib/Types/Socket.d.ts +0 -111
  75. package/lib/Types/State.d.ts +0 -27
  76. package/lib/Types/USync.d.ts +0 -25
  77. package/lib/Types/index.d.ts +0 -57
  78. package/lib/Utils/auth-utils.d.ts +0 -18
  79. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  80. package/lib/Utils/browser-utils.js +0 -29
  81. package/lib/Utils/business.d.ts +0 -22
  82. package/lib/Utils/chat-utils.d.ts +0 -71
  83. package/lib/Utils/crypto.d.ts +0 -41
  84. package/lib/Utils/decode-wa-message.d.ts +0 -19
  85. package/lib/Utils/event-buffer.d.ts +0 -35
  86. package/lib/Utils/generics.d.ts +0 -92
  87. package/lib/Utils/history.d.ts +0 -15
  88. package/lib/Utils/index.d.ts +0 -17
  89. package/lib/Utils/link-preview.d.ts +0 -21
  90. package/lib/Utils/logger.d.ts +0 -4
  91. package/lib/Utils/lt-hash.d.ts +0 -12
  92. package/lib/Utils/make-mutex.d.ts +0 -7
  93. package/lib/Utils/message-retry-manager.js +0 -134
  94. package/lib/Utils/messages-media.d.ts +0 -116
  95. package/lib/Utils/messages.d.ts +0 -77
  96. package/lib/Utils/noise-handler.d.ts +0 -21
  97. package/lib/Utils/pre-key-manager.js +0 -86
  98. package/lib/Utils/process-message.d.ts +0 -41
  99. package/lib/Utils/signal.d.ts +0 -32
  100. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  101. package/lib/Utils/validate-connection.d.ts +0 -11
  102. package/lib/Utils/vialeys-event-stream.js +0 -41
  103. package/lib/WABinary/constants.d.ts +0 -30
  104. package/lib/WABinary/decode.d.ts +0 -7
  105. package/lib/WABinary/encode.d.ts +0 -3
  106. package/lib/WABinary/generic-utils.d.ts +0 -17
  107. package/lib/WABinary/index.d.ts +0 -5
  108. package/lib/WABinary/jid-utils.d.ts +0 -31
  109. package/lib/WABinary/types.d.ts +0 -18
  110. package/lib/WAM/BinaryInfo.d.ts +0 -17
  111. package/lib/WAM/constants.d.ts +0 -38
  112. package/lib/WAM/encode.d.ts +0 -3
  113. package/lib/WAM/index.d.ts +0 -3
  114. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -62
  115. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  116. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  117. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  118. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -24
  119. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  120. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  121. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  122. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  123. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  124. package/lib/WAUSync/USyncUser.d.ts +0 -12
  125. package/lib/WAUSync/index.d.ts +0 -3
  126. package/lib/index.d.ts +0 -12
@@ -1,1468 +1,831 @@
1
- "use strict";
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const { default: NodeCache } = require("@cacheable/node-cache");
4
- const { Boom: Boom } = require("@hapi/boom");
5
- const { randomBytes: randomBytes } = require("crypto");
6
- const { proto: proto } = require("../../WAProto");
7
- const {
8
- DEFAULT_CACHE_TTLS: DEFAULT_CACHE_TTLS,
9
- WA_DEFAULT_EPHEMERAL: WA_DEFAULT_EPHEMERAL,
10
- } = require("../Defaults");
11
- const {
12
- delay: delay,
13
- assertMediaContent: assertMediaContent,
14
- bindWaitForEvent: bindWaitForEvent,
15
- decryptMediaRetryData: decryptMediaRetryData,
16
- encodeNewsletterMessage: encodeNewsletterMessage,
17
- encodeSignedDeviceIdentity: encodeSignedDeviceIdentity,
18
- encodeWAMessage: encodeWAMessage,
19
- encryptMediaRetryRequest: encryptMediaRetryRequest,
20
- extractDeviceJids: extractDeviceJids,
21
- generateMessageID: generateMessageID,
22
- generateParticipantHashV2: generateParticipantHashV2,
23
- generateWAMessage: generateWAMessage,
24
- generateWAMessageFromContent: generateWAMessageFromContent,
25
- getStatusCodeForMediaRetry: getStatusCodeForMediaRetry,
26
- getUrlFromDirectPath: getUrlFromDirectPath,
27
- getWAUploadToServer: getWAUploadToServer,
28
- MessageRetryManager: MessageRetryManager,
29
- normalizeMessageContent: normalizeMessageContent,
30
- parseAndInjectE2ESessions: parseAndInjectE2ESessions,
31
- unixTimestampSeconds: unixTimestampSeconds,
32
- prepareAlbumMessageContent: prepareAlbumMessageContent,
33
- aggregateMessageKeysNotFromMe: aggregateMessageKeysNotFromMe,
34
- } = require("../Utils");
35
- const { WAMessageAddressingMode: WAMessageAddressingMode } = require("../Types");
36
- const {
37
- areJidsSameUser: areJidsSameUser,
38
- getBinaryNodeChild: getBinaryNodeChild,
39
- getBinaryNodeChildren: getBinaryNodeChildren,
40
- getBinaryFilteredBizBot: getBinaryFilteredBizBot,
41
- getBinaryFilteredButtons: getBinaryFilteredButtons,
42
- isHostedLidUser: isHostedLidUser,
43
- isHostedPnUser: isHostedPnUser,
44
- isJidNewsletter: isJidNewsletter,
45
- isJidGroup: isJidGroup,
46
- isLidUser: isLidUser,
47
- isPnUser: isPnUser,
48
- jidDecode: jidDecode,
49
- jidEncode: jidEncode,
50
- jidNormalizedUser: jidNormalizedUser,
51
- STORIES_JID: STORIES_JID,
52
- S_WHATSAPP_NET: S_WHATSAPP_NET,
53
- } = require("../WABinary");
54
- const { USyncUser: USyncUser, USyncQuery: USyncQuery } = require("../WAUSync");
55
- const { makeNewsletterSocket: makeNewsletterSocket } = require("./newsletter");
56
- const { getUrlInfo: getUrlInfo } = require("../Utils/link-preview");
57
- const { makeKeyedMutex: makeKeyedMutex } = require("../Utils/make-mutex");
6
+ exports.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Types_1 = require("../Types");
12
+ const Utils_1 = require("../Utils");
13
+ const link_preview_1 = require("../Utils/link-preview");
14
+ const WABinary_1 = require("../WABinary");
15
+ const newsletter_1 = require("./newsletter");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const kikyy = require('./dugong');
58
18
  const makeMessagesSocket = (config) => {
59
19
  const {
60
- logger: logger,
61
- linkPreviewImageThumbnailWidth: linkPreviewImageThumbnailWidth,
62
- generateHighQualityLinkPreview: generateHighQualityLinkPreview,
63
- options: httpRequestOptions,
64
- patchMessageBeforeSending: patchMessageBeforeSending,
65
- cachedGroupMetadata: cachedGroupMetadata,
66
- enableRecentMessageCache: enableRecentMessageCache,
67
- maxMsgRetryCount: maxMsgRetryCount,
20
+ logger,
21
+ linkPreviewImageThumbnailWidth,
22
+ generateHighQualityLinkPreview,
23
+ options: axiosOptions,
24
+ patchMessageBeforeSending
68
25
  } = config;
69
- const conn = makeNewsletterSocket(config);
26
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
70
27
  const {
71
- ev: ev,
72
- authState: authState,
73
- messageMutex: messageMutex,
74
- signalRepository: signalRepository,
75
- upsertMessage: upsertMessage,
76
- createCallLink: createCallLink,
77
- query: query,
78
- fetchPrivacySettings: fetchPrivacySettings,
79
- sendNode: sendNode,
80
- groupQuery: groupQuery,
81
- groupMetadata: groupMetadata,
82
- groupToggleEphemeral: groupToggleEphemeral,
83
- executeUSyncQuery: executeUSyncQuery,
84
- newsletterMetadata: newsletterMetadata,
85
- } = conn;
86
- const userDevicesCache =
87
- config.userDevicesCache ||
88
- new NodeCache({
89
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
90
- useClones: false,
91
- });
92
- const peerSessionsCache = new NodeCache({
93
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
94
- useClones: false,
28
+ ev,
29
+ authState,
30
+ processingMutex,
31
+ signalRepository,
32
+ upsertMessage,
33
+ query,
34
+ fetchPrivacySettings,
35
+ sendNode,
36
+ groupMetadata,
37
+ groupToggleEphemeral,
38
+ executeUSyncQuery
39
+ } = sock;
40
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
41
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
42
+ useClones: false
95
43
  });
96
- const messageRetryManager = enableRecentMessageCache
97
- ? new MessageRetryManager(logger, maxMsgRetryCount)
98
- : null;
99
- const encryptionMutex = makeKeyedMutex();
100
44
  let mediaConn;
101
45
  const refreshMediaConn = async (forceGet = false) => {
102
46
  const media = await mediaConn;
103
- if (
104
- !media ||
105
- forceGet ||
106
- new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1e3
107
- ) {
47
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
108
48
  mediaConn = (async () => {
109
49
  const result = await query({
110
- tag: "iq",
111
- attrs: { type: "set", xmlns: "w:m", to: S_WHATSAPP_NET },
112
- content: [{ tag: "media_conn", attrs: {} }],
50
+ tag: 'iq',
51
+ attrs: {
52
+ type: 'set',
53
+ xmlns: 'w:m',
54
+ to: WABinary_1.S_WHATSAPP_NET,
55
+ },
56
+ content: [{ tag: 'media_conn', attrs: {} }]
113
57
  });
114
- const mediaConnNode = getBinaryNodeChild(result, "media_conn");
58
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn');
115
59
  const node = {
116
- hosts: getBinaryNodeChildren(mediaConnNode, "host").map(({ attrs: attrs }) => ({
60
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
117
61
  hostname: attrs.hostname,
118
62
  maxContentLengthBytes: +attrs.maxContentLengthBytes,
119
63
  })),
120
64
  auth: mediaConnNode.attrs.auth,
121
65
  ttl: +mediaConnNode.attrs.ttl,
122
- fetchDate: new Date(),
66
+ fetchDate: new Date()
123
67
  };
124
- logger.debug("fetched media conn");
68
+ logger.debug('fetched media conn');
125
69
  return node;
126
70
  })();
127
71
  }
128
72
  return mediaConn;
129
73
  };
130
74
  const sendReceipt = async (jid, participant, messageIds, type) => {
131
- if (!messageIds || messageIds.length === 0) {
132
- throw new Boom("missing ids in receipt");
133
- }
134
- const node = { tag: "receipt", attrs: { id: messageIds[0] } };
135
- const isReadReceipt = type === "read" || type === "read-self";
75
+ const node = {
76
+ tag: 'receipt',
77
+ attrs: {
78
+ id: messageIds[0],
79
+ },
80
+ };
81
+ const isReadReceipt = type === 'read' || type === 'read-self';
136
82
  if (isReadReceipt) {
137
- node.attrs.t = unixTimestampSeconds().toString();
83
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
138
84
  }
139
- if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
85
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
140
86
  node.attrs.recipient = jid;
141
87
  node.attrs.to = participant;
142
- } else {
88
+ }
89
+ else {
143
90
  node.attrs.to = jid;
144
91
  if (participant) {
145
92
  node.attrs.participant = participant;
146
93
  }
147
94
  }
148
95
  if (type) {
149
- node.attrs.type = type;
96
+ node.attrs.type = WABinary_1.isJidNewsLetter(jid) ? 'read-self' : type;
150
97
  }
151
98
  const remainingMessageIds = messageIds.slice(1);
152
99
  if (remainingMessageIds.length) {
153
100
  node.content = [
154
101
  {
155
- tag: "list",
102
+ tag: 'list',
156
103
  attrs: {},
157
- content: remainingMessageIds.map((id) => ({
158
- tag: "item",
159
- attrs: { id: id },
160
- })),
161
- },
104
+ content: remainingMessageIds.map(id => ({
105
+ tag: 'item',
106
+ attrs: { id }
107
+ }))
108
+ }
162
109
  ];
163
110
  }
164
- logger.debug({ attrs: node.attrs, messageIds: messageIds }, "sending receipt for messages");
111
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
165
112
  await sendNode(node);
166
113
  };
167
114
  const sendReceipts = async (keys, type) => {
168
- const recps = aggregateMessageKeysNotFromMe(keys);
169
- for (const { jid: jid, participant: participant, messageIds: messageIds } of recps) {
115
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
116
+ for (const { jid, participant, messageIds } of recps) {
170
117
  await sendReceipt(jid, participant, messageIds, type);
171
118
  }
172
119
  };
173
120
  const readMessages = async (keys) => {
174
121
  const privacySettings = await fetchPrivacySettings();
175
- const readType = privacySettings.readreceipts === "all" ? "read" : "read-self";
122
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
176
123
  await sendReceipts(keys, readType);
177
124
  };
178
125
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
179
- const deviceResults = [];
126
+ const deviceResults = []
180
127
  if (!useCache) {
181
- logger.debug("not using cache for devices");
128
+ logger.debug('not using cache for devices')
182
129
  }
183
- const toFetch = [];
184
- const jidsWithUser = jids
185
- .map((jid) => {
186
- const decoded = jidDecode(jid);
187
- const user = decoded?.user;
188
- const device = decoded?.device;
189
- const isExplicitDevice = typeof device === "number" && device >= 0;
190
- if (isExplicitDevice && user) {
191
- deviceResults.push({ user: user, device: device, jid: jid });
192
- return null;
193
- }
194
- jid = jidNormalizedUser(jid);
195
- return { jid: jid, user: user };
196
- })
197
- .filter((jid) => jid !== null);
198
- let mgetDevices;
199
- if (useCache && userDevicesCache.mget) {
200
- const usersToFetch = jidsWithUser.map((j) => j?.user).filter(Boolean);
201
- mgetDevices = await userDevicesCache.mget(usersToFetch);
202
- }
203
- for (const { jid: jid, user: user } of jidsWithUser) {
130
+ const toFetch = []
131
+ jids = Array.from(new Set(jids))
132
+ for (let jid of jids) {
133
+ const user = WABinary_1.jidDecode(jid)?.user
134
+ jid = WABinary_1.jidNormalizedUser(jid)
204
135
  if (useCache) {
205
- const devices =
206
- mgetDevices?.[user] ||
207
- (userDevicesCache.mget ? undefined : await userDevicesCache.get(user));
136
+ const devices = userDevicesCache.get(user)
208
137
  if (devices) {
209
- const devicesWithJid = devices.map((d) => ({
210
- ...d,
211
- jid: jidEncode(d.user, d.server, d.device),
212
- }));
213
- deviceResults.push(...devicesWithJid);
214
- logger.trace({ user: user }, "using cache for devices");
215
- } else {
216
- toFetch.push(jid);
138
+ deviceResults.push(...devices)
139
+ logger.trace({ user }, 'using cache for devices')
140
+ }
141
+ else {
142
+ toFetch.push(jid)
217
143
  }
218
- } else {
219
- toFetch.push(jid);
144
+ }
145
+ else {
146
+ toFetch.push(jid)
220
147
  }
221
148
  }
222
149
  if (!toFetch.length) {
223
- return deviceResults;
150
+ return deviceResults
224
151
  }
225
- const requestedLidUsers = new Set();
226
- for (const jid of toFetch) {
227
- if (isLidUser(jid) || isHostedLidUser(jid)) {
228
- const user = jidDecode(jid)?.user;
229
- if (user) requestedLidUsers.add(user);
230
- }
231
- }
232
- const query = new USyncQuery()
233
- .withContext("message")
152
+ const query = new WAUSync_1.USyncQuery()
153
+ .withContext('message')
234
154
  .withDeviceProtocol()
235
- .withLIDProtocol();
236
155
  for (const jid of toFetch) {
237
- query.withUser(new USyncUser().withId(jid));
156
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
238
157
  }
239
- const result = await executeUSyncQuery(query);
158
+ const result = await executeUSyncQuery(query)
240
159
  if (result) {
241
- const lidResults = result.list.filter((a) => !!a.lid);
242
- if (lidResults.length > 0) {
243
- logger.trace("Storing LID maps from device call");
244
- await signalRepository.lidMapping.storeLIDPNMappings(
245
- lidResults.map((a) => ({ lid: a.lid, pn: a.id }))
246
- );
247
- try {
248
- const lids = lidResults.map((a) => a.lid);
249
- if (lids.length) {
250
- await assertSessions(lids, true);
251
- }
252
- } catch (e) {
253
- logger.warn(
254
- { e: e, count: lidResults.length },
255
- "failed to assert sessions for newly mapped LIDs"
256
- );
257
- }
258
- }
259
- const extracted = extractDeviceJids(
260
- result?.list,
261
- authState.creds.me.id,
262
- authState.creds.me.lid,
263
- ignoreZeroDevices
264
- );
265
- const deviceMap = {};
160
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
161
+ const deviceMap = {}
266
162
  for (const item of extracted) {
267
- deviceMap[item.user] = deviceMap[item.user] || [];
268
- deviceMap[item.user]?.push(item);
163
+ deviceMap[item.user] = deviceMap[item.user] || []
164
+ deviceMap[item.user].push(item)
165
+ deviceResults.push(item)
269
166
  }
270
- for (const [user, userDevices] of Object.entries(deviceMap)) {
271
- const isLidUser = requestedLidUsers.has(user);
272
- for (const item of userDevices) {
273
- const finalJid = isLidUser
274
- ? jidEncode(user, item.server, item.device)
275
- : jidEncode(item.user, item.server, item.device);
276
- deviceResults.push({ ...item, jid: finalJid });
277
- logger.debug(
278
- {
279
- user: item.user,
280
- device: item.device,
281
- finalJid: finalJid,
282
- usedLid: isLidUser,
283
- },
284
- "Processed device with LID priority"
285
- );
286
- }
287
- }
288
- if (userDevicesCache.mset) {
289
- await userDevicesCache.mset(
290
- Object.entries(deviceMap).map(([key, value]) => ({
291
- key: key,
292
- value: value,
293
- }))
294
- );
295
- } else {
296
- for (const key in deviceMap) {
297
- if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key]);
298
- }
299
- }
300
- const userDeviceUpdates = {};
301
- for (const [userId, devices] of Object.entries(deviceMap)) {
302
- if (devices && devices.length > 0) {
303
- userDeviceUpdates[userId] = devices.map((d) => d.device?.toString() || "0");
304
- }
305
- }
306
- if (Object.keys(userDeviceUpdates).length > 0) {
307
- try {
308
- await authState.keys.set({ "device-list": userDeviceUpdates });
309
- logger.debug(
310
- { userCount: Object.keys(userDeviceUpdates).length },
311
- "stored user device lists for bulk migration"
312
- );
313
- } catch (error) {
314
- logger.warn({ error: error }, "failed to store user device lists");
315
- }
167
+ for (const key in deviceMap) {
168
+ userDevicesCache.set(key, deviceMap[key])
316
169
  }
317
170
  }
318
- return deviceResults;
319
- };
320
- const updateMemberLabel = (jid, memberLabel) => {
321
- if (!isJidGroup(jid)) {
322
- throw new Error("Jid must a group!");
323
- }
324
- const protocolMessage = {
325
- protocolMessage: {
326
- type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
327
- memberLabel: {
328
- label: memberLabel?.slice(0, 30),
329
- labelTimestamp: unixTimestampSeconds(),
330
- },
331
- },
332
- };
333
- return relayMessage(jid, protocolMessage, {
334
- additionalNodes: [
335
- {
336
- tag: "meta",
337
- attrs: { tag_reason: "user_update", appdata: "member_tag" },
338
- },
339
- ],
340
- });
341
- };
171
+ return deviceResults
172
+ }
342
173
  const assertSessions = async (jids, force) => {
343
174
  let didFetchNewSession = false;
344
- const uniqueJids = [...new Set(jids)];
345
- const jidsRequiringFetch = [];
346
- logger.debug({ jids: jids }, "assertSessions call with jids");
347
- for (const jid of uniqueJids) {
348
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
349
- const cachedSession = peerSessionsCache.get(signalId);
350
- if (cachedSession !== undefined) {
351
- if (cachedSession && !force) {
352
- continue;
353
- }
354
- } else {
355
- const sessionValidation = await signalRepository.validateSession(jid);
356
- const hasSession = sessionValidation.exists;
357
- peerSessionsCache.set(signalId, hasSession);
358
- if (hasSession && !force) {
359
- continue;
175
+ let jidsRequiringFetch = [];
176
+ if (force) {
177
+ jidsRequiringFetch = jids;
178
+ }
179
+ else {
180
+ const addrs = jids.map(jid => (signalRepository
181
+ .jidToSignalProtocolAddress(jid)));
182
+ const sessions = await authState.keys.get('session', addrs);
183
+ for (const jid of jids) {
184
+ const signalId = signalRepository
185
+ .jidToSignalProtocolAddress(jid);
186
+ if (!sessions[signalId]) {
187
+ jidsRequiringFetch.push(jid);
360
188
  }
361
189
  }
362
- jidsRequiringFetch.push(jid);
363
190
  }
364
191
  if (jidsRequiringFetch.length) {
365
- const wireJids = [
366
- ...jidsRequiringFetch.filter((jid) => !!isLidUser(jid) || !!isHostedLidUser(jid)),
367
- ...(
368
- (await signalRepository.lidMapping.getLIDsForPNs(
369
- jidsRequiringFetch.filter((jid) => !!isPnUser(jid) || !!isHostedPnUser(jid))
370
- )) || []
371
- ).map((a) => a.lid),
372
- ];
373
- logger.debug(
374
- { jidsRequiringFetch: jidsRequiringFetch, wireJids: wireJids },
375
- "fetching sessions"
376
- );
192
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
377
193
  const result = await query({
378
- tag: "iq",
379
- attrs: { xmlns: "encrypt", type: "get", to: S_WHATSAPP_NET },
194
+ tag: 'iq',
195
+ attrs: {
196
+ xmlns: 'encrypt',
197
+ type: 'get',
198
+ to: WABinary_1.S_WHATSAPP_NET,
199
+ },
380
200
  content: [
381
201
  {
382
- tag: "key",
202
+ tag: 'key',
383
203
  attrs: {},
384
- content: wireJids.map((jid) => {
385
- const attrs = { jid: jid };
386
- if (force) attrs.reason = "identity";
387
- return { tag: "user", attrs: attrs };
388
- }),
389
- },
390
- ],
204
+ content: jidsRequiringFetch.map(jid => ({
205
+ tag: 'user',
206
+ attrs: { jid },
207
+ }))
208
+ }
209
+ ]
391
210
  });
392
- await parseAndInjectE2ESessions(result, signalRepository);
211
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
393
212
  didFetchNewSession = true;
394
- for (const wireJid of wireJids) {
395
- const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
396
- peerSessionsCache.set(signalId, true);
397
- }
398
213
  }
399
214
  return didFetchNewSession;
400
215
  };
401
216
  const sendPeerDataOperationMessage = async (pdoMessage) => {
402
217
  if (!authState.creds.me?.id) {
403
- throw new Boom("Not authenticated");
218
+ throw new boom_1.Boom('Not authenticated')
404
219
  }
405
220
  const protocolMessage = {
406
221
  protocolMessage: {
407
222
  peerDataOperationRequestMessage: pdoMessage,
408
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE,
409
- },
223
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
224
+ }
410
225
  };
411
- const meJid = jidNormalizedUser(authState.creds.me.id);
226
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
412
227
  const msgId = await relayMessage(meJid, protocolMessage, {
413
- additionalAttributes: { category: "peer", push_priority: "high_force" },
414
- additionalNodes: [{ tag: "meta", attrs: { appdata: "default" } }],
228
+ additionalAttributes: {
229
+ category: 'peer',
230
+ push_priority: 'high_force',
231
+ },
415
232
  });
416
233
  return msgId;
417
234
  };
418
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
419
- if (!recipientJids.length) {
420
- return { nodes: [], shouldIncludeDeviceIdentity: false };
421
- }
422
- const patched = await patchMessageBeforeSending(message, recipientJids);
423
- const patchedMessages = Array.isArray(patched)
424
- ? patched
425
- : recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
235
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
236
+ const patched = await patchMessageBeforeSending(message, jids);
237
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
426
238
  let shouldIncludeDeviceIdentity = false;
427
- const meId = authState.creds.me.id;
428
- const meLid = authState.creds.me?.lid;
429
- const meLidUser = meLid ? jidDecode(meLid)?.user : null;
430
- const encryptionPromises = patchedMessages.map(
431
- async ({ recipientJid: jid, message: patchedMessage }) => {
432
- if (!jid) return null;
433
- let msgToEncrypt = patchedMessage;
434
- if (dsmMessage) {
435
- const { user: targetUser } = jidDecode(jid);
436
- const { user: ownPnUser } = jidDecode(meId);
437
- const ownLidUser = meLidUser;
438
- const isOwnUser =
439
- targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
440
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
441
- if (isOwnUser && !isExactSenderDevice) {
442
- msgToEncrypt = dsmMessage;
443
- logger.debug(
444
- { jid: jid, targetUser: targetUser },
445
- "Using DSM for own device"
446
- );
447
- }
448
- }
449
- const bytes = encodeWAMessage(msgToEncrypt);
450
- const mutexKey = jid;
451
- const node = await encryptionMutex.mutex(mutexKey, async () => {
452
- const { type: type, ciphertext: ciphertext } =
453
- await signalRepository.encryptMessage({ jid: jid, data: bytes });
454
- if (type === "pkmsg") {
455
- shouldIncludeDeviceIdentity = true;
456
- }
457
- return {
458
- tag: "to",
459
- attrs: { jid: jid },
460
- content: [
461
- {
462
- tag: "enc",
463
- attrs: { v: "2", type: type, ...(extraAttrs || {}) },
464
- content: ciphertext,
465
- },
466
- ],
467
- };
468
- });
469
- return node;
470
- }
471
- );
472
- const nodes = (await Promise.all(encryptionPromises)).filter((node) => node !== null);
473
- return {
474
- nodes: nodes,
475
- shouldIncludeDeviceIdentity: shouldIncludeDeviceIdentity,
476
- };
477
- };
478
- const profilePictureUrl = async (jid) => {
479
- if (isJidNewsletter(jid)) {
480
- const metadata = await conn.newsletterMetadata("JID", jid);
481
- return getUrlFromDirectPath(metadata.thread_metadata.picture?.direct_path || "");
482
- } else {
483
- const result = await query({
484
- tag: "iq",
485
- attrs: {
486
- target: jidNormalizedUser(jid),
487
- to: S_WHATSAPP_NET,
488
- type: "get",
489
- xmlns: "w:profile:picture",
490
- },
491
- content: [{ tag: "picture", attrs: { type: "image", query: "url" } }],
492
- });
493
- const child = getBinaryNodeChild(result, "picture");
494
- return child?.attrs?.url || null;
495
- }
239
+ const nodes = await Promise.all(jids.map(async (jid) => {
240
+ const { type, ciphertext } = await signalRepository
241
+ .encryptMessage({ jid, data: bytes });
242
+ if (type === 'pkmsg') {
243
+ shouldIncludeDeviceIdentity = true;
244
+ }
245
+ const node = {
246
+ tag: 'to',
247
+ attrs: { jid },
248
+ content: [{
249
+ tag: 'enc',
250
+ attrs: {
251
+ v: '2',
252
+ type,
253
+ ...extraAttrs || {}
254
+ },
255
+ content: ciphertext
256
+ }]
257
+ };
258
+ return node;
259
+ }));
260
+ return { nodes, shouldIncludeDeviceIdentity };
496
261
  };
497
- const relayMessage = async (
498
- jid,
499
- message,
500
- {
501
- messageId: msgId,
502
- participant: participant,
503
- additionalAttributes: additionalAttributes,
504
- useUserDevicesCache: useUserDevicesCache,
505
- useCachedGroupMetadata: useCachedGroupMetadata,
506
- statusJidList: statusJidList,
507
- additionalNodes: additionalNodes,
508
- AI: AI = false,
509
- }
510
- ) => {
262
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList, AI = true }) => {
511
263
  const meId = authState.creds.me.id;
512
- const meLid = authState.creds.me?.lid;
513
- const isRetryResend = Boolean(participant?.jid);
514
- let shouldIncludeDeviceIdentity = isRetryResend;
515
- let didPushAdditional = false;
516
- const statusJid = "status@broadcast";
517
- const { user: user, server: server } = jidDecode(jid);
518
- const isGroup = server === "g.us";
264
+ let shouldIncludeDeviceIdentity = false;
265
+ let didPushAdditional = false
266
+ const { user, server } = WABinary_1.jidDecode(jid);
267
+ const statusJid = 'status@broadcast';
268
+ const isGroup = server === 'g.us';
519
269
  const isStatus = jid === statusJid;
520
- const isLid = server === "lid";
521
- const isNewsletter = server === "newsletter";
522
- const isGroupOrStatus = isGroup || isStatus;
523
- const finalJid = jid;
524
- msgId = msgId || generateMessageID(meId);
270
+ const isLid = server === 'lid';
271
+ const isPrivate = server === 's.whatsapp.net'
272
+ const isNewsletter = server === 'newsletter';
273
+ msgId = msgId || (0, Utils_1.generateMessageID)();
525
274
  useUserDevicesCache = useUserDevicesCache !== false;
526
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
275
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
527
276
  const participants = [];
528
- const destinationJid = !isStatus ? finalJid : statusJid;
277
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
529
278
  const binaryNodeContent = [];
530
279
  const devices = [];
531
280
  const meMsg = {
532
- deviceSentMessage: { destinationJid: destinationJid, message: message },
533
- messageContextInfo: message.messageContextInfo,
281
+ deviceSentMessage: {
282
+ destinationJid,
283
+ message
284
+ }
534
285
  };
535
- const extraAttrs = {};
536
- const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/;
537
- const messages = normalizeMessageContent(message);
286
+ const extraAttrs = {}
287
+ const messages = Utils_1.normalizeMessageContent(message);
538
288
  const buttonType = getButtonType(messages);
539
- const pollMessage =
540
- messages.pollCreationMessage ||
541
- messages.pollCreationMessageV2 ||
542
- messages.pollCreationMessageV3;
543
289
  if (participant) {
544
290
  if (!isGroup && !isStatus) {
545
- additionalAttributes = {
546
- ...additionalAttributes,
547
- device_fanout: "false",
548
- };
291
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
549
292
  }
550
- const { user: user, device: device } = jidDecode(participant.jid);
551
- devices.push({ user: user, device: device, jid: participant.jid });
293
+ const { user, device } = WABinary_1.jidDecode(participant.jid);
294
+ devices.push({ user, device });
552
295
  }
553
296
  await authState.keys.transaction(async () => {
554
- const mediaType = getMediaType(message);
297
+ const mediaType = getMediaType(messages);
555
298
  if (mediaType) {
556
- extraAttrs["mediatype"] = mediaType;
299
+ extraAttrs['mediatype'] = mediaType
557
300
  }
558
- if (isNewsletter) {
559
-
560
- const patched = patchMessageBeforeSending
561
- ? await patchMessageBeforeSending(message, [])
562
- : message
563
-
564
- const mediaType = getMediaType(patched)
565
-
566
- if (mediaType) {
567
- extraAttrs["mediatype"] = mediaType
568
- }
569
-
570
- if (
571
- patched.interactiveMessage &&
572
- !extraAttrs["mediatype"]
573
- ) {
574
- extraAttrs["mediatype"] = "interactive"
575
- }
576
-
577
- const bytes = encodeNewsletterMessage(patched)
578
-
579
- binaryNodeContent.push({
580
- tag: "plaintext",
581
- attrs: extraAttrs,
582
- content: bytes
583
- })
584
-
585
- const stanza = {
586
- tag: "message",
587
- attrs: {
588
- to: jid,
589
- id: msgId,
590
- type: getTypeMessage(patched),
591
- ...(additionalAttributes || {}),
592
- },
593
- content: binaryNodeContent,
594
- }
595
-
596
- logger.debug(
597
- {
598
- msgId,
599
- mediaType,
600
- extraAttrs
601
- },
602
- `sending newsletter message to ${jid}`
603
- )
604
-
605
- await sendNode(stanza)
606
-
607
- return
608
- }
609
- if (
610
- messages.pinInChatMessage ||
611
- messages.keepInChatMessage ||
612
- message.reactionMessage ||
613
- message.protocolMessage?.editedMessage
614
- ) {
615
- extraAttrs["decrypt-fail"] = "hide";
301
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
302
+ extraAttrs['decrypt-fail'] = 'hide'
616
303
  }
617
304
  if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
618
- extraAttrs["native_flow_name"] =
619
- messages.interactiveResponseMessage.nativeFlowResponseMessage?.name ||
620
- "menu_options";
305
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
621
306
  }
622
- if (isGroupOrStatus && !isRetryResend) {
307
+ if (isGroup || isStatus) {
623
308
  const [groupData, senderKeyMap] = await Promise.all([
624
309
  (async () => {
625
- let groupData =
626
- useCachedGroupMetadata && cachedGroupMetadata
627
- ? await cachedGroupMetadata(jid)
628
- : undefined;
629
- if (groupData && Array.isArray(groupData?.participants)) {
630
- logger.trace(
631
- { jid: jid, participants: groupData.participants.length },
632
- "using cached group metadata"
633
- );
634
- } else if (!isStatus) {
635
- groupData = await groupMetadata(jid);
310
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
311
+ if (groupData) {
312
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
313
+ }
314
+ else if (!isStatus) {
315
+ groupData = await groupMetadata(jid)
636
316
  }
637
317
  return groupData;
638
318
  })(),
639
319
  (async () => {
640
320
  if (!participant && !isStatus) {
641
- const result = await authState.keys.get("sender-key-memory", [jid]);
642
- return result[jid] || {};
321
+ const result = await authState.keys.get('sender-key-memory', [jid])
322
+ return result[jid] || {}
643
323
  }
644
- return {};
645
- })(),
324
+ return {}
325
+ })()
646
326
  ]);
647
- const participantsList = groupData ? groupData.participants.map((p) => p.id) : [];
648
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
649
- additionalAttributes = {
650
- ...additionalAttributes,
651
- expiration: groupData.ephemeralDuration.toString(),
652
- };
653
- }
654
- if (isStatus && statusJidList) {
655
- participantsList.push(...statusJidList);
656
- }
657
- const additionalDevices = await getUSyncDevices(
658
- participantsList,
659
- !!useUserDevicesCache,
660
- false
661
- );
662
- devices.push(...additionalDevices);
663
- if (isGroup) {
664
- additionalAttributes = {
665
- ...additionalAttributes,
666
- addressing_mode: groupData?.addressingMode || "lid",
667
- };
668
- }
669
- const patched = await patchMessageBeforeSending(message);
670
- if (Array.isArray(patched)) {
671
- throw new Boom("Per-jid patching is not supported in groups");
327
+ if (!participant) {
328
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
329
+ if (isStatus && statusJidList) {
330
+ participantsList.push(...statusJidList)
331
+ }
332
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
333
+ devices.push(...additionalDevices)
672
334
  }
673
- const bytes = encodeWAMessage(patched);
674
- const groupAddressingMode =
675
- additionalAttributes?.["addressing_mode"] || groupData?.addressingMode || "lid";
676
- const groupSenderIdentity = groupAddressingMode === "lid" && meLid ? meLid : meId;
677
- const {
678
- ciphertext: ciphertext,
679
- senderKeyDistributionMessage: senderKeyDistributionMessage,
680
- } = await signalRepository.encryptGroupMessage({
335
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
336
+ const bytes = Utils_1.encodeWAMessage(patched);
337
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
681
338
  group: destinationJid,
682
339
  data: bytes,
683
- meId: groupSenderIdentity,
340
+ meId,
684
341
  });
685
- const senderKeyRecipients = [];
686
- for (const device of devices) {
687
- const deviceJid = device.jid;
688
- const hasKey = !!senderKeyMap[deviceJid];
689
- if (
690
- (!hasKey || !!participant) &&
691
- !isHostedLidUser(deviceJid) &&
692
- !isHostedPnUser(deviceJid) &&
693
- device.device !== 99
694
- ) {
695
- senderKeyRecipients.push(deviceJid);
696
- senderKeyMap[deviceJid] = true;
342
+ const senderKeyJids = [];
343
+ for (const { user, device } of devices) {
344
+ const jid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
345
+ if (!senderKeyMap[jid] || !!participant) {
346
+ senderKeyJids.push(jid);
347
+ senderKeyMap[jid] = true;
697
348
  }
698
349
  }
699
- if (senderKeyRecipients.length) {
700
- logger.debug({ senderKeyJids: senderKeyRecipients }, "sending new sender key");
350
+ if (senderKeyJids.length) {
351
+ logger.debug({ senderKeyJids }, 'sending new sender key');
701
352
  const senderKeyMsg = {
702
353
  senderKeyDistributionMessage: {
703
354
  axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
704
- groupId: destinationJid,
705
- },
355
+ groupId: destinationJid
356
+ }
706
357
  };
707
- const senderKeySessionTargets = senderKeyRecipients;
708
- await assertSessions(senderKeySessionTargets);
709
- const result = await createParticipantNodes(
710
- senderKeyRecipients,
711
- senderKeyMsg,
712
- extraAttrs
713
- );
714
- shouldIncludeDeviceIdentity =
715
- shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
358
+ await assertSessions(senderKeyJids, false);
359
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
360
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
716
361
  participants.push(...result.nodes);
717
362
  }
718
363
  binaryNodeContent.push({
719
- tag: "enc",
720
- attrs: { v: "2", type: "skmsg", ...extraAttrs },
721
- content: ciphertext,
722
- });
723
- await authState.keys.set({
724
- "sender-key-memory": { [jid]: senderKeyMap },
364
+ tag: 'enc',
365
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
366
+ content: ciphertext
725
367
  });
726
- } else {
727
- let ownId = meId;
728
- if (isLid && meLid) {
729
- ownId = meLid;
730
- logger.debug(
731
- { to: jid, ownId: ownId },
732
- "Using LID identity for @lid conversation"
733
- );
734
- } else {
735
- logger.debug(
736
- { to: jid, ownId: ownId },
737
- "Using PN identity for @s.whatsapp.net conversation"
738
- );
368
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
369
+ }
370
+ else if (isNewsletter) {
371
+ if (message.protocolMessage?.editedMessage) {
372
+ msgId = message.protocolMessage.key?.id
373
+ message = message.protocolMessage.editedMessage
739
374
  }
740
- const { user: ownUser } = jidDecode(ownId);
741
- if (!isRetryResend) {
742
- const targetUserServer = isLid ? "lid" : "s.whatsapp.net";
743
- devices.push({
744
- user: user,
745
- device: 0,
746
- jid: jidEncode(user, targetUserServer, 0),
747
- });
748
- if (user !== ownUser) {
749
- const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
750
- const ownUserForAddressing =
751
- isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
752
- devices.push({
753
- user: ownUserForAddressing,
754
- device: 0,
755
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0),
756
- });
375
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
376
+ msgId = message.protocolMessage.key?.id
377
+ message = {}
378
+ }
379
+ const patched = await patchMessageBeforeSending(message, [])
380
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
381
+ binaryNodeContent.push({
382
+ tag: 'plaintext',
383
+ attrs: extraAttrs ? extraAttrs : {},
384
+ content: bytes
385
+ })
386
+ }
387
+ else {
388
+ const { user: meUser } = WABinary_1.jidDecode(meId);
389
+ if (!participant) {
390
+ devices.push({ user })
391
+ if (user !== meUser) {
392
+ devices.push({ user: meUser })
757
393
  }
758
- if (additionalAttributes?.["category"] !== "peer") {
759
- devices.length = 0;
760
- const senderIdentity =
761
- isLid && meLid
762
- ? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
763
- : jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
764
- const sessionDevices = await getUSyncDevices(
765
- [senderIdentity, jid],
766
- true,
767
- false
768
- );
769
- devices.push(...sessionDevices);
770
- logger.debug(
771
- {
772
- deviceCount: devices.length,
773
- devices: devices.map(
774
- (d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`
775
- ),
776
- },
777
- "Device enumeration complete with unified addressing"
778
- );
394
+ if (additionalAttributes?.['category'] !== 'peer') {
395
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
396
+ devices.push(...additionalDevices)
779
397
  }
780
398
  }
781
- const allRecipients = [];
782
- const meRecipients = [];
783
- const otherRecipients = [];
784
- const { user: mePnUser } = jidDecode(meId);
785
- const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
786
- for (const { user: user, jid: jid } of devices) {
787
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
788
- if (isExactSenderDevice) {
789
- logger.debug(
790
- { jid: jid, meId: meId, meLid: meLid },
791
- "Skipping exact sender device (whatsmeow pattern)"
792
- );
793
- continue;
794
- }
795
- const isMe = user === mePnUser || user === meLidUser;
399
+ const allJids = [];
400
+ const meJids = [];
401
+ const otherJids = [];
402
+ for (const { user, device } of devices) {
403
+ const isMe = user === meUser
404
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
796
405
  if (isMe) {
797
- meRecipients.push(jid);
798
- } else {
799
- otherRecipients.push(jid);
406
+ meJids.push(jid)
800
407
  }
801
- allRecipients.push(jid);
408
+ else {
409
+ otherJids.push(jid)
410
+ }
411
+ allJids.push(jid)
802
412
  }
803
- await assertSessions(allRecipients);
804
- const [
805
- { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
806
- { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 },
807
- ] = await Promise.all([
808
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
809
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg),
810
- ]);
413
+ await assertSessions(allJids, false);
414
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
415
+ createParticipantNodes(meJids, meMsg, extraAttrs),
416
+ createParticipantNodes(otherJids, message, extraAttrs)
417
+ ])
811
418
  participants.push(...meNodes);
812
419
  participants.push(...otherNodes);
813
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
814
- extraAttrs["phash"] = generateParticipantHashV2([
815
- ...meRecipients,
816
- ...otherRecipients,
817
- ]);
818
- }
819
420
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
820
421
  }
821
- if (isRetryResend) {
822
- const isParticipantLid = isLidUser(participant.jid);
823
- const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
824
- const encodedMessageToSend = isMe
825
- ? encodeWAMessage({
826
- deviceSentMessage: {
827
- destinationJid: destinationJid,
828
- message: message,
829
- },
830
- })
831
- : encodeWAMessage(message);
832
- const { type: type, ciphertext: encryptedContent } =
833
- await signalRepository.encryptMessage({
834
- data: encodedMessageToSend,
835
- jid: participant.jid,
836
- });
837
- binaryNodeContent.push({
838
- tag: "enc",
839
- attrs: { v: "2", type: type, count: participant.count.toString() },
840
- content: encryptedContent,
841
- });
842
- }
843
422
  if (participants.length) {
844
- if (additionalAttributes?.["category"] === "peer") {
845
- const peerNode = participants[0]?.content?.[0];
423
+ if (additionalAttributes?.['category'] === 'peer') {
424
+ const peerNode = participants[0]?.content?.[0]
846
425
  if (peerNode) {
847
- binaryNodeContent.push(peerNode);
426
+ binaryNodeContent.push(peerNode)
848
427
  }
849
- } else {
428
+ }
429
+ else {
850
430
  binaryNodeContent.push({
851
- tag: "participants",
431
+ tag: 'participants',
852
432
  attrs: {},
853
- content: participants,
854
- });
433
+ content: participants
434
+ })
855
435
  }
856
436
  }
857
437
  const stanza = {
858
- tag: "message",
438
+ tag: 'message',
859
439
  attrs: {
860
440
  id: msgId,
861
- to: destinationJid,
862
- type: getTypeMessage(message),
863
- ...(additionalAttributes || {}),
441
+ type: getTypeMessage(messages),
442
+ ...(additionalAttributes || {})
864
443
  },
865
- content: binaryNodeContent,
866
- };
444
+ content: binaryNodeContent
445
+ }
867
446
  if (participant) {
868
- if (isJidGroup(destinationJid)) {
447
+ if (WABinary_1.isJidGroup(destinationJid)) {
869
448
  stanza.attrs.to = destinationJid;
870
449
  stanza.attrs.participant = participant.jid;
871
- } else if (areJidsSameUser(participant.jid, meId)) {
450
+ }
451
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
872
452
  stanza.attrs.to = participant.jid;
873
453
  stanza.attrs.recipient = destinationJid;
874
- } else {
454
+ }
455
+ else {
875
456
  stanza.attrs.to = participant.jid;
876
457
  }
877
- } else {
458
+ }
459
+ else {
878
460
  stanza.attrs.to = destinationJid;
879
461
  }
880
462
  if (shouldIncludeDeviceIdentity) {
881
463
  stanza.content.push({
882
- tag: "device-identity",
464
+ tag: 'device-identity',
883
465
  attrs: {},
884
- content: encodeSignedDeviceIdentity(authState.creds.account, true),
885
- });
886
- logger.debug({ jid: jid }, "adding device identity");
887
- }
888
- const contactTcTokenData =
889
- !isGroup && !isRetryResend && !isStatus
890
- ? await authState.keys.get("tctoken", [destinationJid])
891
- : {};
892
- const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
893
- if (tcTokenBuffer) {
894
- stanza.content.push({
895
- tag: "tctoken",
896
- attrs: {},
897
- content: tcTokenBuffer,
898
- });
899
- }
900
- if (isGroup && regexGroupOld.test(jid) && !message.reactionMessage) {
901
- stanza.content.push({ tag: "multicast", attrs: {} });
902
- }
903
- if (pollMessage || messages.eventMessage) {
904
- stanza.content.push({
905
- tag: "meta",
906
- attrs: messages.eventMessage
907
- ? { event_type: "creation" }
908
- : isNewsletter
909
- ? {
910
- polltype: "creation",
911
- contenttype: pollMessage?.pollContentType === 2 ? "image" : "text",
912
- }
913
- : { polltype: "creation" },
466
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
914
467
  });
915
- }
916
- if (!isNewsletter && buttonType) {
917
- const buttonsNode = getButtonArgs(messages);
918
- const filteredButtons = getBinaryFilteredButtons(
919
- additionalNodes ? additionalNodes : []
920
- );
921
- if (filteredButtons) {
922
- stanza.content.push(...additionalNodes);
923
- didPushAdditional = true;
924
- } else {
925
- stanza.content.push(buttonsNode);
926
- }
468
+ logger.debug({ jid }, 'adding device identity');
927
469
  }
928
470
  if (AI && isPrivate) {
929
- const botNode = { tag: "bot", attrs: { biz_bot: "1" } };
930
- const filteredBizBot = getBinaryFilteredBizBot(
931
- additionalNodes ? additionalNodes : []
932
- );
471
+ const botNode = {
472
+ tag: 'bot',
473
+ attrs: {
474
+ biz_bot: '1'
475
+ }
476
+ }
477
+ const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
933
478
  if (filteredBizBot) {
934
- stanza.content.push(...additionalNodes);
935
- didPushAdditional = true;
936
- } else {
937
- stanza.content.push(botNode);
479
+ stanza.content.push(...additionalNodes)
480
+ didPushAdditional = true
481
+ }
482
+ else {
483
+ stanza.content.push(botNode)
938
484
  }
939
485
  }
486
+ if (!isNewsletter && buttonType && !isStatus) {
487
+ const content = WABinary_1.getAdditionalNode(buttonType)
488
+ const filteredNode = WABinary_1.getBinaryNodeFilter(additionalNodes)
489
+ if (filteredNode) {
490
+ didPushAdditional = true
491
+ stanza.content.push(...additionalNodes)
492
+ }
493
+ else {
494
+ stanza.content.push(...content)
495
+ }
496
+ logger.debug({ jid }, 'adding business node')
497
+ }
940
498
  if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
941
499
  stanza.content.push(...additionalNodes);
942
500
  }
943
- logger.debug({ msgId: msgId }, `sending message to ${participants.length} devices`);
501
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
944
502
  await sendNode(stanza);
945
- if (messageRetryManager && !participant) {
946
- messageRetryManager.addRecentMessage(destinationJid, msgId, message);
947
- }
948
- }, meId);
949
- return msgId;
503
+ });
504
+ message = Types_1.WAProto.Message.fromObject(message)
505
+ const messageJSON = {
506
+ key: {
507
+ remoteJid: jid,
508
+ fromMe: true,
509
+ id: msgId
510
+ },
511
+ message: message,
512
+ messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
513
+ messageStubParameters: [],
514
+ participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
515
+ status: Types_1.WAMessageStatus.PENDING
516
+ }
517
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
950
518
  };
951
519
  const getTypeMessage = (msg) => {
952
- const message = normalizeMessageContent(msg);
953
- if (
954
- message.pollCreationMessage ||
955
- message.pollCreationMessageV2 ||
956
- message.pollCreationMessageV3
957
- ) {
958
- return "poll";
959
- } else if (message.reactionMessage) {
960
- return "reaction";
961
- } else if (message.eventMessage) {
962
- return "event";
963
- } else if (getMediaType(message)) {
964
- return "media";
965
- } else {
966
- return "text";
520
+ const message = Utils_1.normalizeMessageContent(msg);
521
+ if (message.reactionMessage) {
522
+ return 'reaction'
967
523
  }
968
- };
524
+ else if (getMediaType(message)) {
525
+ return 'media'
526
+ }
527
+ else {
528
+ return 'text'
529
+ }
530
+ }
969
531
  const getMediaType = (message) => {
970
532
  if (message.imageMessage) {
971
- return "image";
972
- } else if (message.stickerMessage) {
973
- return message.stickerMessage.isLottie
974
- ? "1p_sticker"
975
- : message.stickerMessage.isAvatar
976
- ? "avatar_sticker"
977
- : "sticker";
978
- } else if (message.videoMessage) {
979
- return message.videoMessage.gifPlayback ? "gif" : "video";
980
- } else if (message.audioMessage) {
981
- return message.audioMessage.ptt ? "ptt" : "audio";
982
- } else if (message.ptvMessage) {
983
- return "ptv";
984
- } else if (message.albumMessage) {
985
- return "collection";
986
- } else if (message.contactMessage) {
987
- return "vcard";
988
- } else if (message.documentMessage) {
989
- return "document";
990
- } else if (message.stickerPackMessage) {
991
- return "sticker_pack";
992
- } else if (message.contactsArrayMessage) {
993
- return "contact_array";
994
- } else if (message.locationMessage) {
995
- return "location";
996
- } else if (message.liveLocationMessage) {
997
- return "livelocation";
998
- } else if (message.listMessage) {
999
- return "list";
1000
- } else if (message.listResponseMessage) {
1001
- return "list_response";
1002
- } else if (message.buttonsResponseMessage) {
1003
- return "buttons_response";
1004
- } else if (message.orderMessage) {
1005
- return "order";
1006
- } else if (message.productMessage) {
1007
- return "product";
1008
- } else if (message.interactiveResponseMessage) {
1009
- return "native_flow_response";
1010
- } else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
1011
- return "cataloglink";
1012
- } else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
1013
- return "productlink";
1014
- } else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1015
- return "url";
533
+ return 'image'
1016
534
  }
1017
- };
535
+ else if (message.videoMessage) {
536
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
537
+ }
538
+ else if (message.audioMessage) {
539
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
540
+ }
541
+ else if (message.contactMessage) {
542
+ return 'vcard'
543
+ }
544
+ else if (message.documentMessage) {
545
+ return 'document'
546
+ }
547
+ else if (message.contactsArrayMessage) {
548
+ return 'contact_array'
549
+ }
550
+ else if (message.liveLocationMessage) {
551
+ return 'livelocation'
552
+ }
553
+ else if (message.stickerMessage) {
554
+ return 'sticker'
555
+ }
556
+ else if (message.listMessage) {
557
+ return 'list'
558
+ }
559
+ else if (message.listResponseMessage) {
560
+ return 'list_response'
561
+ }
562
+ else if (message.buttonsResponseMessage) {
563
+ return 'buttons_response'
564
+ }
565
+ else if (message.orderMessage) {
566
+ return 'order'
567
+ }
568
+ else if (message.productMessage) {
569
+ return 'product'
570
+ }
571
+ else if (message.interactiveResponseMessage) {
572
+ return 'native_flow_response'
573
+ }
574
+ else if (message.groupInviteMessage) {
575
+ return 'url'
576
+ }
577
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
578
+ return 'productlink'
579
+ }
580
+ }
1018
581
  const getButtonType = (message) => {
1019
582
  if (message.listMessage) {
1020
- return "list";
1021
- } else if (message.buttonsMessage) {
1022
- return "buttons";
1023
- } else if (message.interactiveMessage?.nativeFlowMessage) {
1024
- return "native_flow";
583
+ return 'list'
1025
584
  }
1026
- };
1027
- const getButtonArgs = (message) => {
1028
- const nativeFlow = message.interactiveMessage?.nativeFlowMessage;
1029
- const firstButtonName = nativeFlow?.buttons?.[0]?.name;
1030
- const nativeFlowSpecials = [
1031
- "mpm",
1032
- "cta_catalog",
1033
- "send_location",
1034
- "call_permission_request",
1035
- "wa_payment_transaction_details",
1036
- "automated_greeting_message_view_catalog",
1037
- ];
1038
- if (
1039
- nativeFlow &&
1040
- (firstButtonName === "review_and_pay" || firstButtonName === "payment_info")
1041
- ) {
1042
- return {
1043
- tag: "biz",
1044
- attrs: {
1045
- native_flow_name:
1046
- firstButtonName === "review_and_pay" ? "order_details" : firstButtonName,
1047
- },
1048
- };
1049
- } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1050
- return {
1051
- tag: "biz",
1052
- attrs: {
1053
- actual_actors: "2",
1054
- host_storage: "2",
1055
- privacy_mode_ts: unixTimestampSeconds().toString(),
1056
- },
1057
- content: [
1058
- {
1059
- tag: "interactive",
1060
- attrs: { type: "native_flow", v: "1" },
1061
- content: [{ tag: "native_flow", attrs: { v: "2", name: firstButtonName } }],
1062
- },
1063
- { tag: "quality_control", attrs: { source_type: "third_party" } },
1064
- ],
1065
- };
1066
- } else if (nativeFlow || message.buttonsMessage) {
1067
- return {
1068
- tag: "biz",
1069
- attrs: {
1070
- actual_actors: "2",
1071
- host_storage: "2",
1072
- privacy_mode_ts: unixTimestampSeconds().toString(),
1073
- },
1074
- content: [
1075
- {
1076
- tag: "interactive",
1077
- attrs: { type: "native_flow", v: "1" },
1078
- content: [{ tag: "native_flow", attrs: { v: "9", name: "mixed" } }],
1079
- },
1080
- { tag: "quality_control", attrs: { source_type: "third_party" } },
1081
- ],
1082
- };
1083
- } else if (message.listMessage) {
1084
- return {
1085
- tag: "biz",
1086
- attrs: {
1087
- actual_actors: "2",
1088
- host_storage: "2",
1089
- privacy_mode_ts: unixTimestampSeconds().toString(),
1090
- },
1091
- content: [
1092
- { tag: "list", attrs: { v: "2", type: "product_list" } },
1093
- { tag: "quality_control", attrs: { source_type: "third_party" } },
1094
- ],
1095
- };
1096
- } else {
1097
- return {
1098
- tag: "biz",
1099
- attrs: {
1100
- actual_actors: "2",
1101
- host_storage: "2",
1102
- privacy_mode_ts: unixTimestampSeconds().toString(),
1103
- },
1104
- };
585
+ else if (message.buttonsMessage) {
586
+ return 'buttons'
1105
587
  }
1106
- };
588
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
589
+ return 'review_and_pay'
590
+ }
591
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
592
+ return 'review_order'
593
+ }
594
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
595
+ return 'payment_info'
596
+ }
597
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
598
+ return 'payment_status'
599
+ }
600
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
601
+ return 'payment_method'
602
+ }
603
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
604
+ return 'interactive'
605
+ }
606
+ else if (message.interactiveMessage?.nativeFlowMessage) {
607
+ return 'native_flow'
608
+ }
609
+ }
1107
610
  const getPrivacyTokens = async (jids) => {
1108
- const t = unixTimestampSeconds().toString();
611
+ const t = Utils_1.unixTimestampSeconds().toString();
1109
612
  const result = await query({
1110
- tag: "iq",
1111
- attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "privacy" },
613
+ tag: 'iq',
614
+ attrs: {
615
+ to: WABinary_1.S_WHATSAPP_NET,
616
+ type: 'set',
617
+ xmlns: 'privacy'
618
+ },
1112
619
  content: [
1113
620
  {
1114
- tag: "tokens",
621
+ tag: 'tokens',
1115
622
  attrs: {},
1116
- content: jids.map((jid) => ({
1117
- tag: "token",
623
+ content: jids.map(jid => ({
624
+ tag: 'token',
1118
625
  attrs: {
1119
- jid: jidNormalizedUser(jid),
1120
- t: t,
1121
- type: "trusted_contact",
1122
- },
1123
- })),
1124
- },
1125
- ],
626
+ jid: WABinary_1.jidNormalizedUser(jid),
627
+ t,
628
+ type: 'trusted_contact'
629
+ }
630
+ }))
631
+ }
632
+ ]
1126
633
  });
1127
634
  return result;
1128
- };
1129
- const getEphemeralGroup = (jid) => {
1130
- if (!isJidGroup(jid)) throw new TypeError("Jid should originate from a group!");
1131
- return groupQuery(jid, "get", [{ tag: "query", attrs: { request: "interactive" } }])
1132
- .then((groups) => getBinaryNodeChild(groups, "group"))
1133
- .then((metadata) => getBinaryNodeChild(metadata, "ephemeral")?.attrs?.expiration || 0);
1134
- };
1135
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1136
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
635
+ }
636
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
637
+ const rahmi = new kikyy(Utils_1, waUploadToServer, relayMessage, config, sock);
638
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
1137
639
  return {
1138
- ...conn,
1139
- getPrivacyTokens: getPrivacyTokens,
1140
- assertSessions: assertSessions,
1141
- profilePictureUrl: profilePictureUrl,
1142
- relayMessage: relayMessage,
1143
- sendReceipt: sendReceipt,
1144
- sendReceipts: sendReceipts,
1145
- readMessages: readMessages,
1146
- getUSyncDevices: getUSyncDevices,
1147
- refreshMediaConn: refreshMediaConn,
1148
- waUploadToServer: waUploadToServer,
1149
- getEphemeralGroup: getEphemeralGroup,
1150
- fetchPrivacySettings: fetchPrivacySettings,
1151
- messageRetryManager: messageRetryManager,
1152
- createParticipantNodes: createParticipantNodes,
1153
- sendPeerDataOperationMessage: sendPeerDataOperationMessage,
1154
- updateMemberLabel: updateMemberLabel,
640
+ ...sock,
641
+ getPrivacyTokens,
642
+ assertSessions,
643
+ relayMessage,
644
+ sendReceipt,
645
+ sendReceipts,
646
+ rahmi,
647
+ readMessages,
648
+ refreshMediaConn,
649
+ getUSyncDevices,
650
+ createParticipantNodes,
651
+ waUploadToServer,
652
+ sendPeerDataOperationMessage,
653
+ fetchPrivacySettings,
1155
654
  updateMediaMessage: async (message) => {
1156
- const content = assertMediaContent(message.message);
655
+ const content = (0, Utils_1.assertMediaContent)(message.message);
1157
656
  const mediaKey = content.mediaKey;
1158
657
  const meId = authState.creds.me.id;
1159
- const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
658
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
1160
659
  let error = undefined;
1161
660
  await Promise.all([
1162
661
  sendNode(node),
1163
- waitForMsgMediaUpdate(async (update) => {
1164
- const result = update.find((c) => c.key.id === message.key.id);
662
+ waitForMsgMediaUpdate(update => {
663
+ const result = update.find(c => c.key.id === message.key.id);
1165
664
  if (result) {
1166
665
  if (result.error) {
1167
666
  error = result.error;
1168
- } else {
667
+ }
668
+ else {
1169
669
  try {
1170
- const media = await decryptMediaRetryData(
1171
- result.media,
1172
- mediaKey,
1173
- result.key.id
1174
- );
1175
- if (
1176
- media.result !== proto.MediaRetryNotification.ResultType.SUCCESS
1177
- ) {
1178
- const resultStr =
1179
- proto.MediaRetryNotification.ResultType[media.result];
1180
- throw new Boom(
1181
- `Media re-upload failed by device (${resultStr})`,
1182
- {
1183
- data: media,
1184
- statusCode:
1185
- getStatusCodeForMediaRetry(media.result) || 404,
1186
- }
1187
- );
670
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
671
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
672
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
673
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
1188
674
  }
1189
675
  content.directPath = media.directPath;
1190
- content.url = getUrlFromDirectPath(content.directPath);
1191
- logger.debug(
1192
- { directPath: media.directPath, key: result.key },
1193
- "media update successful"
1194
- );
1195
- } catch (err) {
676
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
677
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
678
+ }
679
+ catch (err) {
1196
680
  error = err;
1197
681
  }
1198
682
  }
1199
683
  return true;
1200
684
  }
1201
- }),
685
+ })
1202
686
  ]);
1203
687
  if (error) {
1204
688
  throw error;
1205
689
  }
1206
- ev.emit("messages.update", [
1207
- { key: message.key, update: { message: message.message } },
690
+ ev.emit('messages.update', [
691
+ {
692
+ key: message.key,
693
+ update: {
694
+ message: message.message
695
+ }
696
+ }
1208
697
  ]);
1209
698
  return message;
1210
699
  },
1211
- sendStatusMentions: async (content, jids = []) => {
1212
- const userJid = jidNormalizedUser(authState.creds.me.id);
1213
- let allUsers = new Set();
1214
- allUsers.add(userJid);
1215
- for (const id of jids) {
1216
- const isGroup = isJidGroup(id);
1217
- const isPrivate = isPnUser(id);
1218
- if (isGroup) {
1219
- try {
1220
- const metadata =
1221
- (await cachedGroupMetadata(id)) || (await groupMetadata(id));
1222
- const participants = metadata.participants.map((p) =>
1223
- jidNormalizedUser(p.id)
1224
- );
1225
- participants.forEach((jid) => allUsers.add(jid));
1226
- } catch (error) {
1227
- logger.error(`Error getting metadata for group ${id}: ${error}`);
700
+ setLabelGroup: async (id, text) => {
701
+ await relayMessage(id, {
702
+ protocolMessage: {
703
+ type: 30,
704
+ memberLabel: {
705
+ label: text.slice(0, 30)
1228
706
  }
1229
- } else if (isPrivate) {
1230
- allUsers.add(jidNormalizedUser(id));
1231
707
  }
1232
- }
1233
- const uniqueUsers = Array.from(allUsers);
1234
- const getRandomHexColor = () =>
1235
- "#" +
1236
- Math.floor(Math.random() * 16777215)
1237
- .toString(16)
1238
- .padStart(6, "0");
1239
- const isMedia = content.image || content.video || content.audio;
1240
- const isAudio = !!content.audio;
1241
- const messageContent = { ...content };
1242
- if (isMedia && !isAudio) {
1243
- if (messageContent.text) {
1244
- messageContent.caption = messageContent.text;
1245
- delete messageContent.text;
1246
- }
1247
- delete messageContent.ptt;
1248
- delete messageContent.font;
1249
- delete messageContent.backgroundColor;
1250
- delete messageContent.textColor;
1251
- }
1252
- if (isAudio) {
1253
- delete messageContent.text;
1254
- delete messageContent.caption;
1255
- delete messageContent.font;
1256
- delete messageContent.textColor;
1257
- }
1258
- const font = !isMedia ? content.font || Math.floor(Math.random() * 9) : undefined;
1259
- const textColor = !isMedia ? content.textColor || getRandomHexColor() : undefined;
1260
- const backgroundColor =
1261
- !isMedia || isAudio ? content.backgroundColor || getRandomHexColor() : undefined;
1262
- const ptt = isAudio
1263
- ? typeof content.ptt === "boolean"
1264
- ? content.ptt
1265
- : true
1266
- : undefined;
1267
- let msg;
1268
- let mediaHandle;
1269
- try {
1270
- msg = await generateWAMessage(STORIES_JID, messageContent, {
1271
- logger: logger,
1272
- userJid: userJid,
1273
- getUrlInfo: (text) =>
1274
- getUrlInfo(text, {
1275
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1276
- fetchOpts: { timeout: 3e3, ...(httpRequestOptions || {}) },
1277
- logger: logger,
1278
- uploadImage: generateHighQualityLinkPreview
1279
- ? waUploadToServer
1280
- : undefined,
1281
- }),
1282
- upload: async (encFilePath, opts) => {
1283
- const up = await waUploadToServer(encFilePath, { ...opts });
1284
- mediaHandle = up.handle;
1285
- return up;
1286
- },
1287
- mediaCache: config.mediaCache,
1288
- options: config.options,
1289
- font: font,
1290
- textColor: textColor,
1291
- backgroundColor: backgroundColor,
1292
- ptt: ptt,
1293
- });
1294
- } catch (error) {
1295
- logger.error(`Error generating message: ${error}`);
1296
- throw error;
1297
- }
1298
- await relayMessage(STORIES_JID, msg.message, {
1299
- messageId: msg.key.id,
1300
- statusJidList: uniqueUsers,
708
+ }, {
1301
709
  additionalNodes: [
1302
710
  {
1303
711
  tag: "meta",
1304
- attrs: {},
1305
- content: [
1306
- {
1307
- tag: "mentioned_users",
1308
- attrs: {},
1309
- content: jids.map((jid) => ({
1310
- tag: "to",
1311
- attrs: { jid: jidNormalizedUser(jid) },
1312
- })),
1313
- },
1314
- ],
1315
- },
1316
- ],
1317
- });
1318
- for (const id of jids) {
1319
- try {
1320
- const normalizedId = jidNormalizedUser(id);
1321
- const isPrivate = isPnUser(normalizedId);
1322
- const type = isPrivate ? "statusMentionMessage" : "groupStatusMentionMessage";
1323
- const protocolMessage = {
1324
- [type]: {
1325
- message: { protocolMessage: { key: msg.key, type: 25 } },
712
+ attrs: {
713
+ tag_reason: "user_update",
714
+ appdata: "member_tag"
1326
715
  },
1327
- messageContextInfo: { messageSecret: randomBytes(32) },
1328
- };
1329
- const statusMsg = await generateWAMessageFromContent(
1330
- normalizedId,
1331
- protocolMessage,
1332
- {}
1333
- );
1334
- await relayMessage(normalizedId, statusMsg.message, {
1335
- additionalNodes: [
1336
- {
1337
- tag: "meta",
1338
- attrs: isPrivate
1339
- ? { is_status_mention: "true" }
1340
- : { is_group_status_mention: "true" },
1341
- },
1342
- ],
1343
- });
1344
- await delay(2e3);
1345
- } catch (error) {
1346
- logger.error(`Error sending to ${id}: ${error}`);
1347
- }
1348
- }
1349
- return msg;
716
+ content: undefined
717
+ }
718
+ ]
719
+ })
720
+ },
721
+ sendStatusMention: async (content, jids = []) => {
722
+ return await rahmi.sendStatusWhatsApp(content, jids);
1350
723
  },
1351
724
  sendMessage: async (jid, content, options = {}) => {
1352
725
  const userJid = authState.creds.me.id;
1353
- const additionalAttributes = {};
1354
- if (!options.ephemeralExpiration) {
1355
- if (isJidGroup(jid)) {
1356
- const expiration = await getEphemeralGroup(jid);
1357
- options.ephemeralExpiration = expiration;
1358
- }
1359
- }
1360
- if (
1361
- typeof content === "object" &&
1362
- "disappearingMessagesInChat" in content &&
1363
- typeof content["disappearingMessagesInChat"] !== "undefined" &&
1364
- isJidGroup(jid)
1365
- ) {
1366
- const { disappearingMessagesInChat: disappearingMessagesInChat } = content;
1367
- const value =
1368
- typeof disappearingMessagesInChat === "boolean"
1369
- ? disappearingMessagesInChat
1370
- ? WA_DEFAULT_EPHEMERAL
1371
- : 0
1372
- : disappearingMessagesInChat;
1373
- await groupToggleEphemeral(jid, value);
1374
- } else if (typeof content === "object" && "album" in content && content.album) {
1375
- const albumMsg = await prepareAlbumMessageContent(jid, content.album, {
1376
- conn: {
1377
- relayMessage: relayMessage,
1378
- waUploadToServer: waUploadToServer,
1379
- },
1380
- userJid: userJid,
1381
- ...options,
1382
- });
1383
- for (const media of albumMsg) {
1384
- await delay(options.delay || 500);
1385
- await relayMessage(jid, media.message, {
1386
- messageId: media.key.id,
1387
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1388
- additionalAttributes: additionalAttributes,
1389
- statusJidList: options.statusJidList,
1390
- additionalNodes: options.additionalNodes,
1391
- AI: options.ai,
1392
- });
726
+ delete options.ephemeralExpiration
727
+ const { filter = false, quoted } = options;
728
+ const getParticipantAttr = () => filter ? { participant: { jid } } : {};
729
+ const messageType = rahmi.detectType(content);
730
+ if (typeof content === 'object' && 'disappearingMessagesInChat' in content &&
731
+ typeof content['disappearingMessagesInChat'] !== 'undefined' && WABinary_1.isJidGroup(jid)) {
732
+ const { disappearingMessagesInChat } = content
733
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
734
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
735
+ disappearingMessagesInChat
736
+ await groupToggleEphemeral(jid, value)
737
+ }
738
+ else {
739
+ let mediaHandle
740
+ if (messageType) {
741
+ switch (messageType) {
742
+ case 'PAYMENT':
743
+ const paymentContent = await rahmi.handlePayment(content, quoted);
744
+ return await relayMessage(jid, paymentContent, {
745
+ messageId: Utils_1.generateMessageID(),
746
+ ...getParticipantAttr()
747
+ });
748
+ case 'PRODUCT':
749
+ const productContent = await rahmi.handleProduct(content, jid, quoted);
750
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
751
+ return await relayMessage(jid, productMsg.message, {
752
+ messageId: productMsg.key.id,
753
+ ...getParticipantAttr()
754
+ });
755
+ case 'INTERACTIVE':
756
+ const interactiveContent = await rahmi.handleInteractive(content, jid, quoted);
757
+ const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
758
+ return await relayMessage(jid, interactiveMsg.message, {
759
+ messageId: interactiveMsg.key.id,
760
+ ...getParticipantAttr()
761
+ });
762
+ case 'ALBUM':
763
+ return await rahmi.handleAlbum(content, jid, quoted)
764
+ case 'EVENT':
765
+ return await rahmi.handleEvent(content, jid, quoted)
766
+ case 'POLL_RESULT':
767
+ return await rahmi.handlePollResult(content, jid, quoted)
768
+ case 'GROUP_STORY':
769
+ return await rahmi.handleGroupStory(content, jid, quoted)
770
+ }
1393
771
  }
1394
- return albumMsg;
1395
- } else {
1396
- let mediaHandle;
1397
- const fullMsg = await generateWAMessage(jid, content, {
1398
- logger: logger,
1399
- userJid: userJid,
1400
- getUrlInfo: (text) =>
1401
- getUrlInfo(text, {
1402
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1403
- fetchOpts: { timeout: 3e3, ...(httpRequestOptions || {}) },
1404
- logger: logger,
1405
- uploadImage: generateHighQualityLinkPreview
1406
- ? waUploadToServer
1407
- : undefined,
1408
- }),
1409
- getProfilePicUrl: profilePictureUrl,
1410
- getCallLink: createCallLink,
1411
- upload: async (encFilePath, opts) => {
1412
- const up = await waUploadToServer(encFilePath, {
772
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
773
+ logger,
774
+ userJid,
775
+ quoted,
776
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
777
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
778
+ fetchOpts: {
779
+ timeout: 3000,
780
+ ...axiosOptions || {}
781
+ },
782
+ logger,
783
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
784
+ }),
785
+ upload: async (readStream, opts) => {
786
+ const up = await waUploadToServer(readStream, {
1413
787
  ...opts,
1414
- newsletter: isJidNewsletter(jid),
788
+ newsletter: WABinary_1.isJidNewsLetter(jid)
1415
789
  });
1416
- mediaHandle = up.handle;
1417
790
  return up;
1418
791
  },
1419
792
  mediaCache: config.mediaCache,
1420
793
  options: config.options,
1421
- messageId: generateMessageID(userJid),
1422
- ...options,
794
+ ...options
1423
795
  });
1424
- const isPin = "pin" in content && !!content.pin;
1425
- const isEdit = "edit" in content && !!content.edit;
1426
- const isDelete = "delete" in content && !!content.delete;
1427
- const isKeep = "keep" in content && !!content.keep && content.keep?.type === 2;
1428
- if (isDelete || isKeep) {
1429
- if (
1430
- (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) ||
1431
- isJidNewsletter(jid)
1432
- ) {
1433
- additionalAttributes.edit = "8";
1434
- } else {
1435
- additionalAttributes.edit = "7";
1436
- }
1437
- } else if (isEdit) {
1438
- additionalAttributes.edit = isJidNewsletter(jid) ? "3" : "1";
1439
- } else if (isPin) {
1440
- additionalAttributes.edit = "2";
1441
- }
1442
- if (mediaHandle) {
1443
- additionalAttributes["media_id"] = mediaHandle;
1444
- }
1445
- if ("cachedGroupMetadata" in options) {
1446
- console.warn(
1447
- "cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config."
1448
- );
796
+ const isDeleteMsg = 'delete' in content && !!content.delete;
797
+ const isEditMsg = 'edit' in content && !!content.edit;
798
+ const isAiMsg = 'ai' in content && !!content.ai;
799
+ const additionalAttributes = {};
800
+ const additionalNodes = [];
801
+ if (isDeleteMsg) {
802
+ const fromMe = content.delete?.fromMe;
803
+ const isGroup = WABinary_1.isJidGroup(content.delete?.remoteJid);
804
+ additionalAttributes.edit = (isGroup && !fromMe) || WABinary_1.isJidNewsLetter(jid) ? '8' : '7';
805
+ } else if (isEditMsg) {
806
+ additionalAttributes.edit = WABinary_1.isJidNewsLetter(jid) ? '3' : '1';
807
+ } else if (isAiMsg) {
808
+ additionalNodes.push({
809
+ attrs: {
810
+ biz_bot: '1'
811
+ }, tag: "bot"
812
+ });
1449
813
  }
1450
814
  await relayMessage(jid, fullMsg.message, {
1451
815
  messageId: fullMsg.key.id,
1452
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1453
- additionalAttributes: additionalAttributes,
1454
- statusJidList: options.statusJidList,
1455
- additionalNodes: options.additionalNodes,
1456
- AI: options.ai,
816
+ cachedGroupMetadata: options.cachedGroupMetadata,
817
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
818
+ additionalAttributes,
819
+ statusJidList: options.statusJidList
1457
820
  });
1458
821
  if (config.emitOwnEvents) {
1459
- process.nextTick(async () => {
1460
- await messageMutex.mutex(() => upsertMessage(fullMsg, "append"));
822
+ process.nextTick(() => {
823
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1461
824
  });
1462
825
  }
1463
826
  return fullMsg;
1464
827
  }
1465
- },
1466
- };
828
+ }
829
+ }
1467
830
  };
1468
- module.exports = { makeMessagesSocket: makeMessagesSocket };
831
+ exports.makeMessagesSocket = makeMessagesSocket;