@heavstaltech/baileys 2.3.4 → 3.2.4

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 (133) hide show
  1. package/README.md +226 -53
  2. package/WAProto/index.js +14270 -302
  3. package/engine-requirements.js +10 -0
  4. package/lib/Defaults/baileys-version.json +1 -1
  5. package/lib/Defaults/index.js +118 -79
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +64 -0
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +34 -0
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +69 -0
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +51 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +53 -0
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +99 -0
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +6 -16
  33. package/lib/Signal/libsignal.js +51 -29
  34. package/lib/Socket/business.d.ts +43 -42
  35. package/lib/Socket/chats.d.ts +222 -36
  36. package/lib/Socket/chats.js +186 -153
  37. package/lib/Socket/dugong.d.ts +254 -0
  38. package/lib/Socket/dugong.js +484 -0
  39. package/lib/Socket/groups.d.ts +7 -7
  40. package/lib/Socket/groups.js +37 -35
  41. package/lib/Socket/index.d.ts +52 -51
  42. package/lib/Socket/index.js +1 -0
  43. package/lib/Socket/messages-recv.d.ts +37 -34
  44. package/lib/Socket/messages-recv.js +175 -37
  45. package/lib/Socket/messages-send.d.ts +12 -18
  46. package/lib/Socket/messages-send.js +396 -574
  47. package/lib/Socket/newsletter.d.ts +28 -26
  48. package/lib/Socket/newsletter.js +140 -25
  49. package/lib/Socket/registration.d.ts +52 -49
  50. package/lib/Socket/registration.js +7 -7
  51. package/lib/Socket/socket.d.ts +0 -1
  52. package/lib/Socket/socket.js +47 -198
  53. package/lib/Socket/usync.d.ts +10 -11
  54. package/lib/Store/make-cache-manager-store.d.ts +1 -2
  55. package/lib/Store/make-in-memory-store.d.ts +2 -2
  56. package/lib/Store/make-in-memory-store.js +1 -5
  57. package/lib/Store/make-ordered-dictionary.js +2 -2
  58. package/lib/Types/Auth.d.ts +1 -0
  59. package/lib/Types/Call.d.ts +1 -1
  60. package/lib/Types/Chat.d.ts +7 -12
  61. package/lib/Types/Events.d.ts +2 -17
  62. package/lib/Types/GroupMetadata.d.ts +2 -3
  63. package/lib/Types/Label.d.ts +0 -11
  64. package/lib/Types/Label.js +1 -1
  65. package/lib/Types/LabelAssociation.js +1 -1
  66. package/lib/Types/Message.d.ts +10 -170
  67. package/lib/Types/Newsletter.d.ts +97 -86
  68. package/lib/Types/Newsletter.js +38 -32
  69. package/lib/Types/Socket.d.ts +2 -7
  70. package/lib/Types/index.d.ts +0 -9
  71. package/lib/Types/index.js +1 -1
  72. package/lib/Utils/auth-utils.js +14 -35
  73. package/lib/Utils/business.d.ts +1 -1
  74. package/lib/Utils/business.js +2 -2
  75. package/lib/Utils/chat-utils.d.ts +12 -11
  76. package/lib/Utils/chat-utils.js +36 -52
  77. package/lib/Utils/crypto.d.ts +16 -15
  78. package/lib/Utils/crypto.js +26 -74
  79. package/lib/Utils/decode-wa-message.d.ts +0 -17
  80. package/lib/Utils/decode-wa-message.js +17 -53
  81. package/lib/Utils/event-buffer.js +7 -10
  82. package/lib/Utils/generics.d.ts +17 -13
  83. package/lib/Utils/generics.js +79 -58
  84. package/lib/Utils/history.d.ts +2 -6
  85. package/lib/Utils/history.js +6 -4
  86. package/lib/Utils/logger.d.ts +3 -1
  87. package/lib/Utils/lt-hash.js +12 -12
  88. package/lib/Utils/make-mutex.d.ts +2 -2
  89. package/lib/Utils/messages-media.d.ts +28 -25
  90. package/lib/Utils/messages-media.js +201 -103
  91. package/lib/Utils/messages.js +36 -473
  92. package/lib/Utils/noise-handler.d.ts +5 -4
  93. package/lib/Utils/noise-handler.js +14 -19
  94. package/lib/Utils/process-message.d.ts +5 -5
  95. package/lib/Utils/process-message.js +23 -75
  96. package/lib/Utils/signal.d.ts +1 -2
  97. package/lib/Utils/signal.js +26 -32
  98. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -0
  99. package/lib/Utils/use-multi-file-auth-state.js +66 -242
  100. package/lib/Utils/validate-connection.d.ts +1 -1
  101. package/lib/Utils/validate-connection.js +88 -64
  102. package/lib/WABinary/constants.d.ts +27 -24
  103. package/lib/WABinary/decode.d.ts +2 -1
  104. package/lib/WABinary/decode.js +11 -23
  105. package/lib/WABinary/encode.d.ts +2 -1
  106. package/lib/WABinary/encode.js +147 -134
  107. package/lib/WABinary/generic-utils.d.ts +5 -2
  108. package/lib/WABinary/generic-utils.js +125 -37
  109. package/lib/WABinary/jid-utils.d.ts +1 -1
  110. package/lib/WAM/BinaryInfo.d.ts +11 -2
  111. package/lib/WAM/encode.d.ts +2 -1
  112. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +3 -3
  113. package/lib/WAUSync/USyncUser.d.ts +2 -0
  114. package/lib/index.d.ts +12 -0
  115. package/lib/index.js +12 -0
  116. package/package.json +102 -98
  117. package/WAProto/index.d.ts +0 -50383
  118. package/WASignalGroup/GroupProtocol.js +0 -1697
  119. package/WASignalGroup/ciphertext_message.js +0 -16
  120. package/WASignalGroup/group_cipher.js +0 -120
  121. package/WASignalGroup/group_session_builder.js +0 -46
  122. package/WASignalGroup/index.js +0 -5
  123. package/WASignalGroup/keyhelper.js +0 -21
  124. package/WASignalGroup/protobufs.js +0 -3
  125. package/WASignalGroup/queue_job.js +0 -69
  126. package/WASignalGroup/sender_chain_key.js +0 -50
  127. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  128. package/WASignalGroup/sender_key_message.js +0 -92
  129. package/WASignalGroup/sender_key_name.js +0 -70
  130. package/WASignalGroup/sender_key_record.js +0 -56
  131. package/WASignalGroup/sender_key_state.js +0 -129
  132. package/lib/Utils/use-single-file-auth-state.d.ts +0 -12
  133. package/lib/Utils/use-single-file-auth-state.js +0 -75
@@ -1,36 +1,45 @@
1
- "use strict";
1
+ "use strict";
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
4
+ };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.makeMessagesSocket = void 0;
7
7
  const boom_1 = require("@hapi/boom");
8
8
  const node_cache_1 = __importDefault(require("node-cache"));
9
9
  const WAProto_1 = require("../../WAProto");
10
10
  const Defaults_1 = require("../Defaults");
11
- const Types_1 = require("../Types");
11
+ const axios_1 = require("axios")
12
+ const Types_1 = require("../Types")
12
13
  const Utils_1 = require("../Utils");
13
14
  const link_preview_1 = require("../Utils/link-preview");
14
15
  const WABinary_1 = require("../WABinary");
15
- const WAUSync_1 = require("../WAUSync");
16
16
  const newsletter_1 = require("./newsletter");
17
+ const WAUSync_1 = require("../WAUSync")
18
+ const kikyy = require('./dugong');
17
19
  var ListType = WAProto_1.proto.Message.ListMessage.ListType;
18
20
  const makeMessagesSocket = (config) => {
19
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, } = config;
21
+ const {
22
+ logger,
23
+ linkPreviewImageThumbnailWidth,
24
+ generateHighQualityLinkPreview,
25
+ options: axiosOptions,
26
+ patchMessageBeforeSending
27
+ } = config;
20
28
  const sock = (0, newsletter_1.makeNewsletterSocket)(config);
21
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupQuery, newsletterWMexQuery, groupToggleEphemeral } = sock;
22
- const patchMessageRequiresBeforeSending = (msg, recipientJids) => {
23
- var _a, _b;
24
- if ((_b = (_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.listMessage) {
25
- msg = JSON.parse(JSON.stringify(msg));
26
- msg.deviceSentMessage.message.listMessage.listType = WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT;
27
- }
28
- if (msg === null || msg === void 0 ? void 0 : msg.listMessage) {
29
- msg = JSON.parse(JSON.stringify(msg));
30
- msg.listMessage.listType = WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT;
31
- }
32
- return msg;
33
- };
29
+ const {
30
+ ev,
31
+ authState,
32
+ processingMutex,
33
+ signalRepository,
34
+ upsertMessage,
35
+ query,
36
+ fetchPrivacySettings,
37
+ generateMessageTag,
38
+ sendNode,
39
+ groupMetadata,
40
+ groupToggleEphemeral,
41
+ executeUSyncQuery
42
+ } = sock;
34
43
  const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
35
44
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
36
45
  useClones: false
@@ -49,9 +58,9 @@ const makeMessagesSocket = (config) => {
49
58
  },
50
59
  content: [{ tag: 'media_conn', attrs: {} }]
51
60
  });
52
- const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
61
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn');
53
62
  const node = {
54
- hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
63
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
55
64
  hostname: attrs.hostname,
56
65
  maxContentLengthBytes: +attrs.maxContentLengthBytes,
57
66
  })),
@@ -80,7 +89,7 @@ const makeMessagesSocket = (config) => {
80
89
  if (isReadReceipt) {
81
90
  node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
82
91
  }
83
- if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
92
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
84
93
  node.attrs.recipient = jid;
85
94
  node.attrs.to = participant;
86
95
  }
@@ -91,7 +100,7 @@ const makeMessagesSocket = (config) => {
91
100
  }
92
101
  }
93
102
  if (type) {
94
- node.attrs.type = (0, WABinary_1.isJidNewsLetter)(jid) ? 'read-self' : type;
103
+ node.attrs.type = WABinary_1.isJidNewsLetter(jid) ? 'read-self' : type;
95
104
  }
96
105
  const remainingMessageIds = messageIds.slice(1);
97
106
  if (remainingMessageIds.length) {
@@ -123,93 +132,72 @@ const makeMessagesSocket = (config) => {
123
132
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
124
133
  await sendReceipts(keys, readType);
125
134
  };
126
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
127
- var _a, _b, _c, _d;
128
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
129
- if ((0, WABinary_1.isJidNewsLetter)(jid)) {
130
- const node = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
131
- input: {
132
- key: jid,
133
- type: "JID",
134
- 'view_role': 'GUEST'
135
- },
136
- 'fetch_viewer_metadata': true,
137
- 'fetch_full_image': true,
138
- 'fetch_creation_time': true
139
- });
140
- const result = (_b = (_a = (0, WABinary_1.getBinaryNodeChild)(node, 'result')) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.toString();
141
- const metadataPath = JSON.parse(result).data[Types_1.XWAPaths.NEWSLETTER];
142
- const pictype = type === 'image' ? 'picture' : 'preview';
143
- const directPath = (_c = metadataPath === null || metadataPath === void 0 ? void 0 : metadataPath.thread_metadata[pictype]) === null || _c === void 0 ? void 0 : _c.direct_path;
144
- return directPath ? (0, Utils_1.getUrlFromDirectPath)(directPath) : null;
145
- }
146
- else {
147
- const result = await query({
148
- tag: 'iq',
149
- attrs: {
150
- target: jid,
151
- to: WABinary_1.S_WHATSAPP_NET,
152
- type: 'get',
153
- xmlns: 'w:profile:picture'
154
- },
155
- content: [
156
- { tag: 'picture', attrs: { type, query: 'url' } }
157
- ]
158
- }, timeoutMs);
159
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
160
- return (_d = child === null || child === void 0 ? void 0 : child.attrs) === null || _d === void 0 ? void 0 : _d.url;
161
- }
162
- };
163
135
  /** Fetch all the devices we've to send a message to */
164
136
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
165
- var _a;
166
- const deviceResults = [];
137
+ const deviceResults = []
138
+
167
139
  if (!useCache) {
168
- logger.debug('not using cache for devices');
140
+ logger.debug('not using cache for devices')
169
141
  }
170
- const toFetch = [];
171
- jids = Array.from(new Set(jids));
142
+
143
+ const toFetch = []
144
+
145
+ jids = Array.from(new Set(jids))
146
+
172
147
  for (let jid of jids) {
173
- const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
174
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
148
+ const user = WABinary_1.jidDecode(jid)?.user
149
+
150
+ jid = WABinary_1.jidNormalizedUser(jid)
151
+
175
152
  if (useCache) {
176
- const devices = userDevicesCache.get(user);
153
+ const devices = userDevicesCache.get(user)
154
+
177
155
  if (devices) {
178
- deviceResults.push(...devices);
179
- logger.trace({ user }, 'using cache for devices');
156
+ deviceResults.push(...devices)
157
+ logger.trace({ user }, 'using cache for devices')
180
158
  }
159
+
181
160
  else {
182
- toFetch.push(jid);
161
+ toFetch.push(jid)
183
162
  }
184
163
  }
164
+
185
165
  else {
186
- toFetch.push(jid);
166
+ toFetch.push(jid)
187
167
  }
188
168
  }
169
+
189
170
  if (!toFetch.length) {
190
- return deviceResults;
171
+ return deviceResults
191
172
  }
173
+
192
174
  const query = new WAUSync_1.USyncQuery()
193
175
  .withContext('message')
194
- .withDeviceProtocol();
176
+ .withDeviceProtocol()
177
+
195
178
  for (const jid of toFetch) {
196
- query.withUser(new WAUSync_1.USyncUser().withId(jid));
179
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
197
180
  }
198
- const result = await sock.executeUSyncQuery(query);
181
+
182
+ const result = await executeUSyncQuery(query)
183
+
199
184
  if (result) {
200
- const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
201
- const deviceMap = {};
185
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
186
+ const deviceMap = {}
187
+
202
188
  for (const item of extracted) {
203
- deviceMap[item.user] = deviceMap[item.user] || [];
204
- deviceMap[item.user].push(item);
205
- deviceResults.push(item);
189
+ deviceMap[item.user] = deviceMap[item.user] || []
190
+ deviceMap[item.user].push(item)
191
+ deviceResults.push(item)
206
192
  }
193
+
207
194
  for (const key in deviceMap) {
208
- userDevicesCache.set(key, deviceMap[key]);
195
+ userDevicesCache.set(key, deviceMap[key])
209
196
  }
210
197
  }
211
- return deviceResults;
212
- };
198
+
199
+ return deviceResults
200
+ }
213
201
  const assertSessions = async (jids, force) => {
214
202
  let didFetchNewSession = false;
215
203
  let jidsRequiringFetch = [];
@@ -253,19 +241,20 @@ const makeMessagesSocket = (config) => {
253
241
  }
254
242
  return didFetchNewSession;
255
243
  };
244
+
245
+
256
246
  const sendPeerDataOperationMessage = async (pdoMessage) => {
257
- var _a;
258
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
259
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
260
- throw new boom_1.Boom('Not authenticated');
247
+ if (!authState.creds.me?.id) {
248
+ throw new boom_1.Boom('Not authenticated')
261
249
  }
250
+
262
251
  const protocolMessage = {
263
252
  protocolMessage: {
264
253
  peerDataOperationRequestMessage: pdoMessage,
265
254
  type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
266
255
  }
267
256
  };
268
- const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
257
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
269
258
  const msgId = await relayMessage(meJid, protocolMessage, {
270
259
  additionalAttributes: {
271
260
  category: 'peer',
@@ -276,9 +265,8 @@ const makeMessagesSocket = (config) => {
276
265
  return msgId;
277
266
  };
278
267
  const createParticipantNodes = async (jids, message, extraAttrs) => {
279
- let patched = await patchMessageBeforeSending(message, jids);
280
- const requiredPatched = patchMessageRequiresBeforeSending(patched, jids);
281
- const bytes = (0, Utils_1.encodeWAMessage)(requiredPatched);
268
+ const patched = await patchMessageBeforeSending(message, jids);
269
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
282
270
  let shouldIncludeDeviceIdentity = false;
283
271
  const nodes = await Promise.all(jids.map(async (jid) => {
284
272
  const { type, ciphertext } = await signalRepository
@@ -303,21 +291,22 @@ const makeMessagesSocket = (config) => {
303
291
  }));
304
292
  return { nodes, shouldIncludeDeviceIdentity };
305
293
  }; //apela
306
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList }) => {
294
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList, AI = true }) => {
307
295
  const meId = authState.creds.me.id;
308
296
  let shouldIncludeDeviceIdentity = false;
309
- const { user, server } = (0, WABinary_1.jidDecode)(jid);
297
+ let didPushAdditional = false
298
+ const { user, server } = WABinary_1.jidDecode(jid);
310
299
  const statusJid = 'status@broadcast';
311
300
  const isGroup = server === 'g.us';
312
301
  const isStatus = jid === statusJid;
313
302
  const isLid = server === 'lid';
314
- const isPrivate = server === 's.whatsapp.net';
303
+ const isPrivate = server === 's.whatsapp.net'
315
304
  const isNewsletter = server === 'newsletter';
316
- msgId = msgId || (await config.generateMessageID() ?? (0, Utils_1.generateMessageID)());
305
+ msgId = msgId || (0, Utils_1.generateMessageID)();
317
306
  useUserDevicesCache = useUserDevicesCache !== false;
318
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
307
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
319
308
  const participants = [];
320
- const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
309
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
321
310
  const binaryNodeContent = [];
322
311
  const devices = [];
323
312
  const meMsg = {
@@ -326,7 +315,9 @@ const makeMessagesSocket = (config) => {
326
315
  message
327
316
  }
328
317
  };
329
- const extraAttrs = {};
318
+ const extraAttrs = {}
319
+ const messages = Utils_1.normalizeMessageContent(message)
320
+ const buttonType = getButtonType(messages);
330
321
  if (participant) {
331
322
  // when the retry request is not for a group
332
323
  // only send to the specific device that asked for a retry
@@ -334,58 +325,80 @@ const makeMessagesSocket = (config) => {
334
325
  if (!isGroup && !isStatus) {
335
326
  additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
336
327
  }
337
- const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
328
+ const { user, device } = WABinary_1.jidDecode(participant.jid);
338
329
  devices.push({ user, device });
339
330
  }
340
331
  await authState.keys.transaction(async () => {
341
- var _a, _b, _c, _d, _e, _f;
342
- const mediaType = getMediaType(message);
332
+ const mediaType = getMediaType(messages);
333
+
343
334
  if (mediaType) {
344
- extraAttrs['mediatype'] = mediaType;
335
+ extraAttrs['mediatype'] = mediaType
345
336
  }
346
- if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
347
- extraAttrs['decrypt-fail'] = 'hide';
337
+
338
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
339
+ extraAttrs['decrypt-fail'] = 'hide'
340
+ }
341
+
342
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
343
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
348
344
  }
345
+
349
346
  if (isGroup || isStatus) {
350
347
  const [groupData, senderKeyMap] = await Promise.all([
351
348
  (async () => {
352
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
353
- if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
349
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
350
+ if (groupData) {
354
351
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
355
352
  }
356
- if (!groupData && !isStatus) {
357
- groupData = await groupMetadata(jid);
353
+
354
+ else if (!isStatus) {
355
+ groupData = await groupMetadata(jid)
358
356
  }
357
+
359
358
  return groupData;
360
359
  })(),
361
360
  (async () => {
362
361
  if (!participant && !isStatus) {
363
- const result = await authState.keys.get('sender-key-memory', [jid]);
364
- return result[jid] || {};
362
+ const result = await authState.keys.get('sender-key-memory', [jid])
363
+ return result[jid] || {}
365
364
  }
366
- return {};
367
- })()
365
+
366
+ return {}
367
+
368
+ })()
368
369
  ]);
369
370
  if (!participant) {
370
- const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
371
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
372
+
371
373
  if (isStatus && statusJidList) {
372
- participantsList.push(...statusJidList);
374
+ participantsList.push(...statusJidList)
373
375
  }
374
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
375
- devices.push(...additionalDevices);
376
- }
377
- const patched = await patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', d.device)));
378
- const requiredPatched = patchMessageRequiresBeforeSending(patched, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', d.device)));
379
- const bytes = (0, Utils_1.encodeWAMessage)(requiredPatched);
376
+
377
+ // if (!isStatus) {
378
+ // const expiration = await getEphemeralGroup(jid)
379
+ // additionalAttributes = {
380
+ // ...additionalAttributes,
381
+ // addressing_mode: 'pn',
382
+ // ...expiration ? { expiration: expiration.toString() } : null
383
+ // }
384
+ // }
385
+
386
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
387
+ devices.push(...additionalDevices)
388
+ }
389
+
390
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
391
+ const bytes = Utils_1.encodeWAMessage(patched);
392
+
380
393
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
381
394
  group: destinationJid,
382
395
  data: bytes,
383
396
  meId,
384
397
  });
385
398
  const senderKeyJids = [];
386
- // ensure a connection is established with every device
399
+
387
400
  for (const { user, device } of devices) {
388
- const jid = (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : 's.whatsapp.net', device);
401
+ const jid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
389
402
  if (!senderKeyMap[jid] || !!participant) {
390
403
  senderKeyJids.push(jid);
391
404
  // store that this person has had the sender keys sent to them
@@ -403,107 +416,115 @@ const makeMessagesSocket = (config) => {
403
416
  }
404
417
  };
405
418
  await assertSessions(senderKeyJids, false);
406
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { ...extraAttrs, mediatype: mediaType } : extraAttrs);
419
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
407
420
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
408
421
  participants.push(...result.nodes);
409
422
  }
410
423
  binaryNodeContent.push({
411
424
  tag: 'enc',
412
- attrs: { v: '2', type: 'skmsg' },
425
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
413
426
  content: ciphertext
414
427
  });
415
428
  await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
416
429
  }
417
430
  else if (isNewsletter) {
418
431
  // Message edit
419
- if ((_a = message.protocolMessage) === null || _a === void 0 ? void 0 : _a.editedMessage) {
420
- msgId = (_b = message.protocolMessage.key) === null || _b === void 0 ? void 0 : _b.id;
421
- message = message.protocolMessage.editedMessage;
432
+ if (message.protocolMessage?.editedMessage) {
433
+ msgId = message.protocolMessage.key?.id
434
+ message = message.protocolMessage.editedMessage
422
435
  }
436
+
423
437
  // Message delete
424
- if (((_c = message.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
425
- msgId = (_d = message.protocolMessage.key) === null || _d === void 0 ? void 0 : _d.id;
426
- message = {};
427
- }
428
- const patched = await patchMessageBeforeSending(message, []);
429
- const bytes = WAProto_1.proto.Message.encode(patched).finish();
438
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
439
+ msgId = message.protocolMessage.key?.id
440
+ message = {}
441
+ }
442
+
443
+ const patched = await patchMessageBeforeSending(message, [])
444
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
445
+
430
446
  binaryNodeContent.push({
431
447
  tag: 'plaintext',
432
- attrs: mediaType ? { mediatype: mediaType } : {},
448
+ attrs: extraAttrs ? extraAttrs : {},
433
449
  content: bytes
434
- });
450
+ })
435
451
  }
436
452
  else {
437
- const { user: meUser, device: meDevice } = (0, WABinary_1.jidDecode)(meId);
453
+ const { user: meUser } = WABinary_1.jidDecode(meId);
438
454
  if (!participant) {
439
- devices.push({ user });
440
- // do not send message to self if the device is 0 (mobile)
441
- if (meDevice !== undefined && meDevice !== 0) {
442
- devices.push({ user: meUser });
455
+ devices.push({ user })
456
+ if (user !== meUser) {
457
+ devices.push({ user: meUser })
443
458
  }
444
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
445
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
446
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
447
- devices.push(...additionalDevices);
459
+
460
+ if (additionalAttributes?.['category'] !== 'peer') {
461
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
462
+
463
+ devices.push(...additionalDevices)
448
464
  }
449
- devices.push(...additionalDevices);
450
465
  }
451
466
  const allJids = [];
452
467
  const meJids = [];
453
468
  const otherJids = [];
454
469
  for (const { user, device } of devices) {
455
- const isMe = user === meUser;
456
- const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_f = (_e = authState.creds) === null || _e === void 0 ? void 0 : _e.me) === null || _f === void 0 ? void 0 : _f.lid.split(':')[0]) || user : user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', device);
470
+ const isMe = user === meUser
471
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
472
+
457
473
  if (isMe) {
458
- meJids.push(jid);
474
+ meJids.push(jid)
459
475
  }
476
+
460
477
  else {
461
- otherJids.push(jid);
478
+ otherJids.push(jid)
462
479
  }
463
- allJids.push(jid);
480
+
481
+ allJids.push(jid)
464
482
  }
465
483
  await assertSessions(allJids, false);
466
484
  const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
467
- createParticipantNodes(meJids, meMsg, mediaType ? { ...extraAttrs, mediatype: mediaType } : extraAttrs),
468
- createParticipantNodes(otherJids, message, mediaType ? { ...extraAttrs, mediatype: mediaType } : extraAttrs)
469
- ]);
485
+ createParticipantNodes(meJids, meMsg, extraAttrs),
486
+ createParticipantNodes(otherJids, message, extraAttrs)
487
+ ])
470
488
  participants.push(...meNodes);
471
489
  participants.push(...otherNodes);
472
490
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
473
491
  }
474
492
  if (participants.length) {
475
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
476
- const peerNode = (_e = (_d = participants[0]) === null || _d === void 0 ? void 0 : _d.content) === null || _e === void 0 ? void 0 : _e[0];
493
+ if (additionalAttributes?.['category'] === 'peer') {
494
+ const peerNode = participants[0]?.content?.[0]
495
+
477
496
  if (peerNode) {
478
- binaryNodeContent.push(peerNode); // push only enc
497
+ binaryNodeContent.push(peerNode) // push only enc
479
498
  }
480
499
  }
500
+
481
501
  else {
482
502
  binaryNodeContent.push({
483
503
  tag: 'participants',
484
504
  attrs: {},
485
505
  content: participants
486
- });
506
+ })
487
507
  }
488
508
  }
509
+
489
510
  const stanza = {
490
511
  tag: 'message',
491
512
  attrs: {
492
513
  id: msgId,
493
- type: isNewsletter ? getTypeMessage(message) : 'text',
514
+ type: getTypeMessage(messages),
494
515
  ...(additionalAttributes || {})
495
516
  },
496
517
  content: binaryNodeContent
497
- };
518
+ }
498
519
  // if the participant to send to is explicitly specified (generally retry recp)
499
520
  // ensure the message is only sent to that person
500
521
  // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
501
522
  if (participant) {
502
- if ((0, WABinary_1.isJidGroup)(destinationJid)) {
523
+ if (WABinary_1.isJidGroup(destinationJid)) {
503
524
  stanza.attrs.to = destinationJid;
504
525
  stanza.attrs.participant = participant.jid;
505
526
  }
506
- else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
527
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
507
528
  stanza.attrs.to = participant.jid;
508
529
  stanza.attrs.recipient = destinationJid;
509
530
  }
@@ -522,220 +543,162 @@ const makeMessagesSocket = (config) => {
522
543
  });
523
544
  logger.debug({ jid }, 'adding device identity');
524
545
  }
525
- if (additionalNodes && additionalNodes.length > 0) {
526
- stanza.content.push(...additionalNodes);
527
- }
528
- const inMsg = (0, Utils_1.normalizeMessageContent)(message) || null;
529
- const key = inMsg ? (0, Utils_1.getContentType)(inMsg) : null;
530
- if (!isNewsletter && (key === 'interactiveMessage' || key === 'buttonsMessage')) {
531
- const nativeNode = {
532
- tag: 'biz',
533
- attrs: {},
534
- content: [{
535
- tag: 'interactive',
536
- attrs: {
537
- type: 'native_flow',
538
- v: '1'
539
- },
540
- content: [{
541
- tag: 'native_flow',
542
- attrs: {
543
- name: 'quick_reply'
544
- }
545
- }]
546
- }]
547
- };
548
- const resultNativeNode = filterNativeNode(additionalNodes);
549
- if (resultNativeNode && additionalNodes && additionalNodes.length > 0) {
550
- stanza.content.push(...resultNativeNode);
546
+
547
+ if (AI && isPrivate) {
548
+ const botNode = {
549
+ tag: 'bot',
550
+ attrs: {
551
+ biz_bot: '1'
552
+ }
551
553
  }
552
- else {
553
- stanza.content.push(nativeNode);
554
+
555
+ const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
556
+
557
+ if (filteredBizBot) {
558
+ stanza.content.push(...additionalNodes)
559
+ didPushAdditional = true
554
560
  }
555
- }/*
556
- if (isPrivate) {
557
- const botNode = {
558
- tag: 'bot',
559
- attrs: { biz_bot: '1' }
560
- };
561
- const resultBotNode = filterBotNode(additionalNodes);
562
- if (resultBotNode && additionalNodes && additionalNodes.length > 0) {
563
- stanza.content.push(...resultBotNode);
561
+
562
+ else {
563
+ stanza.content.push(botNode)
564
564
  }
565
+ }
566
+
567
+ if(!isNewsletter && buttonType && !isStatus) {
568
+ const content = WABinary_1.getAdditionalNode(buttonType)
569
+ const filteredNode = WABinary_1.getBinaryNodeFilter(additionalNodes)
570
+
571
+ if (filteredNode) {
572
+ didPushAdditional = true
573
+ stanza.content.push(...additionalNodes)
574
+ }
565
575
  else {
566
- stanza.content.push(botNode);
576
+ stanza.content.push(...content)
567
577
  }
568
- }*
569
- if (message && message.listMessage) {
570
- stanza.content.push({
571
- tag: 'biz',
572
- attrs: {},
573
- content: [
574
- {
575
- tag: 'list',
576
- attrs: getButtonArgs(message)
577
- }
578
- ]
579
- });
580
- logger.debug({ jid }, 'adding business node');
581
- }*/
582
- const buttonType = getButtonType(message);
583
- if (buttonType) {
584
- stanza.content.push({
585
- tag: 'biz',
586
- attrs: {},
587
- content: [
588
- {
589
- tag: buttonType,
590
- attrs: getButtonArgs(message),
591
- }
592
- ]
593
- });
594
- logger.debug({ jid }, 'adding business node');
578
+ logger.debug({ jid }, 'adding business node')
579
+ }
580
+
581
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
582
+ stanza.content.push(...additionalNodes);
595
583
  }
584
+
596
585
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
597
586
  await sendNode(stanza);
598
587
  });
599
- return msgId;
600
- };
601
- const filterNativeNode = (nodeContent) => {
602
- if (Array.isArray(nodeContent)) {
603
- return nodeContent.filter((item) => {
604
- var _a, _b, _c, _d, _e, _f, _g, _h;
605
- if (item.tag === 'biz' && ((_a = item === null || item === void 0 ? void 0 : item.content[0]) === null || _a === void 0 ? void 0 : _a.tag) === 'interactive' && ((_c = (_b = item === null || item === void 0 ? void 0 : item.content[0]) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.type) === 'native_flow' && ((_e = (_d = item === null || item === void 0 ? void 0 : item.content[0]) === null || _d === void 0 ? void 0 : _d.content[0]) === null || _e === void 0 ? void 0 : _e.tag) === 'native_flow' && ((_h = (_g = (_f = item === null || item === void 0 ? void 0 : item.content[0]) === null || _f === void 0 ? void 0 : _f.content[0]) === null || _g === void 0 ? void 0 : _g.attrs) === null || _h === void 0 ? void 0 : _h.name) === 'quick_reply') {
606
- return false;
607
- }
608
- return true;
609
- });
610
- }
611
- else {
612
- return nodeContent;
613
- }
614
- };
615
- const filterBotNode = (nodeContent) => {
616
- if (Array.isArray(nodeContent)) {
617
- return nodeContent.filter((item) => {
618
- if (item.tag === 'bot' && item.attrs.biz_bot === '1') {
619
- return false;
620
- }
621
- return true;
622
- });
623
- }
624
- else {
625
- return nodeContent;
626
- }
588
+
589
+ message = Types_1.WAProto.Message.fromObject(message)
590
+
591
+ const messageJSON = {
592
+ key: {
593
+ remoteJid: jid,
594
+ fromMe: true,
595
+ id: msgId
596
+ },
597
+ message: message,
598
+ messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
599
+ messageStubParameters: [],
600
+ participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
601
+ status: Types_1.WAMessageStatus.PENDING
602
+ }
603
+
604
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON)
605
+ // return msgId;
627
606
  };
628
607
  const getTypeMessage = (msg) => {
629
- if (msg.viewOnceMessage) {
630
- return getTypeMessage(msg.viewOnceMessage.message);
631
- }
632
- else if (msg.viewOnceMessageV2) {
633
- return getTypeMessage(msg.viewOnceMessageV2.message);
634
- }
635
- else if (msg.viewOnceMessageV2Extension) {
636
- return getTypeMessage(msg.viewOnceMessageV2Extension.message);
637
- }
638
- else if (msg.ephemeralMessage) {
639
- return getTypeMessage(msg.ephemeralMessage.message);
640
- }
641
- else if (msg.documentWithCaptionMessage) {
642
- return getTypeMessage(msg.documentWithCaptionMessage.message);
643
- }
644
- else if (msg.reactionMessage) {
645
- return 'reaction';
646
- }
647
- else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
648
- return 'poll';
649
- }
650
- else if (getMediaType(msg)) {
651
- return 'media';
652
- }
608
+ const message = Utils_1.normalizeMessageContent(msg)
609
+ if (message.reactionMessage) {
610
+ return 'reaction'
611
+ }
612
+ else if (getMediaType(message)) {
613
+ return 'media'
614
+ }
653
615
  else {
654
- return 'text';
616
+ return 'text'
655
617
  }
656
- };
618
+ }
619
+
657
620
  const getMediaType = (message) => {
658
621
  if (message.imageMessage) {
659
- return 'image';
622
+ return 'image'
660
623
  }
661
624
  else if (message.videoMessage) {
662
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
625
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
663
626
  }
664
627
  else if (message.audioMessage) {
665
- return message.audioMessage.ptt ? 'ptt' : 'audio';
628
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
666
629
  }
667
630
  else if (message.contactMessage) {
668
- return 'vcard';
631
+ return 'vcard'
669
632
  }
670
633
  else if (message.documentMessage) {
671
- return 'document';
634
+ return 'document'
672
635
  }
673
636
  else if (message.contactsArrayMessage) {
674
- return 'contact_array';
637
+ return 'contact_array'
675
638
  }
676
639
  else if (message.liveLocationMessage) {
677
- return 'livelocation';
640
+ return 'livelocation'
678
641
  }
679
642
  else if (message.stickerMessage) {
680
- return 'sticker';
643
+ return 'sticker'
681
644
  }
682
645
  else if (message.listMessage) {
683
- return 'list';
646
+ return 'list'
684
647
  }
685
648
  else if (message.listResponseMessage) {
686
- return 'list_response';
649
+ return 'list_response'
687
650
  }
688
651
  else if (message.buttonsResponseMessage) {
689
- return 'buttons_response';
652
+ return 'buttons_response'
690
653
  }
691
654
  else if (message.orderMessage) {
692
- return 'order';
655
+ return 'order'
693
656
  }
694
657
  else if (message.productMessage) {
695
- return 'product';
658
+ return 'product'
696
659
  }
697
660
  else if (message.interactiveResponseMessage) {
698
- return 'native_flow_response';
661
+ return 'native_flow_response'
699
662
  }
700
663
  else if (message.groupInviteMessage) {
701
- return 'url';
664
+ return 'url'
702
665
  }
703
- };
666
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
667
+ return 'productlink'
668
+ }
669
+ }
670
+
704
671
  const getButtonType = (message) => {
705
- if (message.buttonsMessage) {
706
- return 'buttons';
672
+ if (message.listMessage) {
673
+ return 'list'
707
674
  }
708
- else if (message.buttonsResponseMessage) {
709
- return 'buttons_response';
675
+ else if (message.buttonsMessage) {
676
+ return 'buttons'
710
677
  }
711
- else if (message.interactiveResponseMessage) {
712
- return 'interactive_response';
678
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
679
+ return 'review_and_pay'
713
680
  }
714
- else if (message.listMessage) {
715
- return 'list';
681
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
682
+ return 'review_order'
716
683
  }
717
- else if (message.listResponseMessage) {
718
- return 'list_response';
684
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
685
+ return 'payment_info'
719
686
  }
720
- };
721
- const getButtonArgs = (message) => {
722
- if (message.templateMessage) {
723
- // TODO: Add attributes
724
- return {};
687
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
688
+ return 'payment_status'
725
689
  }
726
- else if (message.listMessage) {
727
- const type = message.listMessage.listType;
728
- if (!type) {
729
- throw new boom_1.Boom('Expected list type inside message');
730
- }
731
- return { v: '2', type: ListType[type].toLowerCase() };
690
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
691
+ return 'payment_method'
732
692
  }
733
- else {
734
- return {};
693
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
694
+ return 'interactive'
735
695
  }
736
- };
696
+ else if (message.interactiveMessage?.nativeFlowMessage) {
697
+ return 'native_flow'
698
+ }
699
+ }
737
700
  const getPrivacyTokens = async (jids) => {
738
- const t = (0, Utils_1.unixTimestampSeconds)().toString();
701
+ const t = Utils_1.unixTimestampSeconds().toString();
739
702
  const result = await query({
740
703
  tag: 'iq',
741
704
  attrs: {
@@ -750,7 +713,7 @@ const makeMessagesSocket = (config) => {
750
713
  content: jids.map(jid => ({
751
714
  tag: 'token',
752
715
  attrs: {
753
- jid: (0, WABinary_1.jidNormalizedUser)(jid),
716
+ jid: WABinary_1.jidNormalizedUser(jid),
754
717
  t,
755
718
  type: 'trusted_contact'
756
719
  }
@@ -759,8 +722,9 @@ const makeMessagesSocket = (config) => {
759
722
  ]
760
723
  });
761
724
  return result;
762
- };
725
+ }
763
726
  const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
727
+ const rahmi = new kikyy(Utils_1, waUploadToServer, relayMessage);
764
728
  const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
765
729
  return {
766
730
  ...sock,
@@ -769,24 +733,23 @@ const makeMessagesSocket = (config) => {
769
733
  relayMessage,
770
734
  sendReceipt,
771
735
  sendReceipts,
772
- getButtonArgs,
736
+ rahmi,
773
737
  readMessages,
774
738
  refreshMediaConn,
775
739
  getUSyncDevices,
776
- sendPeerDataOperationMessage,
777
740
  createParticipantNodes,
778
- profilePictureUrl,
779
741
  waUploadToServer,
742
+ sendPeerDataOperationMessage,
780
743
  fetchPrivacySettings,
781
744
  updateMediaMessage: async (message) => {
782
745
  const content = (0, Utils_1.assertMediaContent)(message.message);
783
746
  const mediaKey = content.mediaKey;
784
747
  const meId = authState.creds.me.id;
785
- const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
748
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
786
749
  let error = undefined;
787
750
  await Promise.all([
788
751
  sendNode(node),
789
- waitForMsgMediaUpdate(async update => {
752
+ waitForMsgMediaUpdate(update => {
790
753
  const result = update.find(c => c.key.id === message.key.id);
791
754
  if (result) {
792
755
  if (result.error) {
@@ -794,8 +757,8 @@ const makeMessagesSocket = (config) => {
794
757
  }
795
758
  else {
796
759
  try {
797
- const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
798
- if (media && media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
760
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
761
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
799
762
  const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
800
763
  throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
801
764
  }
@@ -815,273 +778,132 @@ const makeMessagesSocket = (config) => {
815
778
  throw error;
816
779
  }
817
780
  ev.emit('messages.update', [
818
- { key: message.key, update: { message: message.message } }
781
+ {
782
+ key: message.key,
783
+ update: {
784
+ message: message.message
785
+ }
786
+ }
819
787
  ]);
820
788
  return message;
821
789
  },
822
- sendStatusMentions: async (content, jids = []) => {
823
- const userJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
824
- let allUsers = [];
825
- for (const id of jids) {
826
- const { user, server } = (0, WABinary_1.jidDecode)(id);
827
- const isGroup = server === 'g.us';
828
- const isPrivate = server === 's.whatsapp.net';
829
- if (isGroup) {
830
- let userId = await groupMetadata(id);
831
- let participant = await userId.participants;
832
- let users = await Promise.all(participant.map(u => (0, WABinary_1.jidNormalizedUser)(u.id)));
833
- allUsers = [...allUsers, ...users];
834
- }
835
- else if (isPrivate) {
836
- let users = await Promise.all(jids.map(id => id.replace(/\b\d{18}@.{4}\b/g, '')));
837
- allUsers = [...allUsers, ...users];
838
- }
839
- if (!allUsers.find(user => user.includes(userJid))) {
840
- allUsers.push(userJid);
790
+ sendMessage: async (jid, content, options = {}) => {
791
+ const userJid = authState.creds.me.id;
792
+ delete options.ephemeralExpiration
793
+ const { filter = false, quoted } = options;
794
+ const getParticipantAttr = () => filter ? { participant: { jid } } : {};
795
+ const messageType = rahmi.detectType(content);
796
+ if (typeof content === 'object' && 'disappearingMessagesInChat' in content &&
797
+ typeof content['disappearingMessagesInChat'] !== 'undefined' && WABinary_1.isJidGroup(jid)) {
798
+ const { disappearingMessagesInChat } = content
799
+
800
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
801
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
802
+ disappearingMessagesInChat
803
+
804
+ await groupToggleEphemeral(jid, value)
805
+ }
806
+
807
+ else {
808
+ let mediaHandle
809
+
810
+
811
+ if (messageType) {
812
+ switch(messageType) {
813
+ case 'PAYMENT':
814
+ const paymentContent = await rahmi.handlePayment(content, quoted);
815
+ return await relayMessage(jid, paymentContent, {
816
+ messageId: Utils_1.generateMessageID(),
817
+ ...getParticipantAttr()
818
+ });
819
+
820
+ case 'PRODUCT':
821
+ const productContent = await rahmi.handleProduct(content, jid, quoted);
822
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
823
+ return await relayMessage(jid, productMsg.message, {
824
+ messageId: productMsg.key.id,
825
+ ...getParticipantAttr()
826
+ });
827
+
828
+ case 'INTERACTIVE':
829
+ const interactiveContent = await rahmi.handleInteractive(content, jid, quoted);
830
+ const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
831
+ return await relayMessage(jid, interactiveMsg.message, {
832
+ messageId: interactiveMsg.key.id,
833
+ ...getParticipantAttr()
834
+ });
835
+ case 'ALBUM':
836
+ return await rahmi.handleAlbum(content, jid, quoted)
837
+ case 'EVENT':
838
+ return await rahmi.handleEvent(content, jid, quoted)
839
+ case 'POLL_RESULT':
840
+ return await rahmi.handlePollResult(content, jid, quoted)
841
+ case 'GROUP_STORY':
842
+ return await rahmi.handleGroupStory(content, jid, quoted)
841
843
  }
842
844
  }
843
- ;
844
- const getRandomHexColor = () => {
845
- return "#" + Math.floor(Math.random() * 16777215)
846
- .toString(16)
847
- .padStart(6, "0");
848
- };
849
- let mediaHandle;
850
- let msg = await (0, Utils_1.generateWAMessage)(WABinary_1.STORIES_JID, content, {
845
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
851
846
  logger,
852
847
  userJid,
853
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
848
+ quoted,
849
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
854
850
  thumbnailWidth: linkPreviewImageThumbnailWidth,
855
851
  fetchOpts: {
856
852
  timeout: 3000,
857
853
  ...axiosOptions || {}
858
854
  },
859
855
  logger,
860
- uploadImage: generateHighQualityLinkPreview
861
- ? waUploadToServer
862
- : undefined
856
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
863
857
  }),
864
858
  upload: async (readStream, opts) => {
865
- const up = await waUploadToServer(readStream, { ...opts });
866
- mediaHandle = up.handle;
859
+ const up = await waUploadToServer(readStream, {
860
+ ...opts,
861
+ newsletter: WABinary_1.isJidNewsLetter(jid)
862
+ });
867
863
  return up;
868
864
  },
869
865
  mediaCache: config.mediaCache,
870
866
  options: config.options,
871
- backgroundColor: getRandomHexColor(),
872
- font: Math.floor(Math.random() * 9),
867
+ ...options
873
868
  });
874
- await relayMessage(WABinary_1.STORIES_JID, msg.message, {
875
- messageId: msg.key.id,
876
- statusJidList: allUsers,
877
- additionalNodes: [
878
- {
879
- tag: 'meta',
880
- attrs: {},
881
- content: [
882
- {
883
- tag: 'mentioned_users',
884
- attrs: {},
885
- content: jids.map(jid => ({
886
- tag: 'to',
887
- attrs: { jid },
888
- content: undefined,
889
- })),
890
- },
891
- ],
892
- },
893
- ],
894
- });
895
- jids.forEach(async (id) => {
896
- id = (0, WABinary_1.jidNormalizedUser)(id);
897
- const { user, server } = (0, WABinary_1.jidDecode)(id);
898
- const isPrivate = server === 's.whatsapp.net';
899
- let type = isPrivate
900
- ? 'statusMentionMessage'
901
- : 'groupStatusMentionMessage';
902
- await relayMessage(id, {
903
- [type]: {
904
- message: {
905
- protocolMessage: {
906
- key: msg.key,
907
- type: 25,
908
- },
909
- },
910
- },
911
- }, {});
912
- await (0, Utils_1.delay)(2500);
913
- });
914
- return msg;
915
- },
916
- sendAlbumMessage: async (jid, medias, options = {}) => {
917
- const userJid = authState.creds.me.id;
918
- for (const media of medias) {
919
- if (!media.image && !media.video)
920
- throw new TypeError(`medias[i] must have image or video property`);
921
- }
922
- if (medias.length < 2)
923
- throw new RangeError("Minimum 2 media");
924
- const time = options.delay || 500;
925
- delete options.delay;
926
- const album = await (0, Utils_1.generateWAMessageFromContent)(jid, {
927
- albumMessage: {
928
- expectedImageCount: medias.filter(media => media.image).length,
929
- expectedVideoCount: medias.filter(media => media.video).length,
930
- ...options
931
- }
932
- }, { userJid, ...options });
933
- await relayMessage(jid, album.message, { messageId: album.key.id });
934
- let mediaHandle;
935
- let msg;
936
- for (const i in medias) {
937
- const media = medias[i];
938
- if (media.image) {
939
- msg = await (0, Utils_1.generateWAMessage)(jid, {
940
- image: media.image,
941
- ...media,
942
- ...options
943
- }, {
944
- userJid,
945
- upload: async (readStream, opts) => {
946
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
947
- mediaHandle = up.handle;
948
- return up;
949
- },
950
- ...options,
951
- });
952
- }
953
- else if (media.video) {
954
- msg = await (0, Utils_1.generateWAMessage)(jid, {
955
- video: media.video,
956
- ...media,
957
- ...options
958
- }, {
959
- userJid,
960
- upload: async (readStream, opts) => {
961
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
962
- mediaHandle = up.handle;
963
- return up;
964
- },
965
- ...options,
966
- });
967
- }
968
- if (msg) {
969
- msg.message.messageContextInfo = {
970
- messageAssociation: {
971
- associationType: 1,
972
- parentMessageKey: album.key
973
- }
974
- };
975
- }
976
- await relayMessage(jid, msg.message, { messageId: msg.key.id });
977
- await (0, Utils_1.delay)(time);
978
- }
979
- return album;
980
- },
981
- sendMessage: async (jid, content, options = {}) => {
982
- var _a, _b, _c;
983
- const userJid = authState.creds.me.id;
984
- if (typeof content === 'object' &&
985
- 'disappearingMessagesInChat' in content &&
986
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
987
- (0, WABinary_1.isJidGroup)(jid)) {
988
- const { disappearingMessagesInChat } = content;
989
- const value = typeof disappearingMessagesInChat === 'boolean' ?
990
- (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
991
- disappearingMessagesInChat;
992
- await groupToggleEphemeral(jid, value);
869
+
870
+ const isDeleteMsg = 'delete' in content && !!content.delete;
871
+ const isEditMsg = 'edit' in content && !!content.edit;
872
+ const isAiMsg = 'ai' in content && !!content.ai;
873
+
874
+ const additionalAttributes = {};
875
+ const additionalNodes = [];
876
+
877
+ if (isDeleteMsg) {
878
+ const fromMe = content.delete?.fromMe;
879
+ const isGroup = WABinary_1.isJidGroup(content.delete?.remoteJid);
880
+ additionalAttributes.edit = (isGroup && !fromMe) || WABinary_1.isJidNewsLetter(jid) ? '8' : '7';
881
+ } else if (isEditMsg) {
882
+ additionalAttributes.edit = WABinary_1.isJidNewsLetter(jid) ? '3' : '1';
883
+ } else if (isAiMsg) {
884
+ additionalNodes.push({
885
+ attrs: {
886
+ biz_bot: '1'
887
+ }, tag: "bot"
888
+ });
993
889
  }
994
- else {
995
- let mediaHandle;
996
- const { server } = (0, WABinary_1.jidDecode)(jid);
997
- const isGroup = server === 'g.us';
998
- let eph;
999
- if (isGroup) {
1000
- const disappearingNode = await groupQuery(jid, 'get', [
1001
- {
1002
- tag: 'query',
1003
- attrs: { request: 'interactive' }
1004
- }
1005
- ]);
1006
- const group = (0, WABinary_1.getBinaryNodeChild)(disappearingNode, 'group');
1007
- const expiration = (0, WABinary_1.getBinaryNodeChild)(group, 'ephemeral');
1008
- eph = (_a = expiration === null || expiration === void 0 ? void 0 : expiration.attrs) === null || _a === void 0 ? void 0 : _a.expiration;
1009
- }
1010
- const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
1011
- logger,
1012
- userJid,
1013
- ephemeralExpiration: (options.ephemeralExpiration && options.ephemeralExpiration > 0) ? options.ephemeralExpiration : eph,
1014
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
1015
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1016
- fetchOpts: {
1017
- timeout: 3000,
1018
- ...axiosOptions || {}
1019
- },
1020
- logger,
1021
- uploadImage: generateHighQualityLinkPreview
1022
- ? waUploadToServer
1023
- : undefined
1024
- }),
1025
- upload: async (readStream, opts) => {
1026
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
1027
- mediaHandle = up.handle;
1028
- return up;
1029
- },
1030
- mediaCache: config.mediaCache,
1031
- options: config.options,
1032
- messageId: await config.generateMessageIDV2((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id) ?? (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id),
1033
- ...options,
890
+
891
+ await relayMessage(jid, fullMsg.message, {
892
+ messageId: fullMsg.key.id,
893
+ cachedGroupMetadata: options.cachedGroupMetadata,
894
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
895
+ additionalAttributes,
896
+ statusJidList: options.statusJidList
897
+ });
898
+
899
+ if (config.emitOwnEvents) {
900
+ process.nextTick(() => {
901
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1034
902
  });
1035
- const isAiMsg = 'ai' in content && !!content.ai;
1036
- const isPinMsg = 'pin' in content && !!content.pin;
1037
- const isKeepMsg = 'keep' in content && content.keep;
1038
- const isPollMsg = 'poll' in content && !!content.poll;
1039
- const isEditMsg = 'edit' in content && !!content.edit;
1040
- const isDeleteMsg = 'delete' in content && !!content.delete;
1041
- const additionalAttributes = {};
1042
- const additionalNodes = [];
1043
- // required for delete
1044
- if (isDeleteMsg) {
1045
- // if the chat is a group, and I am not the author, then delete the message as an admin
1046
- if (((0, WABinary_1.isJidGroup)((_b = content.delete) === null || _b === void 0 ? void 0 : _b.remoteJid) && !((_c = content.delete) === null || _c === void 0 ? void 0 : _c.fromMe)) || (0, WABinary_1.isJidNewsLetter)(jid)) {
1047
- additionalAttributes.edit = '8';
1048
- }
1049
- else {
1050
- additionalAttributes.edit = '7';
1051
- }
1052
- }
1053
- else if (isEditMsg) {
1054
- additionalAttributes.edit = (0, WABinary_1.isJidNewsLetter)(jid) ? '3' : '1';
1055
- }
1056
- else if (isPinMsg) {
1057
- additionalAttributes.edit = '2';
1058
- }
1059
- else if (isAiMsg) {
1060
- additionalNodes.push({
1061
- attrs: {
1062
- biz_bot: '1'
1063
- },
1064
- tag: 'bot'
1065
- });
1066
- if (options.additionalNodes) {
1067
- additionalNodes.push(...options.additionalNodes);
1068
- }
1069
- }
1070
- if (mediaHandle) {
1071
- additionalAttributes['media_id'] = mediaHandle;
1072
- }
1073
- if ('cachedGroupMetadata' in options) {
1074
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
1075
- }
1076
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, additionalAttributes, statusJidList: options.statusJidList });
1077
- if (config.emitOwnEvents) {
1078
- process.nextTick(() => {
1079
- processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
1080
- });
1081
- }
1082
- return fullMsg;
903
+ }
904
+ return fullMsg;
1083
905
  }
1084
906
  }
1085
- };
907
+ }
1086
908
  };
1087
909
  exports.makeMessagesSocket = makeMessagesSocket;