riftcore 1.4.5

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