alipclutch-baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +4775 -0
  4. package/WAProto/index.d.ts +55057 -0
  5. package/WAProto/index.js +169661 -0
  6. package/WAProto/index.ts.ts +53473 -0
  7. package/WAProto/p.html +1 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.d.ts +51 -0
  11. package/lib/Defaults/index.js +106 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  13. package/lib/Signal/Group/ciphertext-message.js +15 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  15. package/lib/Signal/Group/group-session-builder.js +64 -0
  16. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  17. package/lib/Signal/Group/group_cipher.js +96 -0
  18. package/lib/Signal/Group/index.d.ts +11 -0
  19. package/lib/Signal/Group/index.js +57 -0
  20. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  21. package/lib/Signal/Group/keyhelper.js +55 -0
  22. package/lib/Signal/Group/queue-job.d.ts +1 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  25. package/lib/Signal/Group/sender-chain-key.js +34 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  33. package/lib/Signal/Group/sender-key-record.js +53 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  35. package/lib/Signal/Group/sender-key-state.js +99 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +3 -0
  39. package/lib/Signal/libsignal.js +174 -0
  40. package/lib/Socket/Client/index.d.ts +2 -0
  41. package/lib/Socket/Client/index.js +18 -0
  42. package/lib/Socket/Client/types.d.ts +16 -0
  43. package/lib/Socket/Client/types.js +13 -0
  44. package/lib/Socket/Client/websocket.d.ts +13 -0
  45. package/lib/Socket/Client/websocket.js +111 -0
  46. package/lib/Socket/business.d.ts +172 -0
  47. package/lib/Socket/business.js +260 -0
  48. package/lib/Socket/chats.d.ts +82 -0
  49. package/lib/Socket/chats.js +893 -0
  50. package/lib/Socket/groups.d.ts +124 -0
  51. package/lib/Socket/groups.js +332 -0
  52. package/lib/Socket/index.d.ts +172 -0
  53. package/lib/Socket/index.js +10 -0
  54. package/lib/Socket/messages-recv.d.ts +161 -0
  55. package/lib/Socket/messages-recv.js +1054 -0
  56. package/lib/Socket/messages-send.d.ts +151 -0
  57. package/lib/Socket/messages-send.js +1021 -0
  58. package/lib/Socket/newsletter.d.ts +136 -0
  59. package/lib/Socket/newsletter.js +294 -0
  60. package/lib/Socket/socket.d.ts +43 -0
  61. package/lib/Socket/socket.js +654 -0
  62. package/lib/Socket/usync.d.ts +36 -0
  63. package/lib/Socket/usync.js +70 -0
  64. package/lib/Store/index.d.ts +2 -0
  65. package/lib/Store/index.js +8 -0
  66. package/lib/Store/make-in-memory-store.d.ts +118 -0
  67. package/lib/Store/make-in-memory-store.js +439 -0
  68. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  69. package/lib/Store/make-ordered-dictionary.js +81 -0
  70. package/lib/Store/object-repository.d.ts +10 -0
  71. package/lib/Store/object-repository.js +27 -0
  72. package/lib/Types/Auth.d.ts +103 -0
  73. package/lib/Types/Auth.js +2 -0
  74. package/lib/Types/Call.d.ts +13 -0
  75. package/lib/Types/Call.js +2 -0
  76. package/lib/Types/Chat.d.ts +109 -0
  77. package/lib/Types/Chat.js +4 -0
  78. package/lib/Types/Contact.d.ts +23 -0
  79. package/lib/Types/Contact.js +2 -0
  80. package/lib/Types/Events.d.ts +199 -0
  81. package/lib/Types/Events.js +2 -0
  82. package/lib/Types/GroupMetadata.d.ts +64 -0
  83. package/lib/Types/GroupMetadata.js +2 -0
  84. package/lib/Types/Label.d.ts +35 -0
  85. package/lib/Types/Label.js +27 -0
  86. package/lib/Types/LabelAssociation.d.ts +29 -0
  87. package/lib/Types/LabelAssociation.js +9 -0
  88. package/lib/Types/Message.d.ts +400 -0
  89. package/lib/Types/Message.js +7 -0
  90. package/lib/Types/Newsletter.d.ts +79 -0
  91. package/lib/Types/Newsletter.js +19 -0
  92. package/lib/Types/Product.d.ts +78 -0
  93. package/lib/Types/Product.js +2 -0
  94. package/lib/Types/Signal.d.ts +57 -0
  95. package/lib/Types/Signal.js +2 -0
  96. package/lib/Types/Socket.d.ts +119 -0
  97. package/lib/Types/Socket.js +2 -0
  98. package/lib/Types/State.d.ts +27 -0
  99. package/lib/Types/State.js +2 -0
  100. package/lib/Types/USync.d.ts +25 -0
  101. package/lib/Types/USync.js +2 -0
  102. package/lib/Types/index.d.ts +64 -0
  103. package/lib/Types/index.js +42 -0
  104. package/lib/Utils/auth-utils.d.ts +18 -0
  105. package/lib/Utils/auth-utils.js +199 -0
  106. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  107. package/lib/Utils/baileys-event-stream.js +63 -0
  108. package/lib/Utils/business.d.ts +22 -0
  109. package/lib/Utils/business.js +234 -0
  110. package/lib/Utils/chat-utils.d.ts +70 -0
  111. package/lib/Utils/chat-utils.js +741 -0
  112. package/lib/Utils/crypto.d.ts +40 -0
  113. package/lib/Utils/crypto.js +193 -0
  114. package/lib/Utils/decode-wa-message.d.ts +35 -0
  115. package/lib/Utils/decode-wa-message.js +207 -0
  116. package/lib/Utils/event-buffer.d.ts +35 -0
  117. package/lib/Utils/event-buffer.js +518 -0
  118. package/lib/Utils/generics.d.ts +89 -0
  119. package/lib/Utils/generics.js +441 -0
  120. package/lib/Utils/history.d.ts +19 -0
  121. package/lib/Utils/history.js +94 -0
  122. package/lib/Utils/index.d.ts +17 -0
  123. package/lib/Utils/index.js +33 -0
  124. package/lib/Utils/link-preview.d.ts +21 -0
  125. package/lib/Utils/link-preview.js +126 -0
  126. package/lib/Utils/logger.d.ts +11 -0
  127. package/lib/Utils/logger.js +7 -0
  128. package/lib/Utils/lt-hash.d.ts +12 -0
  129. package/lib/Utils/lt-hash.js +51 -0
  130. package/lib/Utils/make-mutex.d.ts +7 -0
  131. package/lib/Utils/make-mutex.js +43 -0
  132. package/lib/Utils/messages-media.d.ts +120 -0
  133. package/lib/Utils/messages-media.js +879 -0
  134. package/lib/Utils/messages.d.ts +80 -0
  135. package/lib/Utils/messages.js +1049 -0
  136. package/lib/Utils/noise-handler.d.ts +19 -0
  137. package/lib/Utils/noise-handler.js +150 -0
  138. package/lib/Utils/process-message.d.ts +42 -0
  139. package/lib/Utils/process-message.js +404 -0
  140. package/lib/Utils/signal.d.ts +33 -0
  141. package/lib/Utils/signal.js +153 -0
  142. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  143. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  144. package/lib/Utils/validate-connection.d.ts +10 -0
  145. package/lib/Utils/validate-connection.js +173 -0
  146. package/lib/WABinary/constants.d.ts +27 -0
  147. package/lib/WABinary/constants.js +1303 -0
  148. package/lib/WABinary/decode.d.ts +6 -0
  149. package/lib/WABinary/decode.js +265 -0
  150. package/lib/WABinary/encode.d.ts +2 -0
  151. package/lib/WABinary/encode.js +250 -0
  152. package/lib/WABinary/generic-utils.d.ts +14 -0
  153. package/lib/WABinary/generic-utils.js +110 -0
  154. package/lib/WABinary/index.d.ts +5 -0
  155. package/lib/WABinary/index.js +21 -0
  156. package/lib/WABinary/jid-utils.d.ts +37 -0
  157. package/lib/WABinary/jid-utils.js +85 -0
  158. package/lib/WABinary/types.d.ts +18 -0
  159. package/lib/WABinary/types.js +2 -0
  160. package/lib/WAM/BinaryInfo.d.ts +8 -0
  161. package/lib/WAM/BinaryInfo.js +13 -0
  162. package/lib/WAM/constants.d.ts +38 -0
  163. package/lib/WAM/constants.js +15350 -0
  164. package/lib/WAM/encode.d.ts +2 -0
  165. package/lib/WAM/encode.js +155 -0
  166. package/lib/WAM/index.d.ts +3 -0
  167. package/lib/WAM/index.js +19 -0
  168. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  169. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  170. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  171. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  172. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  173. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  174. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  175. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  176. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  177. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  178. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  179. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  180. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  181. package/lib/WAUSync/Protocols/index.js +20 -0
  182. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  183. package/lib/WAUSync/USyncQuery.js +89 -0
  184. package/lib/WAUSync/USyncUser.d.ts +12 -0
  185. package/lib/WAUSync/USyncUser.js +26 -0
  186. package/lib/WAUSync/index.d.ts +3 -0
  187. package/lib/WAUSync/index.js +19 -0
  188. package/lib/index.d.ts +16 -0
  189. package/lib/index.js +54 -0
  190. package/package.json +68 -0
@@ -0,0 +1,1021 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const crypto_1 = require("crypto");
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Utils_1 = require("../Utils");
13
+ const link_preview_1 = require("../Utils/link-preview");
14
+ const WABinary_1 = require("../WABinary");
15
+ const WAUSync_1 = require("../WAUSync");
16
+ const newsletter_1 = require("./newsletter");
17
+ const makeMessagesSocket = (config) => {
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
19
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
20
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
21
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
22
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
23
+ useClones: false
24
+ });
25
+ let mediaConn;
26
+ const refreshMediaConn = async (forceGet = false) => {
27
+ const media = await mediaConn;
28
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
29
+ mediaConn = (async () => {
30
+ const result = await query({
31
+ tag: 'iq',
32
+ attrs: {
33
+ type: 'set',
34
+ xmlns: 'w:m',
35
+ to: WABinary_1.S_WHATSAPP_NET,
36
+ },
37
+ content: [{ tag: 'media_conn', attrs: {} }]
38
+ });
39
+ const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
40
+ const node = {
41
+ hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
42
+ hostname: attrs.hostname,
43
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
44
+ })),
45
+ auth: mediaConnNode.attrs.auth,
46
+ ttl: +mediaConnNode.attrs.ttl,
47
+ fetchDate: new Date()
48
+ };
49
+ logger.debug('fetched media conn');
50
+ return node;
51
+ })();
52
+ }
53
+ return mediaConn;
54
+ };
55
+ /**
56
+ * generic send receipt function
57
+ * used for receipts of phone call, read, delivery etc.
58
+ * */
59
+ const sendReceipt = async (jid, participant, messageIds, type) => {
60
+ const node = {
61
+ tag: 'receipt',
62
+ attrs: {
63
+ id: messageIds[0],
64
+ },
65
+ };
66
+ const isReadReceipt = type === 'read' || type === 'read-self';
67
+ if (isReadReceipt) {
68
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
69
+ }
70
+ if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
71
+ node.attrs.recipient = jid;
72
+ node.attrs.to = participant;
73
+ }
74
+ else {
75
+ node.attrs.to = jid;
76
+ if (participant) {
77
+ node.attrs.participant = participant;
78
+ }
79
+ }
80
+ if (type) {
81
+ node.attrs.type = (0, WABinary_1.isJidNewsletter)(jid) ? 'read-self' : type;
82
+ }
83
+ const remainingMessageIds = messageIds.slice(1);
84
+ if (remainingMessageIds.length) {
85
+ node.content = [
86
+ {
87
+ tag: 'list',
88
+ attrs: {},
89
+ content: remainingMessageIds.map(id => ({
90
+ tag: 'item',
91
+ attrs: { id }
92
+ }))
93
+ }
94
+ ];
95
+ }
96
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
97
+ await sendNode(node);
98
+ };
99
+ /** Correctly bulk send receipts to multiple chats, participants */
100
+ const sendReceipts = async (keys, type) => {
101
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
102
+ for (const { jid, participant, messageIds } of recps) {
103
+ await sendReceipt(jid, participant, messageIds, type);
104
+ }
105
+ };
106
+ /** Bulk read messages. Keys can be from different chats & participants */
107
+ const readMessages = async (keys) => {
108
+ const privacySettings = await fetchPrivacySettings();
109
+ // based on privacy settings, we have to change the read type
110
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
111
+ await sendReceipts(keys, readType);
112
+ };
113
+ /** Fetch all the devices we've to send a message to */
114
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
115
+ var _a;
116
+ const deviceResults = [];
117
+ if (!useCache) {
118
+ logger.debug('not using cache for devices');
119
+ }
120
+ const toFetch = [];
121
+ jids = Array.from(new Set(jids));
122
+ for (let jid of jids) {
123
+ const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
124
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
125
+ if (useCache) {
126
+ const devices = userDevicesCache.get(user);
127
+ if (devices) {
128
+ deviceResults.push(...devices);
129
+ logger.trace({ user }, 'using cache for devices');
130
+ }
131
+ else {
132
+ toFetch.push(jid);
133
+ }
134
+ }
135
+ else {
136
+ toFetch.push(jid);
137
+ }
138
+ }
139
+ if (!toFetch.length) {
140
+ return deviceResults;
141
+ }
142
+ const query = new WAUSync_1.USyncQuery()
143
+ .withContext('message')
144
+ .withDeviceProtocol();
145
+ for (const jid of toFetch) {
146
+ query.withUser(new WAUSync_1.USyncUser().withId(jid));
147
+ }
148
+ const result = await sock.executeUSyncQuery(query);
149
+ if (result) {
150
+ const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
151
+ const deviceMap = {};
152
+ for (const item of extracted) {
153
+ deviceMap[item.user] = deviceMap[item.user] || [];
154
+ deviceMap[item.user].push(item);
155
+ deviceResults.push(item);
156
+ }
157
+ for (const key in deviceMap) {
158
+ userDevicesCache.set(key, deviceMap[key]);
159
+ }
160
+ }
161
+ return deviceResults;
162
+ };
163
+ const assertSessions = async (jids, force) => {
164
+ let didFetchNewSession = false;
165
+ let jidsRequiringFetch = [];
166
+ if (force) {
167
+ jidsRequiringFetch = jids;
168
+ }
169
+ else {
170
+ const addrs = jids.map(jid => (signalRepository
171
+ .jidToSignalProtocolAddress(jid)));
172
+ const sessions = await authState.keys.get('session', addrs);
173
+ for (const jid of jids) {
174
+ const signalId = signalRepository
175
+ .jidToSignalProtocolAddress(jid);
176
+ if (!sessions[signalId]) {
177
+ jidsRequiringFetch.push(jid);
178
+ }
179
+ }
180
+ }
181
+ if (jidsRequiringFetch.length) {
182
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
183
+ const result = await query({
184
+ tag: 'iq',
185
+ attrs: {
186
+ xmlns: 'encrypt',
187
+ type: 'get',
188
+ to: WABinary_1.S_WHATSAPP_NET,
189
+ },
190
+ content: [
191
+ {
192
+ tag: 'key',
193
+ attrs: {},
194
+ content: jidsRequiringFetch.map(jid => ({
195
+ tag: 'user',
196
+ attrs: { jid },
197
+ }))
198
+ }
199
+ ]
200
+ });
201
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
202
+ didFetchNewSession = true;
203
+ }
204
+ return didFetchNewSession;
205
+ };
206
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
207
+ var _a;
208
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
209
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
210
+ throw new boom_1.Boom('Not authenticated');
211
+ }
212
+ const protocolMessage = {
213
+ protocolMessage: {
214
+ peerDataOperationRequestMessage: pdoMessage,
215
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
216
+ }
217
+ };
218
+ const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
219
+ const msgId = await relayMessage(meJid, protocolMessage, {
220
+ additionalAttributes: {
221
+ category: 'peer',
222
+ // eslint-disable-next-line camelcase
223
+ push_priority: 'high_force',
224
+ },
225
+ });
226
+ return msgId;
227
+ };
228
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
229
+ let patched = await patchMessageBeforeSending(message, jids);
230
+ if (!Array.isArray(patched)) {
231
+ patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched];
232
+ }
233
+ let shouldIncludeDeviceIdentity = false;
234
+ const nodes = await Promise.all(patched.map(async (patchedMessageWithJid) => {
235
+ const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid;
236
+ if (!jid) {
237
+ return {};
238
+ }
239
+ const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
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 };
261
+ };
262
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
263
+ var _a;
264
+ const meId = authState.creds.me.id;
265
+ let shouldIncludeDeviceIdentity = false;
266
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
267
+ const statusJid = 'status@broadcast';
268
+ const isGroup = server === 'g.us';
269
+ const isNewsletter = server === 'newsletter';
270
+ const isStatus = jid === statusJid;
271
+ const isLid = server === 'lid';
272
+ msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
273
+ useUserDevicesCache = useUserDevicesCache !== false;
274
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
275
+ const participants = [];
276
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
277
+ const binaryNodeContent = [];
278
+ const devices = [];
279
+ const meMsg = {
280
+ deviceSentMessage: {
281
+ destinationJid,
282
+ message
283
+ },
284
+ messageContextInfo: message.messageContextInfo
285
+ };
286
+ const extraAttrs = {};
287
+ if (participant) {
288
+ // when the retry request is not for a group
289
+ // only send to the specific device that asked for a retry
290
+ // otherwise the message is sent out to every device that should be a recipient
291
+ if (!isGroup && !isStatus) {
292
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
293
+ }
294
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
295
+ devices.push({ user, device });
296
+ }
297
+ await authState.keys.transaction(async () => {
298
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
299
+ const mediaType = getMediaType(message);
300
+ if (mediaType) {
301
+ extraAttrs['mediatype'] = mediaType;
302
+ }
303
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
304
+ extraAttrs['decrypt-fail'] = 'hide';
305
+ }
306
+ if (isGroup || isStatus) {
307
+ const [groupData, senderKeyMap] = await Promise.all([
308
+ (async () => {
309
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
310
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
311
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
312
+ }
313
+ else if (!isStatus) {
314
+ groupData = await groupMetadata(jid);
315
+ }
316
+ return groupData;
317
+ })(),
318
+ (async () => {
319
+ if (!participant && !isStatus) {
320
+ const result = await authState.keys.get('sender-key-memory', [jid]);
321
+ return result[jid] || {};
322
+ }
323
+ return {};
324
+ })()
325
+ ]);
326
+ if (!participant) {
327
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
328
+ if (isStatus && statusJidList) {
329
+ participantsList.push(...statusJidList);
330
+ }
331
+ if (!isStatus) {
332
+ additionalAttributes = {
333
+ ...additionalAttributes,
334
+ // eslint-disable-next-line camelcase
335
+ addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
336
+ };
337
+ }
338
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
339
+ devices.push(...additionalDevices);
340
+ }
341
+ const patched = await patchMessageBeforeSending(message);
342
+ if (Array.isArray(patched)) {
343
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
344
+ }
345
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
346
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
347
+ group: destinationJid,
348
+ data: bytes,
349
+ meId,
350
+ });
351
+ const senderKeyJids = [];
352
+ // ensure a connection is established with every device
353
+ for (const { user, device } of devices) {
354
+ const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
355
+ if (!senderKeyMap[jid] || !!participant) {
356
+ senderKeyJids.push(jid);
357
+ // store that this person has had the sender keys sent to them
358
+ senderKeyMap[jid] = true;
359
+ }
360
+ }
361
+ // if there are some participants with whom the session has not been established
362
+ // if there are, we re-send the senderkey
363
+ if (senderKeyJids.length) {
364
+ logger.debug({ senderKeyJids }, 'sending new sender key');
365
+ const senderKeyMsg = {
366
+ senderKeyDistributionMessage: {
367
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
368
+ groupId: destinationJid
369
+ }
370
+ };
371
+ await assertSessions(senderKeyJids, false);
372
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
373
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
374
+ participants.push(...result.nodes);
375
+ }
376
+ binaryNodeContent.push({
377
+ tag: 'enc',
378
+ attrs: { v: '2', type: 'skmsg' },
379
+ content: ciphertext
380
+ });
381
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
382
+ }
383
+ else if (isNewsletter) {
384
+ // Message edit
385
+ if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
386
+ msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
387
+ message = message.protocolMessage.editedMessage;
388
+ }
389
+ // Message delete
390
+ if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
391
+ msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
392
+ message = {};
393
+ }
394
+ const patched = await patchMessageBeforeSending(message, []);
395
+ if (Array.isArray(patched)) {
396
+ throw new boom_1.Boom('Per-jid patching is not supported in channel');
397
+ }
398
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
399
+ binaryNodeContent.push({
400
+ tag: 'plaintext',
401
+ attrs: mediaType ? { mediatype: mediaType } : {},
402
+ content: bytes
403
+ });
404
+ }
405
+ else {
406
+ const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
407
+ if (!participant) {
408
+ devices.push({ user });
409
+ if (user !== meUser) {
410
+ devices.push({ user: meUser });
411
+ }
412
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
413
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
414
+ devices.push(...additionalDevices);
415
+ }
416
+ }
417
+ const allJids = [];
418
+ const meJids = [];
419
+ const otherJids = [];
420
+ for (const { user, device } of devices) {
421
+ const isMe = user === meUser;
422
+ const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_g = (_f = authState.creds) === null || _f === void 0 ? void 0 : _f.me) === null || _g === void 0 ? void 0 : _g.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
423
+ if (isMe) {
424
+ meJids.push(jid);
425
+ }
426
+ else {
427
+ otherJids.push(jid);
428
+ }
429
+ allJids.push(jid);
430
+ }
431
+ await assertSessions(allJids, false);
432
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
433
+ createParticipantNodes(meJids, meMsg, extraAttrs),
434
+ createParticipantNodes(otherJids, message, extraAttrs)
435
+ ]);
436
+ participants.push(...meNodes);
437
+ participants.push(...otherNodes);
438
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
439
+ }
440
+ if (participants.length) {
441
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
442
+ const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
443
+ if (peerNode) {
444
+ binaryNodeContent.push(peerNode); // push only enc
445
+ }
446
+ }
447
+ else {
448
+ binaryNodeContent.push({
449
+ tag: 'participants',
450
+ attrs: {},
451
+ content: participants
452
+ });
453
+ }
454
+ }
455
+ const stanza = {
456
+ tag: 'message',
457
+ attrs: {
458
+ id: msgId,
459
+ type: isNewsletter ? getTypeMessage(message) : 'text',
460
+ ...(additionalAttributes || {})
461
+ },
462
+ content: binaryNodeContent
463
+ };
464
+ // if the participant to send to is explicitly specified (generally retry recp)
465
+ // ensure the message is only sent to that person
466
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
467
+ if (participant) {
468
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
469
+ stanza.attrs.to = destinationJid;
470
+ stanza.attrs.participant = participant.jid;
471
+ }
472
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
473
+ stanza.attrs.to = participant.jid;
474
+ stanza.attrs.recipient = destinationJid;
475
+ }
476
+ else {
477
+ stanza.attrs.to = participant.jid;
478
+ }
479
+ }
480
+ else {
481
+ stanza.attrs.to = destinationJid;
482
+ }
483
+ if (shouldIncludeDeviceIdentity) {
484
+ stanza.content.push({
485
+ tag: 'device-identity',
486
+ attrs: {},
487
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
488
+ });
489
+ logger.debug({ jid }, 'adding device identity');
490
+ }
491
+ if (additionalNodes && additionalNodes.length > 0) {
492
+ stanza.content.push(...additionalNodes);
493
+ }
494
+ const content = (0, Utils_1.normalizeMessageContent)(message);
495
+ const contentType = (0, Utils_1.getContentType)(content);
496
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
497
+ contentType === 'buttonsMessage' ||
498
+ contentType === 'listMessage')) {
499
+ const bizNode = { tag: 'biz', attrs: {} };
500
+ if ((((_l = (_k = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _k === void 0 ? void 0 : _k.message) === null || _l === void 0 ? void 0 : _l.interactiveMessage) || ((_o = (_m = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _m === void 0 ? void 0 : _m.message) === null || _o === void 0 ? void 0 : _o.interactiveMessage) || ((_q = (_p = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _p === void 0 ? void 0 : _p.message) === null || _q === void 0 ? void 0 : _q.interactiveMessage) || (message === null || message === void 0 ? void 0 : message.interactiveMessage)) || (((_s = (_r = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _r === void 0 ? void 0 : _r.message) === null || _s === void 0 ? void 0 : _s.buttonsMessage) || ((_u = (_t = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _t === void 0 ? void 0 : _t.message) === null || _u === void 0 ? void 0 : _u.buttonsMessage) || ((_w = (_v = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _v === void 0 ? void 0 : _v.message) === null || _w === void 0 ? void 0 : _w.buttonsMessage) || (message === null || message === void 0 ? void 0 : message.buttonsMessage))) {
501
+ bizNode.content = [{
502
+ tag: 'interactive',
503
+ attrs: {
504
+ type: 'native_flow',
505
+ v: '1'
506
+ },
507
+ content: [{
508
+ tag: 'native_flow',
509
+ attrs: { v: '9', name: 'mixed' }
510
+ }]
511
+ }];
512
+ }
513
+ else if (message === null || message === void 0 ? void 0 : message.listMessage) {
514
+ // list message only support in private chat
515
+ bizNode.content = [{
516
+ tag: 'list',
517
+ attrs: {
518
+ type: 'product_list',
519
+ v: '2'
520
+ }
521
+ }];
522
+ }
523
+ stanza.content.push(bizNode);
524
+ }
525
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
526
+ await sendNode(stanza);
527
+ });
528
+ return msgId;
529
+ };
530
+ const getTypeMessage = (msg) => {
531
+ if (msg.viewOnceMessage) {
532
+ return getTypeMessage(msg.viewOnceMessage.message);
533
+ }
534
+ else if (msg.viewOnceMessageV2) {
535
+ return getTypeMessage(msg.viewOnceMessageV2.message);
536
+ }
537
+ else if (msg.viewOnceMessageV2Extension) {
538
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
539
+ }
540
+ else if (msg.ephemeralMessage) {
541
+ return getTypeMessage(msg.ephemeralMessage.message);
542
+ }
543
+ else if (msg.documentWithCaptionMessage) {
544
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
545
+ }
546
+ else if (msg.reactionMessage) {
547
+ return 'reaction';
548
+ }
549
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
550
+ return 'poll';
551
+ }
552
+ else if (getMediaType(msg)) {
553
+ return 'media';
554
+ }
555
+ else {
556
+ return 'text';
557
+ }
558
+ };
559
+ const getMediaType = (message) => {
560
+ if (message.imageMessage) {
561
+ return 'image';
562
+ }
563
+ else if (message.videoMessage) {
564
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
565
+ }
566
+ else if (message.audioMessage) {
567
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
568
+ }
569
+ else if (message.contactMessage) {
570
+ return 'vcard';
571
+ }
572
+ else if (message.documentMessage) {
573
+ return 'document';
574
+ }
575
+ else if (message.contactsArrayMessage) {
576
+ return 'contact_array';
577
+ }
578
+ else if (message.liveLocationMessage) {
579
+ return 'livelocation';
580
+ }
581
+ else if (message.stickerMessage) {
582
+ return 'sticker';
583
+ }
584
+ else if (message.listMessage) {
585
+ return 'list';
586
+ }
587
+ else if (message.listResponseMessage) {
588
+ return 'list_response';
589
+ }
590
+ else if (message.buttonsResponseMessage) {
591
+ return 'buttons_response';
592
+ }
593
+ else if (message.orderMessage) {
594
+ return 'order';
595
+ }
596
+ else if (message.productMessage) {
597
+ return 'product';
598
+ }
599
+ else if (message.interactiveResponseMessage) {
600
+ return 'native_flow_response';
601
+ }
602
+ else if (message.groupInviteMessage) {
603
+ return 'url';
604
+ }
605
+ };
606
+ const getPrivacyTokens = async (jids) => {
607
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
608
+ const result = await query({
609
+ tag: 'iq',
610
+ attrs: {
611
+ to: WABinary_1.S_WHATSAPP_NET,
612
+ type: 'set',
613
+ xmlns: 'privacy'
614
+ },
615
+ content: [
616
+ {
617
+ tag: 'tokens',
618
+ attrs: {},
619
+ content: jids.map(jid => ({
620
+ tag: 'token',
621
+ attrs: {
622
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
623
+ t,
624
+ type: 'trusted_contact'
625
+ }
626
+ }))
627
+ }
628
+ ]
629
+ });
630
+ return result;
631
+ };
632
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
633
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
634
+ return {
635
+ ...sock,
636
+ getPrivacyTokens,
637
+ assertSessions,
638
+ relayMessage,
639
+ sendReceipt,
640
+ sendReceipts,
641
+ readMessages,
642
+ refreshMediaConn,
643
+ waUploadToServer,
644
+ fetchPrivacySettings,
645
+ getUSyncDevices,
646
+ createParticipantNodes,
647
+ sendPeerDataOperationMessage,
648
+ updateMediaMessage: async (message) => {
649
+ const content = (0, Utils_1.assertMediaContent)(message.message);
650
+ const mediaKey = content.mediaKey;
651
+ const meId = authState.creds.me.id;
652
+ const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
653
+ let error = undefined;
654
+ await Promise.all([
655
+ sendNode(node),
656
+ waitForMsgMediaUpdate(async (update) => {
657
+ const result = update.find(c => c.key.id === message.key.id);
658
+ if (result) {
659
+ if (result.error) {
660
+ error = result.error;
661
+ }
662
+ else {
663
+ try {
664
+ const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
665
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
666
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
667
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
668
+ }
669
+ content.directPath = media.directPath;
670
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
671
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
672
+ }
673
+ catch (err) {
674
+ error = err;
675
+ }
676
+ }
677
+ return true;
678
+ }
679
+ })
680
+ ]);
681
+ if (error) {
682
+ throw error;
683
+ }
684
+ ev.emit('messages.update', [
685
+ { key: message.key, update: { message: message.message } }
686
+ ]);
687
+ return message;
688
+ },
689
+ sendStatusMentions: async (content, jids = []) => {
690
+ const userJid = WABinary_1.jidNormalizedUser(authState.creds.me.id)
691
+ let allUsers = new Set()
692
+ allUsers.add(userJid)
693
+
694
+ for (const id of jids) {
695
+ const isGroup = WABinary_1.isJidGroup(id)
696
+ const isPrivate = WABinary_1.isJidUser(id)
697
+
698
+ if (isGroup) {
699
+ try {
700
+ const metadata = await cachedGroupMetadata(id) || await groupMetadata(id)
701
+ const participants = metadata.participants.map(p => WABinary_1.jidNormalizedUser(p.id))
702
+ participants.forEach(jid => allUsers.add(jid))
703
+ } catch (error) {
704
+ logger.error(`Error getting metadata for group ${id}: ${error}`)
705
+ }
706
+ } else if (isPrivate) {
707
+ allUsers.add(WABinary_1.jidNormalizedUser(id))
708
+ }
709
+ }
710
+
711
+ const uniqueUsers = Array.from(allUsers)
712
+ const getRandomHexColor = () => "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")
713
+
714
+ const isMedia = content.image || content.video || content.audio
715
+ const isAudio = !!content.audio
716
+
717
+ const messageContent = { ...content }
718
+
719
+ if (isMedia && !isAudio) {
720
+ if (messageContent.text) {
721
+ messageContent.caption = messageContent.text
722
+
723
+ delete messageContent.text
724
+ }
725
+
726
+ delete messageContent.ptt
727
+ delete messageContent.font
728
+ delete messageContent.backgroundColor
729
+ delete messageContent.textColor
730
+ }
731
+
732
+ if (isAudio) {
733
+ delete messageContent.text
734
+ delete messageContent.caption
735
+ delete messageContent.font
736
+ delete messageContent.textColor
737
+ }
738
+
739
+ const font = !isMedia ? (content.font || Math.floor(Math.random() * 9)) : undefined
740
+ const textColor = !isMedia ? (content.textColor || getRandomHexColor()) : undefined
741
+ const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor || getRandomHexColor()) : undefined
742
+ const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined
743
+
744
+ let msg
745
+ let mediaHandle
746
+ try {
747
+ msg = await Utils_1.generateWAMessage(WABinary_1.STORIES_JID, messageContent, {
748
+ logger,
749
+ userJid,
750
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
751
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
752
+ fetchOpts: { timeout: 3000, ...axiosOptions || {} },
753
+ logger,
754
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
755
+ }),
756
+ upload: async (encFilePath, opts) => {
757
+ const up = await waUploadToServer(encFilePath, { ...opts })
758
+ mediaHandle = up.handle
759
+ return up
760
+ },
761
+ mediaCache: config.mediaCache,
762
+ options: config.options,
763
+ font,
764
+ textColor,
765
+ backgroundColor,
766
+ ptt
767
+ })
768
+ } catch (error) {
769
+ logger.error(`Error generating message: ${error}`)
770
+ throw error
771
+ }
772
+
773
+ await relayMessage(WABinary_1.STORIES_JID, msg.message, {
774
+ messageId: msg.key.id,
775
+ statusJidList: uniqueUsers,
776
+ additionalNodes: [
777
+ {
778
+ tag: 'meta',
779
+ attrs: {},
780
+ content: [
781
+ {
782
+ tag: 'mentioned_users',
783
+ attrs: {},
784
+ content: jids.map(jid => ({
785
+ tag: 'to',
786
+ attrs: { jid: WABinary_1.jidNormalizedUser(jid) }
787
+ }))
788
+ }]
789
+ }]
790
+ })
791
+
792
+ for (const id of jids) {
793
+ try {
794
+ const normalizedId = WABinary_1.jidNormalizedUser(id)
795
+ const isPrivate = WABinary_1.isJidUser(normalizedId)
796
+ const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage'
797
+
798
+ const protocolMessage = {
799
+ [type]: {
800
+ message: {
801
+ protocolMessage: {
802
+ key: msg.key,
803
+ type: 25
804
+ }
805
+ }
806
+ },
807
+ messageContextInfo: {
808
+ messageSecret: crypto_1.randomBytes(32)
809
+ }
810
+ }
811
+
812
+ const statusMsg = await Utils_1.generateWAMessageFromContent(normalizedId,
813
+ protocolMessage,
814
+ {}
815
+ )
816
+
817
+ await relayMessage(
818
+ normalizedId,
819
+ statusMsg.message,
820
+ {
821
+ additionalNodes: [{
822
+ tag: 'meta',
823
+ attrs: isPrivate ?
824
+ { is_status_mention: 'true' } :
825
+ { is_group_status_mention: 'true' }
826
+ }]
827
+ }
828
+ )
829
+
830
+ await Utils_1.delay(2000)
831
+ } catch (error) {
832
+ logger.error(`Error sending to ${id}: ${error}`)
833
+ }
834
+ }
835
+
836
+ return msg
837
+ },
838
+ sendMessage: async (jid, content, options = {}) => {
839
+ var _a, _b, _c;
840
+ const userJid = authState.creds.me.id;
841
+ if (!options.ephemeralExpiration) {
842
+ if ((0, WABinary_1.isJidGroup)(jid)) {
843
+ const groups = await sock.groupQuery(jid, 'get', [{
844
+ tag: 'query',
845
+ attrs: {
846
+ request: 'interactive'
847
+ }
848
+ }]);
849
+ const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
850
+ const expiration = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(metadata, 'ephemeral')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.expiration) || 0;
851
+ options.ephemeralExpiration = expiration;
852
+ }
853
+ }
854
+ if (typeof content === 'object' &&
855
+ 'disappearingMessagesInChat' in content &&
856
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
857
+ (0, WABinary_1.isJidGroup)(jid)) {
858
+ const { disappearingMessagesInChat } = content;
859
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
860
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
861
+ disappearingMessagesInChat;
862
+ await groupToggleEphemeral(jid, value);
863
+ }
864
+ if (typeof content === 'object' && 'album' in content && content.album) {
865
+ const { album, caption } = content;
866
+ if (caption && !album[0].caption) {
867
+ album[0].caption = caption;
868
+ }
869
+ let mediaHandle;
870
+ let mediaMsg;
871
+ const albumMsg = (0, Utils_1.generateWAMessageFromContent)(jid, {
872
+ albumMessage: {
873
+ expectedImageCount: album.filter(item => 'image' in item).length,
874
+ expectedVideoCount: album.filter(item => 'video' in item).length
875
+ }
876
+ }, { userJid, ...options });
877
+ await relayMessage(jid, albumMsg.message, {
878
+ messageId: albumMsg.key.id
879
+ });
880
+ for (const i in album) {
881
+ const media = album[i];
882
+ if ('image' in media) {
883
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
884
+ image: media.image,
885
+ ...(media.caption ? { caption: media.caption } : {}),
886
+ ...options
887
+ }, {
888
+ userJid,
889
+ upload: async (readStream, opts) => {
890
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
891
+ mediaHandle = up.handle;
892
+ return up;
893
+ },
894
+ ...options,
895
+ });
896
+ }
897
+ else if ('video' in media) {
898
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
899
+ video: media.video,
900
+ ...(media.caption ? { caption: media.caption } : {}),
901
+ ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
902
+ ...options
903
+ }, {
904
+ userJid,
905
+ upload: async (readStream, opts) => {
906
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
907
+ mediaHandle = up.handle;
908
+ return up;
909
+ },
910
+ ...options,
911
+ });
912
+ }
913
+ if (mediaMsg) {
914
+ mediaMsg.message.messageContextInfo = {
915
+ messageSecret: (0, crypto_1.randomBytes)(32),
916
+ messageAssociation: {
917
+ associationType: 1,
918
+ parentMessageKey: albumMsg.key
919
+ }
920
+ };
921
+ }
922
+ await relayMessage(jid, mediaMsg.message, {
923
+ messageId: mediaMsg.key.id
924
+ });
925
+ await new Promise(resolve => setTimeout(resolve, 800));
926
+ }
927
+ return albumMsg;
928
+ }
929
+ else {
930
+ let mediaHandle;
931
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
932
+ logger,
933
+ userJid,
934
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
935
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
936
+ fetchOpts: {
937
+ timeout: 3000,
938
+ ...axiosOptions || {}
939
+ },
940
+ logger,
941
+ uploadImage: generateHighQualityLinkPreview
942
+ ? waUploadToServer
943
+ : undefined
944
+ }),
945
+ getProfilePicUrl: sock.profilePictureUrl,
946
+ upload: async (readStream, opts) => {
947
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
948
+ mediaHandle = up.handle;
949
+ return up;
950
+ },
951
+ mediaCache: config.mediaCache,
952
+ options: config.options,
953
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
954
+ ...options,
955
+ });
956
+ const isDeleteMsg = 'delete' in content && !!content.delete;
957
+ const isEditMsg = 'edit' in content && !!content.edit;
958
+ const isPinMsg = 'pin' in content && !!content.pin;
959
+ const isKeepMsg = 'keep' in content && content.keep;
960
+ const isPollMessage = 'poll' in content && !!content.poll;
961
+ const isAiMsg = 'ai' in content && !!content.ai;
962
+ const additionalAttributes = {};
963
+ const additionalNodes = [];
964
+ // required for delete
965
+ if (isDeleteMsg) {
966
+ // if the chat is a group, and I am not the author, then delete the message as an admin
967
+ if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
968
+ additionalAttributes.edit = '8';
969
+ }
970
+ else {
971
+ additionalAttributes.edit = '7';
972
+ }
973
+ // required for edit message
974
+ }
975
+ else if (isEditMsg) {
976
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
977
+ // required for pin message
978
+ }
979
+ else if (isPinMsg) {
980
+ additionalAttributes.edit = '2';
981
+ // required for keep message
982
+ }
983
+ else if (isKeepMsg) {
984
+ additionalAttributes.edit = '6';
985
+ // required for polling message
986
+ }
987
+ else if (isPollMessage) {
988
+ additionalNodes.push({
989
+ tag: 'meta',
990
+ attrs: {
991
+ polltype: 'creation'
992
+ },
993
+ });
994
+ // required to display AI icon on message
995
+ }
996
+ else if (isAiMsg) {
997
+ additionalNodes.push({
998
+ attrs: {
999
+ biz_bot: '1'
1000
+ },
1001
+ tag: "bot"
1002
+ });
1003
+ }
1004
+ if (mediaHandle) {
1005
+ additionalAttributes['media_id'] = mediaHandle;
1006
+ }
1007
+ if ('cachedGroupMetadata' in options) {
1008
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
1009
+ }
1010
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
1011
+ if (config.emitOwnEvents) {
1012
+ process.nextTick(() => {
1013
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
1014
+ });
1015
+ }
1016
+ return fullMsg;
1017
+ }
1018
+ }
1019
+ };
1020
+ };
1021
+ exports.makeMessagesSocket = makeMessagesSocket;