naya-flore 4.7.1

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