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